body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def _canonicalize_experiment(exp):
'Sorts the repeated fields of an Experiment message.'
exp.hparam_infos.sort(key=operator.attrgetter('name'))
exp.metric_infos.sort(key=operator.attrgetter('name.group', 'name.tag'))
for hparam_info in exp.hparam_infos:
if hparam_info.HasField('domain_discrete')... | -8,215,901,732,217,587,000 | Sorts the repeated fields of an Experiment message. | tensorboard/plugins/hparams/backend_context_test.py | _canonicalize_experiment | aryaman4/tensorboard | python | def _canonicalize_experiment(exp):
exp.hparam_infos.sort(key=operator.attrgetter('name'))
exp.metric_infos.sort(key=operator.attrgetter('name.group', 'name.tag'))
for hparam_info in exp.hparam_infos:
if hparam_info.HasField('domain_discrete'):
hparam_info.domain_discrete.values.sort... |
def __init__(self, request_id=None, return_code=None, return_message=None, total_rows=None, process_list=None):
'ResumeProcessesResponse - a model defined in Swagger'
self._request_id = None
self._return_code = None
self._return_message = None
self._total_rows = None
self._process_list = None
... | 2,894,216,753,114,153,500 | ResumeProcessesResponse - a model defined in Swagger | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | __init__ | NaverCloudPlatform/ncloud-sdk-python | python | def __init__(self, request_id=None, return_code=None, return_message=None, total_rows=None, process_list=None):
self._request_id = None
self._return_code = None
self._return_message = None
self._total_rows = None
self._process_list = None
self.discriminator = None
if (request_id is not ... |
@property
def request_id(self):
'Gets the request_id of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The request_id of this ResumeProcessesResponse. # noqa: E501\n :rtype: str\n '
return self._request_id | -1,183,890,875,359,341,300 | Gets the request_id of this ResumeProcessesResponse. # noqa: E501
:return: The request_id of this ResumeProcessesResponse. # noqa: E501
:rtype: str | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | request_id | NaverCloudPlatform/ncloud-sdk-python | python | @property
def request_id(self):
'Gets the request_id of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The request_id of this ResumeProcessesResponse. # noqa: E501\n :rtype: str\n '
return self._request_id |
@request_id.setter
def request_id(self, request_id):
'Sets the request_id of this ResumeProcessesResponse.\n\n\n :param request_id: The request_id of this ResumeProcessesResponse. # noqa: E501\n :type: str\n '
self._request_id = request_id | -8,333,445,982,014,422,000 | Sets the request_id of this ResumeProcessesResponse.
:param request_id: The request_id of this ResumeProcessesResponse. # noqa: E501
:type: str | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | request_id | NaverCloudPlatform/ncloud-sdk-python | python | @request_id.setter
def request_id(self, request_id):
'Sets the request_id of this ResumeProcessesResponse.\n\n\n :param request_id: The request_id of this ResumeProcessesResponse. # noqa: E501\n :type: str\n '
self._request_id = request_id |
@property
def return_code(self):
'Gets the return_code of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The return_code of this ResumeProcessesResponse. # noqa: E501\n :rtype: str\n '
return self._return_code | 5,002,841,652,600,358,000 | Gets the return_code of this ResumeProcessesResponse. # noqa: E501
:return: The return_code of this ResumeProcessesResponse. # noqa: E501
:rtype: str | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | return_code | NaverCloudPlatform/ncloud-sdk-python | python | @property
def return_code(self):
'Gets the return_code of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The return_code of this ResumeProcessesResponse. # noqa: E501\n :rtype: str\n '
return self._return_code |
@return_code.setter
def return_code(self, return_code):
'Sets the return_code of this ResumeProcessesResponse.\n\n\n :param return_code: The return_code of this ResumeProcessesResponse. # noqa: E501\n :type: str\n '
self._return_code = return_code | 1,679,400,526,842,856,200 | Sets the return_code of this ResumeProcessesResponse.
:param return_code: The return_code of this ResumeProcessesResponse. # noqa: E501
:type: str | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | return_code | NaverCloudPlatform/ncloud-sdk-python | python | @return_code.setter
def return_code(self, return_code):
'Sets the return_code of this ResumeProcessesResponse.\n\n\n :param return_code: The return_code of this ResumeProcessesResponse. # noqa: E501\n :type: str\n '
self._return_code = return_code |
@property
def return_message(self):
'Gets the return_message of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The return_message of this ResumeProcessesResponse. # noqa: E501\n :rtype: str\n '
return self._return_message | -5,566,010,396,584,428,000 | Gets the return_message of this ResumeProcessesResponse. # noqa: E501
:return: The return_message of this ResumeProcessesResponse. # noqa: E501
:rtype: str | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | return_message | NaverCloudPlatform/ncloud-sdk-python | python | @property
def return_message(self):
'Gets the return_message of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The return_message of this ResumeProcessesResponse. # noqa: E501\n :rtype: str\n '
return self._return_message |
@return_message.setter
def return_message(self, return_message):
'Sets the return_message of this ResumeProcessesResponse.\n\n\n :param return_message: The return_message of this ResumeProcessesResponse. # noqa: E501\n :type: str\n '
self._return_message = return_message | 8,625,067,697,036,527,000 | Sets the return_message of this ResumeProcessesResponse.
:param return_message: The return_message of this ResumeProcessesResponse. # noqa: E501
:type: str | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | return_message | NaverCloudPlatform/ncloud-sdk-python | python | @return_message.setter
def return_message(self, return_message):
'Sets the return_message of this ResumeProcessesResponse.\n\n\n :param return_message: The return_message of this ResumeProcessesResponse. # noqa: E501\n :type: str\n '
self._return_message = return_message |
@property
def total_rows(self):
'Gets the total_rows of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The total_rows of this ResumeProcessesResponse. # noqa: E501\n :rtype: int\n '
return self._total_rows | 8,620,200,007,391,291,000 | Gets the total_rows of this ResumeProcessesResponse. # noqa: E501
:return: The total_rows of this ResumeProcessesResponse. # noqa: E501
:rtype: int | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | total_rows | NaverCloudPlatform/ncloud-sdk-python | python | @property
def total_rows(self):
'Gets the total_rows of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The total_rows of this ResumeProcessesResponse. # noqa: E501\n :rtype: int\n '
return self._total_rows |
@total_rows.setter
def total_rows(self, total_rows):
'Sets the total_rows of this ResumeProcessesResponse.\n\n\n :param total_rows: The total_rows of this ResumeProcessesResponse. # noqa: E501\n :type: int\n '
self._total_rows = total_rows | -3,135,320,641,953,777,000 | Sets the total_rows of this ResumeProcessesResponse.
:param total_rows: The total_rows of this ResumeProcessesResponse. # noqa: E501
:type: int | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | total_rows | NaverCloudPlatform/ncloud-sdk-python | python | @total_rows.setter
def total_rows(self, total_rows):
'Sets the total_rows of this ResumeProcessesResponse.\n\n\n :param total_rows: The total_rows of this ResumeProcessesResponse. # noqa: E501\n :type: int\n '
self._total_rows = total_rows |
@property
def process_list(self):
'Gets the process_list of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The process_list of this ResumeProcessesResponse. # noqa: E501\n :rtype: list[Process]\n '
return self._process_list | 3,722,111,833,422,468,600 | Gets the process_list of this ResumeProcessesResponse. # noqa: E501
:return: The process_list of this ResumeProcessesResponse. # noqa: E501
:rtype: list[Process] | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | process_list | NaverCloudPlatform/ncloud-sdk-python | python | @property
def process_list(self):
'Gets the process_list of this ResumeProcessesResponse. # noqa: E501\n\n\n :return: The process_list of this ResumeProcessesResponse. # noqa: E501\n :rtype: list[Process]\n '
return self._process_list |
@process_list.setter
def process_list(self, process_list):
'Sets the process_list of this ResumeProcessesResponse.\n\n\n :param process_list: The process_list of this ResumeProcessesResponse. # noqa: E501\n :type: list[Process]\n '
self._process_list = process_list | 6,121,710,043,043,419,000 | Sets the process_list of this ResumeProcessesResponse.
:param process_list: The process_list of this ResumeProcessesResponse. # noqa: E501
:type: list[Process] | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | process_list | NaverCloudPlatform/ncloud-sdk-python | python | @process_list.setter
def process_list(self, process_list):
'Sets the process_list of this ResumeProcessesResponse.\n\n\n :param process_list: The process_list of this ResumeProcessesResponse. # noqa: E501\n :type: list[Process]\n '
self._process_list = process_list |
def to_dict(self):
'Returns the model properties as a dict'
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
e... | -2,772,352,302,133,010,000 | Returns the model properties as a dict | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | to_dict | NaverCloudPlatform/ncloud-sdk-python | python | def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
... |
def to_str(self):
'Returns the string representation of the model'
return pprint.pformat(self.to_dict()) | 5,849,158,643,760,736,000 | Returns the string representation of the model | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | to_str | NaverCloudPlatform/ncloud-sdk-python | python | def to_str(self):
return pprint.pformat(self.to_dict()) |
def __repr__(self):
'For `print` and `pprint`'
return self.to_str() | -8,960,031,694,814,905,000 | For `print` and `pprint` | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | __repr__ | NaverCloudPlatform/ncloud-sdk-python | python | def __repr__(self):
return self.to_str() |
def __eq__(self, other):
'Returns true if both objects are equal'
if (not isinstance(other, ResumeProcessesResponse)):
return False
return (self.__dict__ == other.__dict__) | -7,900,360,667,409,191,000 | Returns true if both objects are equal | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | __eq__ | NaverCloudPlatform/ncloud-sdk-python | python | def __eq__(self, other):
if (not isinstance(other, ResumeProcessesResponse)):
return False
return (self.__dict__ == other.__dict__) |
def __ne__(self, other):
'Returns true if both objects are not equal'
return (not (self == other)) | 7,764,124,047,908,058,000 | Returns true if both objects are not equal | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | __ne__ | NaverCloudPlatform/ncloud-sdk-python | python | def __ne__(self, other):
return (not (self == other)) |
def query_countries(countries: List[str]=[], country_ids: List[str]=[]) -> List[Region]:
' Returns a list of countries:\n If countries or country_ids are not empty, only those countries are returned (all of those in both lists)\n Otherwise, all countries are returned\n '
where = region_where_clause('s_... | -6,755,750,796,964,314,000 | Returns a list of countries:
If countries or country_ids are not empty, only those countries are returned (all of those in both lists)
Otherwise, all countries are returned | db/sql/dal/regions.py | query_countries | Otamio/datamart-api | python | def query_countries(countries: List[str]=[], country_ids: List[str]=[]) -> List[Region]:
' Returns a list of countries:\n If countries or country_ids are not empty, only those countries are returned (all of those in both lists)\n Otherwise, all countries are returned\n '
where = region_where_clause('s_... |
def query_admin1s(country: Optional[str]=None, country_id: Optional[str]=None, admin1s: List[str]=[], admin1_ids: List[str]=[]) -> List[Region]:
'\n Returns a list of admin1s. If country or country_id is specified, return the admin1s only of that country.\n If admin1s or admin1_ids are provided, only those ad... | 5,190,282,231,298,423,000 | Returns a list of admin1s. If country or country_id is specified, return the admin1s only of that country.
If admin1s or admin1_ids are provided, only those admins are returned.
If all arguments are empty, all admin1s in the system are returned. | db/sql/dal/regions.py | query_admin1s | Otamio/datamart-api | python | def query_admin1s(country: Optional[str]=None, country_id: Optional[str]=None, admin1s: List[str]=[], admin1_ids: List[str]=[]) -> List[Region]:
'\n Returns a list of admin1s. If country or country_id is specified, return the admin1s only of that country.\n If admin1s or admin1_ids are provided, only those ad... |
def query_admin2s(admin1: Optional[str]=None, admin1_id: Optional[str]=None, admin2s: List[str]=[], admin2_ids: List[str]=[]) -> List[Region]:
'\n Returns a list of admin2s. If admin1 or admin1_id is specified, return the admin2s only of that admin1.\n If admin2s or admin2_ids are provided, only those admins ... | -1,743,948,908,563,666,400 | Returns a list of admin2s. If admin1 or admin1_id is specified, return the admin2s only of that admin1.
If admin2s or admin2_ids are provided, only those admins are returned.
If all arguments are empty, all admin2s in the system are returned. | db/sql/dal/regions.py | query_admin2s | Otamio/datamart-api | python | def query_admin2s(admin1: Optional[str]=None, admin1_id: Optional[str]=None, admin2s: List[str]=[], admin2_ids: List[str]=[]) -> List[Region]:
'\n Returns a list of admin2s. If admin1 or admin1_id is specified, return the admin2s only of that admin1.\n If admin2s or admin2_ids are provided, only those admins ... |
def query_admin3s(admin2: Optional[str]=None, admin2_id: Optional[str]=None, admin3s: List[str]=[], admin3_ids: List[str]=[], debug=False) -> List[Region]:
'\n Returns a list of admin3s. If admin2 or admin2_id is specified, return the admin3s only of that admin2.\n If admin3s or admin3_ids are provided, only ... | -7,311,637,996,641,695,000 | Returns a list of admin3s. If admin2 or admin2_id is specified, return the admin3s only of that admin2.
If admin3s or admin3_ids are provided, only those admins are returned.
If all arguments are empty, all admin3s in the system are returned. | db/sql/dal/regions.py | query_admin3s | Otamio/datamart-api | python | def query_admin3s(admin2: Optional[str]=None, admin2_id: Optional[str]=None, admin3s: List[str]=[], admin3_ids: List[str]=[], debug=False) -> List[Region]:
'\n Returns a list of admin3s. If admin2 or admin2_id is specified, return the admin3s only of that admin2.\n If admin3s or admin3_ids are provided, only ... |
@simple_decorator
def error2fault(func):
'\n Catch known exceptions and translate them to\n XML-RPC faults.\n '
def catcher(*args):
try:
return func(*args)
except GameError as error:
raise xmlrpc.client.Fault(GameError.rpc_code, str(error))
except RuleEr... | 6,223,366,847,108,657,000 | Catch known exceptions and translate them to
XML-RPC faults. | tupelo/xmlrpc.py | error2fault | jait/tupelo | python | @simple_decorator
def error2fault(func):
'\n Catch known exceptions and translate them to\n XML-RPC faults.\n '
def catcher(*args):
try:
return func(*args)
except GameError as error:
raise xmlrpc.client.Fault(GameError.rpc_code, str(error))
except RuleEr... |
@simple_decorator
def fault2error(func):
'\n Catch known XML-RPC faults and translate them to\n custom exceptions.\n '
def catcher(*args):
try:
return func(*args)
except xmlrpc.client.Fault as error:
error_classes = (GameError, RuleError, ProtocolError)
... | 550,723,065,045,873,660 | Catch known XML-RPC faults and translate them to
custom exceptions. | tupelo/xmlrpc.py | fault2error | jait/tupelo | python | @simple_decorator
def fault2error(func):
'\n Catch known XML-RPC faults and translate them to\n custom exceptions.\n '
def catcher(*args):
try:
return func(*args)
except xmlrpc.client.Fault as error:
error_classes = (GameError, RuleError, ProtocolError)
... |
def wait_for_turn(self):
"\n Wait for this player's turn.\n "
while True:
time.sleep(0.5)
if (self.controller is not None):
events = self.controller.get_events(self.id)
for event in events:
self.handle_event(event)
if (self.game_state... | -4,054,009,647,122,734,600 | Wait for this player's turn. | tupelo/xmlrpc.py | wait_for_turn | jait/tupelo | python | def wait_for_turn(self):
"\n \n "
while True:
time.sleep(0.5)
if (self.controller is not None):
events = self.controller.get_events(self.id)
for event in events:
self.handle_event(event)
if (self.game_state.turn_id == self.id):
... |
def add_collision_mesh(self, collision_mesh, options=None):
'Add a collision mesh to the planning scene.\n\n Parameters\n ----------\n collision_mesh : :class:`compas_fab.robots.CollisionMesh`\n Object containing the collision mesh to be added.\n options : dict, optional\n ... | -7,232,787,266,132,847,000 | Add a collision mesh to the planning scene.
Parameters
----------
collision_mesh : :class:`compas_fab.robots.CollisionMesh`
Object containing the collision mesh to be added.
options : dict, optional
Unused parameter.
Returns
-------
``None`` | src/compas_fab/backends/ros/backend_features/move_it_add_collision_mesh.py | add_collision_mesh | gramaziokohler/compas_fab | python | def add_collision_mesh(self, collision_mesh, options=None):
'Add a collision mesh to the planning scene.\n\n Parameters\n ----------\n collision_mesh : :class:`compas_fab.robots.CollisionMesh`\n Object containing the collision mesh to be added.\n options : dict, optional\n ... |
def coinChange(self, coins, amount):
'\n :type coins: List[int]\n :type amount: int\n :rtype: int\n '
res = ([(amount + 1)] * (amount + 1))
res[0] = 0
for i in range(1, (amount + 1)):
for j in coins:
if (j <= i):
res[i] = min(res[i], (res[(... | 8,912,028,627,762,102,000 | :type coins: List[int]
:type amount: int
:rtype: int | Session1_2018/coinChange.py | coinChange | vedantc6/LCode | python | def coinChange(self, coins, amount):
'\n :type coins: List[int]\n :type amount: int\n :rtype: int\n '
res = ([(amount + 1)] * (amount + 1))
res[0] = 0
for i in range(1, (amount + 1)):
for j in coins:
if (j <= i):
res[i] = min(res[i], (res[(... |
@interpolate_doc
def func():
'\n this is a docstring\n\n {interpolate_example.foo}\n\n {bar}\n\n {Foo!K}\n ' | 6,285,249,781,807,159,000 | this is a docstring
{interpolate_example.foo}
{bar}
{Foo!K} | interpolate_example.py | func | anntzer/structured-docstrings | python | @interpolate_doc
def func():
'\n this is a docstring\n\n {interpolate_example.foo}\n\n {bar}\n\n {Foo!K}\n ' |
@interpolate_doc
def bad_doc():
'\n fields {must} be preceded by whitespace\n ' | 6,683,463,889,826,569,000 | fields {must} be preceded by whitespace | interpolate_example.py | bad_doc | anntzer/structured-docstrings | python | @interpolate_doc
def bad_doc():
'\n \n ' |
@pytest.mark.django_db
def test_force_staff_sso(client):
'Test that URLs and redirects are in place.'
settings.FEATURE_FLAGS['ENFORCE_STAFF_SSO_ON'] = True
settings.AUTHBROKER_CLIENT_ID = 'debug'
settings.AUTHBROKER_CLIENT_SECRET = 'debug'
settings.AUTHBROKER_URL = 'https://test.com'
reload_urlc... | 1,363,510,666,531,336,200 | Test that URLs and redirects are in place. | tests/users/test_views.py | test_force_staff_sso | uktrade/directory-cms | python | @pytest.mark.django_db
def test_force_staff_sso(client):
settings.FEATURE_FLAGS['ENFORCE_STAFF_SSO_ON'] = True
settings.AUTHBROKER_CLIENT_ID = 'debug'
settings.AUTHBROKER_CLIENT_SECRET = 'debug'
settings.AUTHBROKER_URL = 'https://test.com'
reload_urlconf()
assert (reverse('authbroker_client... |
def __init__(self, db_conn):
'\n init\n :return:\n '
self.parseDbConn(db_conn)
self.__initDbClient() | -2,465,099,712,075,066,400 | init
:return: | db/dbClient.py | __init__ | dota2heqiuzhi/proxy_pool | python | def __init__(self, db_conn):
'\n init\n :return:\n '
self.parseDbConn(db_conn)
self.__initDbClient() |
def __initDbClient(self):
'\n init DB Client\n :return:\n '
__type = None
if ('SSDB' == self.db_type):
__type = 'ssdbClient'
elif ('REDIS' == self.db_type):
__type = 'redisClient'
elif ('POSTGRESQL' == self.db_type):
__type = 'postgresqlClient'
else:
... | -8,341,425,307,030,236,000 | init DB Client
:return: | db/dbClient.py | __initDbClient | dota2heqiuzhi/proxy_pool | python | def __initDbClient(self):
'\n init DB Client\n :return:\n '
__type = None
if ('SSDB' == self.db_type):
__type = 'ssdbClient'
elif ('REDIS' == self.db_type):
__type = 'redisClient'
elif ('POSTGRESQL' == self.db_type):
__type = 'postgresqlClient'
else:
... |
def testV1alpha1PriorityClass(self):
'\n Test V1alpha1PriorityClass\n '
pass | 8,672,129,437,725,520,000 | Test V1alpha1PriorityClass | kubernetes/test/test_v1alpha1_priority_class.py | testV1alpha1PriorityClass | MiaoRachelYu/python | python | def testV1alpha1PriorityClass(self):
'\n \n '
pass |
def fit(self, Xi_train, Xv_train, y_train, Xi_valid=None, Xv_valid=None, y_valid=None, early_stopping=False, refit=False):
'\n :param Xi_train: [[ind1_1, ind1_2, ...], [ind2_1, ind2_2, ...], ..., [indi_1, indi_2, ..., indi_j, ...], ...]\n indi_j is the feature index of... | 4,153,447,849,296,950,300 | :param Xi_train: [[ind1_1, ind1_2, ...], [ind2_1, ind2_2, ...], ..., [indi_1, indi_2, ..., indi_j, ...], ...]
indi_j is the feature index of feature field j of sample i in the training set
:param Xv_train: [[val1_1, val1_2, ...], [val2_1, val2_2, ...], ..., [vali_1, vali_2, ..., vali_j, ...], ...]
... | zzh/mllib/model/_deep_fm.py | fit | zhangzhenhu/zzh | python | def fit(self, Xi_train, Xv_train, y_train, Xi_valid=None, Xv_valid=None, y_valid=None, early_stopping=False, refit=False):
'\n :param Xi_train: [[ind1_1, ind1_2, ...], [ind2_1, ind2_2, ...], ..., [indi_1, indi_2, ..., indi_j, ...], ...]\n indi_j is the feature index of... |
def predict(self, Xi, Xv):
'\n :param Xi: list of list of feature indices of each sample in the dataset\n :param Xv: list of list of feature values of each sample in the dataset\n :return: predicted probability of each sample\n '
dummy_y = ([1] * len(Xi))
batch_index = 0
(Xi_... | 4,152,048,524,689,723,000 | :param Xi: list of list of feature indices of each sample in the dataset
:param Xv: list of list of feature values of each sample in the dataset
:return: predicted probability of each sample | zzh/mllib/model/_deep_fm.py | predict | zhangzhenhu/zzh | python | def predict(self, Xi, Xv):
'\n :param Xi: list of list of feature indices of each sample in the dataset\n :param Xv: list of list of feature values of each sample in the dataset\n :return: predicted probability of each sample\n '
dummy_y = ([1] * len(Xi))
batch_index = 0
(Xi_... |
def evaluate(self, Xi, Xv, y_true):
'\n :param Xi: list of list of feature indices of each sample in the dataset\n :param Xv: list of list of feature values of each sample in the dataset\n :param y: label of each sample in the dataset\n :return: metric of the evaluation\n '
si... | 7,261,298,830,425,360,000 | :param Xi: list of list of feature indices of each sample in the dataset
:param Xv: list of list of feature values of each sample in the dataset
:param y: label of each sample in the dataset
:return: metric of the evaluation | zzh/mllib/model/_deep_fm.py | evaluate | zhangzhenhu/zzh | python | def evaluate(self, Xi, Xv, y_true):
'\n :param Xi: list of list of feature indices of each sample in the dataset\n :param Xv: list of list of feature values of each sample in the dataset\n :param y: label of each sample in the dataset\n :return: metric of the evaluation\n '
si... |
def test_create_valid_user_successful(self):
'Test creating user with valid payload is successful'
payload = {'email': 'example@example.com', 'password': 'testpass', 'name': 'John Doe'}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
user =... | -2,702,256,109,293,972,000 | Test creating user with valid payload is successful | app/user/tests/test_user_api.py | test_create_valid_user_successful | reallyusefulengine/django_rest_recipe | python | def test_create_valid_user_successful(self):
payload = {'email': 'example@example.com', 'password': 'testpass', 'name': 'John Doe'}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
user = get_user_model().objects.get(**res.data)
self.as... |
def test_password_too_short(self):
'tests that the password must be more than 5 characters'
payload = {'email': 'example@example.com', 'password': 'pass', 'name': 'John Doe'}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
user_exists =... | 5,859,076,869,366,854,000 | tests that the password must be more than 5 characters | app/user/tests/test_user_api.py | test_password_too_short | reallyusefulengine/django_rest_recipe | python | def test_password_too_short(self):
payload = {'email': 'example@example.com', 'password': 'pass', 'name': 'John Doe'}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
user_exists = get_user_model().objects.filter(email=payload['email'])... |
def test_create_token_for_user(self):
'Test that a token is created for a user'
payload = {'email': 'example@example.com', 'password': 'testpass'}
create_user(**payload)
res = self.client.post(TOKEN_URL, payload)
self.assertTrue(res.status_code, status.HTTP_200_OK)
self.assertIn('token', res.dat... | -590,296,323,168,376,700 | Test that a token is created for a user | app/user/tests/test_user_api.py | test_create_token_for_user | reallyusefulengine/django_rest_recipe | python | def test_create_token_for_user(self):
payload = {'email': 'example@example.com', 'password': 'testpass'}
create_user(**payload)
res = self.client.post(TOKEN_URL, payload)
self.assertTrue(res.status_code, status.HTTP_200_OK)
self.assertIn('token', res.data) |
def test_create_token_invalid_credentials(self):
'Test that token is not created if invalid credentials are given'
create_user(email='example@example.com', password='testpass')
payload = {'email': 'example@example.com', 'password': 'wrong'}
res = self.client.post(TOKEN_URL, payload)
self.assertTrue(... | -7,467,095,345,633,051,000 | Test that token is not created if invalid credentials are given | app/user/tests/test_user_api.py | test_create_token_invalid_credentials | reallyusefulengine/django_rest_recipe | python | def test_create_token_invalid_credentials(self):
create_user(email='example@example.com', password='testpass')
payload = {'email': 'example@example.com', 'password': 'wrong'}
res = self.client.post(TOKEN_URL, payload)
self.assertTrue(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotI... |
def test_create_token_no_user(self):
'Test that token is not created if user does not exist'
payload = {'email': 'example@example.com', 'password': 'wrong'}
res = self.client.post(TOKEN_URL, payload)
self.assertTrue(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotIn('token', res.data) | -6,124,620,769,133,167,000 | Test that token is not created if user does not exist | app/user/tests/test_user_api.py | test_create_token_no_user | reallyusefulengine/django_rest_recipe | python | def test_create_token_no_user(self):
payload = {'email': 'example@example.com', 'password': 'wrong'}
res = self.client.post(TOKEN_URL, payload)
self.assertTrue(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotIn('token', res.data) |
def test_create_token_no_missing_field(self):
'Test that token is not created if email/password not given'
res = self.client.post(TOKEN_URL, {'email': 'example@example.com', 'password': ''})
self.assertTrue(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotIn('token', res.data) | -2,498,119,025,504,459,000 | Test that token is not created if email/password not given | app/user/tests/test_user_api.py | test_create_token_no_missing_field | reallyusefulengine/django_rest_recipe | python | def test_create_token_no_missing_field(self):
res = self.client.post(TOKEN_URL, {'email': 'example@example.com', 'password': })
self.assertTrue(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotIn('token', res.data) |
def _softplus(x):
'Implements the softplus function.'
return torch.nn.functional.softplus(x, beta=1, threshold=10000) | -8,304,163,192,589,108,000 | Implements the softplus function. | utils/inverter.py | _softplus | Twizwei/idinvert_pytorch | python | def _softplus(x):
return torch.nn.functional.softplus(x, beta=1, threshold=10000) |
def _get_tensor_value(tensor):
'Gets the value of a torch Tensor.'
return tensor.cpu().detach().numpy() | 5,971,145,564,746,899,000 | Gets the value of a torch Tensor. | utils/inverter.py | _get_tensor_value | Twizwei/idinvert_pytorch | python | def _get_tensor_value(tensor):
return tensor.cpu().detach().numpy() |
def __init__(self, model_name, learning_rate=0.01, iteration=100, reconstruction_loss_weight=1.0, perceptual_loss_weight=5e-05, regularization_loss_weight=2.0, logger=None):
'Initializes the inverter.\n\n NOTE: Only Adam optimizer is supported in the optimization process.\n\n Args:\n model_name: Name of ... | 4,956,284,454,006,761,000 | Initializes the inverter.
NOTE: Only Adam optimizer is supported in the optimization process.
Args:
model_name: Name of the model on which the inverted is based. The model
should be first registered in `models/model_settings.py`.
logger: Logger to record the log message.
learning_rate: Learning rate for opt... | utils/inverter.py | __init__ | Twizwei/idinvert_pytorch | python | def __init__(self, model_name, learning_rate=0.01, iteration=100, reconstruction_loss_weight=1.0, perceptual_loss_weight=5e-05, regularization_loss_weight=2.0, logger=None):
'Initializes the inverter.\n\n NOTE: Only Adam optimizer is supported in the optimization process.\n\n Args:\n model_name: Name of ... |
def preprocess(self, image):
'Preprocesses a single image.\n\n This function assumes the input numpy array is with shape [height, width,\n channel], channel order `RGB`, and pixel range [0, 255].\n\n The returned image is with shape [channel, new_height, new_width], where\n `new_height` and `new_width` ... | 8,297,031,020,724,259,000 | Preprocesses a single image.
This function assumes the input numpy array is with shape [height, width,
channel], channel order `RGB`, and pixel range [0, 255].
The returned image is with shape [channel, new_height, new_width], where
`new_height` and `new_width` are specified by the given generative model.
The channel... | utils/inverter.py | preprocess | Twizwei/idinvert_pytorch | python | def preprocess(self, image):
'Preprocesses a single image.\n\n This function assumes the input numpy array is with shape [height, width,\n channel], channel order `RGB`, and pixel range [0, 255].\n\n The returned image is with shape [channel, new_height, new_width], where\n `new_height` and `new_width` ... |
def get_init_code(self, image):
'Gets initial latent codes as the start point for optimization.\n\n The input image is assumed to have already been preprocessed, meaning to\n have shape [self.G.image_channels, self.G.resolution, self.G.resolution],\n channel order `self.G.channel_order`, and pixel range [s... | -7,680,309,811,430,556,000 | Gets initial latent codes as the start point for optimization.
The input image is assumed to have already been preprocessed, meaning to
have shape [self.G.image_channels, self.G.resolution, self.G.resolution],
channel order `self.G.channel_order`, and pixel range [self.G.min_val,
self.G.max_val]. | utils/inverter.py | get_init_code | Twizwei/idinvert_pytorch | python | def get_init_code(self, image):
'Gets initial latent codes as the start point for optimization.\n\n The input image is assumed to have already been preprocessed, meaning to\n have shape [self.G.image_channels, self.G.resolution, self.G.resolution],\n channel order `self.G.channel_order`, and pixel range [s... |
def invert(self, image, num_viz=0):
'Inverts the given image to a latent code.\n\n Basically, this function is based on gradient descent algorithm.\n\n Args:\n image: Target image to invert, which is assumed to have already been\n preprocessed.\n num_viz: Number of intermediate outputs to vis... | -5,647,097,221,206,265,000 | Inverts the given image to a latent code.
Basically, this function is based on gradient descent algorithm.
Args:
image: Target image to invert, which is assumed to have already been
preprocessed.
num_viz: Number of intermediate outputs to visualize. (default: 0)
Returns:
A two-element tuple. First one is t... | utils/inverter.py | invert | Twizwei/idinvert_pytorch | python | def invert(self, image, num_viz=0):
'Inverts the given image to a latent code.\n\n Basically, this function is based on gradient descent algorithm.\n\n Args:\n image: Target image to invert, which is assumed to have already been\n preprocessed.\n num_viz: Number of intermediate outputs to vis... |
def easy_invert(self, image, num_viz=0):
'Wraps functions `preprocess()` and `invert()` together.'
return self.invert(self.preprocess(image), num_viz) | 8,442,911,914,438,245,000 | Wraps functions `preprocess()` and `invert()` together. | utils/inverter.py | easy_invert | Twizwei/idinvert_pytorch | python | def easy_invert(self, image, num_viz=0):
return self.invert(self.preprocess(image), num_viz) |
def diffuse(self, target, context, center_x, center_y, crop_x, crop_y, num_viz=0):
'Diffuses the target image to a context image.\n\n Basically, this function is a motified version of `self.invert()`. More\n concretely, the encoder regularizer is removed from the objectives and the\n reconstruction loss is... | -7,616,106,853,401,418,000 | Diffuses the target image to a context image.
Basically, this function is a motified version of `self.invert()`. More
concretely, the encoder regularizer is removed from the objectives and the
reconstruction loss is computed from the masked region.
Args:
target: Target image (foreground).
context: Context image (... | utils/inverter.py | diffuse | Twizwei/idinvert_pytorch | python | def diffuse(self, target, context, center_x, center_y, crop_x, crop_y, num_viz=0):
'Diffuses the target image to a context image.\n\n Basically, this function is a motified version of `self.invert()`. More\n concretely, the encoder regularizer is removed from the objectives and the\n reconstruction loss is... |
def easy_diffuse(self, target, context, *args, **kwargs):
'Wraps functions `preprocess()` and `diffuse()` together.'
return self.diffuse(self.preprocess(target), self.preprocess(context), *args, **kwargs) | -8,924,164,457,142,377,000 | Wraps functions `preprocess()` and `diffuse()` together. | utils/inverter.py | easy_diffuse | Twizwei/idinvert_pytorch | python | def easy_diffuse(self, target, context, *args, **kwargs):
return self.diffuse(self.preprocess(target), self.preprocess(context), *args, **kwargs) |
async def async_start(hass: HomeAssistantType, discovery_topic, hass_config, config_entry=None) -> bool:
'Initialize of MQTT Discovery.'
async def async_device_message_received(topic, payload, qos):
'Process the received message.'
match = TOPIC_MATCHER.match(topic)
if (not match):
... | 2,637,539,386,003,770,000 | Initialize of MQTT Discovery. | homeassistant/components/mqtt/discovery.py | async_start | arnisoph/home-assistant | python | async def async_start(hass: HomeAssistantType, discovery_topic, hass_config, config_entry=None) -> bool:
async def async_device_message_received(topic, payload, qos):
'Process the received message.'
match = TOPIC_MATCHER.match(topic)
if (not match):
return
(_prefix_... |
async def async_device_message_received(topic, payload, qos):
'Process the received message.'
match = TOPIC_MATCHER.match(topic)
if (not match):
return
(_prefix_topic, component, node_id, object_id) = match.groups()
if (component not in SUPPORTED_COMPONENTS):
_LOGGER.warning('Compone... | -2,159,514,262,508,901,400 | Process the received message. | homeassistant/components/mqtt/discovery.py | async_device_message_received | arnisoph/home-assistant | python | async def async_device_message_received(topic, payload, qos):
match = TOPIC_MATCHER.match(topic)
if (not match):
return
(_prefix_topic, component, node_id, object_id) = match.groups()
if (component not in SUPPORTED_COMPONENTS):
_LOGGER.warning('Component %s is not supported', compon... |
def __init__(self, inplanes, planes, scales=4, base_width=26, base_channels=64, stage_type='normal', **kwargs):
'Bottle2neck block for Res2Net.\n\n If style is "pytorch", the stride-two layer is the 3x3 conv layer, if\n it is "caffe", the stride-two layer is the first 1x1 conv layer.\n '
su... | 4,797,434,700,482,818,000 | Bottle2neck block for Res2Net.
If style is "pytorch", the stride-two layer is the 3x3 conv layer, if
it is "caffe", the stride-two layer is the first 1x1 conv layer. | detection/scrfd/mmdet/models/backbones/res2net.py | __init__ | 007gzs/insightface | python | def __init__(self, inplanes, planes, scales=4, base_width=26, base_channels=64, stage_type='normal', **kwargs):
'Bottle2neck block for Res2Net.\n\n If style is "pytorch", the stride-two layer is the 3x3 conv layer, if\n it is "caffe", the stride-two layer is the first 1x1 conv layer.\n '
su... |
def forward(self, x):
'Forward function.'
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv1_plugin_names)
spx = torch.split(out, sel... | 1,846,693,992,825,146,000 | Forward function. | detection/scrfd/mmdet/models/backbones/res2net.py | forward | 007gzs/insightface | python | def forward(self, x):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv1_plugin_names)
spx = torch.split(out, self.width, 1)
... |
def init_weights(self, pretrained=None):
'Initialize the weights in backbone.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n '
if isinstance(pretrained, str):
logger = get_root_logger()
load_checkpoint(self, pret... | -399,503,817,821,927,300 | Initialize the weights in backbone.
Args:
pretrained (str, optional): Path to pre-trained weights.
Defaults to None. | detection/scrfd/mmdet/models/backbones/res2net.py | init_weights | 007gzs/insightface | python | def init_weights(self, pretrained=None):
'Initialize the weights in backbone.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n '
if isinstance(pretrained, str):
logger = get_root_logger()
load_checkpoint(self, pret... |
def parse_assets(lines):
' Parse asset list\n\n :param string paste_string: An asset list string\n '
(matches, bad_lines) = regex_match_lines(ASSET_LIST_RE, lines)
result = [{'name': name, 'quantity': (f_int(quantity) or 1), 'group': group, 'category': category, 'size': size, 'slot': slot, 'volume': v... | 6,874,263,680,403,479,000 | Parse asset list
:param string paste_string: An asset list string | eveparser/parsers/assets.py | parse_assets | Nothing4You/eveparser | python | def parse_assets(lines):
' Parse asset list\n\n :param string paste_string: An asset list string\n '
(matches, bad_lines) = regex_match_lines(ASSET_LIST_RE, lines)
result = [{'name': name, 'quantity': (f_int(quantity) or 1), 'group': group, 'category': category, 'size': size, 'slot': slot, 'volume': v... |
def __init__(self, compute_client):
'Instantiate ZoneResourceFetcher and embed all required data into it.\n\n ZoneResourceFetcher is a class depending on "base_classes"\n class layout (properties side-derived from one of base_class class). This\n function can be used to avoid unfeasible inheritance and use... | 4,449,017,669,771,330,600 | Instantiate ZoneResourceFetcher and embed all required data into it.
ZoneResourceFetcher is a class depending on "base_classes"
class layout (properties side-derived from one of base_class class). This
function can be used to avoid unfeasible inheritance and use composition
instead when refactoring away from base_clas... | gcloud/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/zone_utils.py | __init__ | bopopescu/JobSniperRails | python | def __init__(self, compute_client):
'Instantiate ZoneResourceFetcher and embed all required data into it.\n\n ZoneResourceFetcher is a class depending on "base_classes"\n class layout (properties side-derived from one of base_class class). This\n function can be used to avoid unfeasible inheritance and use... |
def GetZones(self, resource_refs):
'Fetches zone resources.'
errors = []
requests = []
zone_names = set()
for resource_ref in resource_refs:
if (resource_ref.zone not in zone_names):
zone_names.add(resource_ref.zone)
requests.append((self._compute.zones, 'Get', self._... | -4,250,735,275,922,151,000 | Fetches zone resources. | gcloud/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/zone_utils.py | GetZones | bopopescu/JobSniperRails | python | def GetZones(self, resource_refs):
errors = []
requests = []
zone_names = set()
for resource_ref in resource_refs:
if (resource_ref.zone not in zone_names):
zone_names.add(resource_ref.zone)
requests.append((self._compute.zones, 'Get', self._messages.ComputeZonesGetR... |
def WarnForZonalCreation(self, resource_refs):
'Warns the user if a zone has upcoming deprecation.'
zones = self.GetZones(resource_refs)
if (not zones):
return
prompts = []
zones_with_deprecated = []
for zone in zones:
if zone.deprecated:
zones_with_deprecated.append(... | -5,013,486,056,412,300,000 | Warns the user if a zone has upcoming deprecation. | gcloud/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/zone_utils.py | WarnForZonalCreation | bopopescu/JobSniperRails | python | def WarnForZonalCreation(self, resource_refs):
zones = self.GetZones(resource_refs)
if (not zones):
return
prompts = []
zones_with_deprecated = []
for zone in zones:
if zone.deprecated:
zones_with_deprecated.append(zone)
if (not zones_with_deprecated):
re... |
def run_forever():
'Runs the asyncio event loop with and\n ensures state machines are exited upon a KeyboardInterrupt.\n '
loop = asyncio.get_event_loop()
try:
loop.run_forever()
except KeyboardInterrupt:
Framework.stop()
loop.close() | -6,814,674,388,628,781,000 | Runs the asyncio event loop with and
ensures state machines are exited upon a KeyboardInterrupt. | farc/__init__.py | run_forever | SzeMengTan/farc | python | def run_forever():
'Runs the asyncio event loop with and\n ensures state machines are exited upon a KeyboardInterrupt.\n '
loop = asyncio.get_event_loop()
try:
loop.run_forever()
except KeyboardInterrupt:
Framework.stop()
loop.close() |
@staticmethod
def enable_spy(spy_cls):
'Sets the Spy to use the given class\n and calls its initializer.\n '
Spy._actv_cls = spy_cls
spy_cls.init() | 2,137,537,250,594,512,100 | Sets the Spy to use the given class
and calls its initializer. | farc/__init__.py | enable_spy | SzeMengTan/farc | python | @staticmethod
def enable_spy(spy_cls):
'Sets the Spy to use the given class\n and calls its initializer.\n '
Spy._actv_cls = spy_cls
spy_cls.init() |
def __getattr__(*args):
'Returns\n 1) the enable_spy static method if requested by name, or\n 2) the attribute from the active class (if active class was set), or\n 3) a function that swallows any arguments and does nothing.\n '
if (args[1] == 'enable_spy'):
return Spy.enable... | 6,580,064,896,499,551,000 | Returns
1) the enable_spy static method if requested by name, or
2) the attribute from the active class (if active class was set), or
3) a function that swallows any arguments and does nothing. | farc/__init__.py | __getattr__ | SzeMengTan/farc | python | def __getattr__(*args):
'Returns\n 1) the enable_spy static method if requested by name, or\n 2) the attribute from the active class (if active class was set), or\n 3) a function that swallows any arguments and does nothing.\n '
if (args[1] == 'enable_spy'):
return Spy.enable... |
@staticmethod
def exists(signame):
'Returns True if signame is in the Signal registry.\n '
return (signame in Signal._registry) | -1,967,252,211,100,177,000 | Returns True if signame is in the Signal registry. | farc/__init__.py | exists | SzeMengTan/farc | python | @staticmethod
def exists(signame):
'\n '
return (signame in Signal._registry) |
@staticmethod
def register(signame):
'Registers the signame if it is not already registered.\n Returns the signal number for the signame.\n '
assert (type(signame) is str)
if (signame in Signal._registry):
return Signal._registry[signame]
else:
sigid = len(Signal._lookup)
... | -5,932,514,422,443,632,000 | Registers the signame if it is not already registered.
Returns the signal number for the signame. | farc/__init__.py | register | SzeMengTan/farc | python | @staticmethod
def register(signame):
'Registers the signame if it is not already registered.\n Returns the signal number for the signame.\n '
assert (type(signame) is str)
if (signame in Signal._registry):
return Signal._registry[signame]
else:
sigid = len(Signal._lookup)
... |
def __init__(self):
"Sets this Hsm's current state to Hsm.top(), the default state\n and stores the given initial state.\n "
self.state = self.top
self.initial_state = self._initial | -1,334,007,641,773,020,400 | Sets this Hsm's current state to Hsm.top(), the default state
and stores the given initial state. | farc/__init__.py | __init__ | SzeMengTan/farc | python | def __init__(self):
"Sets this Hsm's current state to Hsm.top(), the default state\n and stores the given initial state.\n "
self.state = self.top
self.initial_state = self._initial |
def _initial(self, event):
'Raises a NotImplementedError to force the derived class\n to implement its own initial state.\n '
raise NotImplementedError | 6,814,616,314,063,496,000 | Raises a NotImplementedError to force the derived class
to implement its own initial state. | farc/__init__.py | _initial | SzeMengTan/farc | python | def _initial(self, event):
'Raises a NotImplementedError to force the derived class\n to implement its own initial state.\n '
raise NotImplementedError |
def state(func):
'A decorator that identifies which methods are states.\n The presence of the farc_state attr, not the value of the attr,\n determines statehood.\n The Spy debugging system uses the farc_state attribute\n to determine which methods inside a class are actually states.\n ... | 4,006,958,211,435,342,000 | A decorator that identifies which methods are states.
The presence of the farc_state attr, not the value of the attr,
determines statehood.
The Spy debugging system uses the farc_state attribute
to determine which methods inside a class are actually states.
Other uses of the attribute may come in the future. | farc/__init__.py | state | SzeMengTan/farc | python | def state(func):
'A decorator that identifies which methods are states.\n The presence of the farc_state attr, not the value of the attr,\n determines statehood.\n The Spy debugging system uses the farc_state attribute\n to determine which methods inside a class are actually states.\n ... |
@state
def top(me, event):
"This is the default state handler.\n This handler ignores all signals except\n the POSIX-like events, SIGINT/SIGTERM.\n Handling SIGINT/SIGTERM here causes the Exit path\n to be executed from the application's active state\n to top/here.\n The ap... | 4,357,347,042,863,078,000 | This is the default state handler.
This handler ignores all signals except
the POSIX-like events, SIGINT/SIGTERM.
Handling SIGINT/SIGTERM here causes the Exit path
to be executed from the application's active state
to top/here.
The application may put something useful
or nothing at all in the Exit path. | farc/__init__.py | top | SzeMengTan/farc | python | @state
def top(me, event):
"This is the default state handler.\n This handler ignores all signals except\n the POSIX-like events, SIGINT/SIGTERM.\n Handling SIGINT/SIGTERM here causes the Exit path\n to be executed from the application's active state\n to top/here.\n The ap... |
@staticmethod
def _perform_init_chain(me, current):
'Act on the chain of initializations required starting from current.\n '
t = current
while (Hsm.trig(me, (t if (t != Hsm.top) else me.initial_state), Signal.INIT) == Hsm.RET_TRAN):
path = []
while (me.state != t):
path.ap... | -3,732,168,619,316,651,000 | Act on the chain of initializations required starting from current. | farc/__init__.py | _perform_init_chain | SzeMengTan/farc | python | @staticmethod
def _perform_init_chain(me, current):
'\n '
t = current
while (Hsm.trig(me, (t if (t != Hsm.top) else me.initial_state), Signal.INIT) == Hsm.RET_TRAN):
path = []
while (me.state != t):
path.append(me.state)
Hsm.trig(me, me.state, Signal.EMPTY)
... |
@staticmethod
def init(me, event=None):
'Transitions to the initial state. Follows any INIT transitions\n from the inital state and performs ENTRY actions as it proceeds.\n Use this to pass any parameters to initialize the state machine.\n p. 172\n '
me.state = Hsm._perform_init_cha... | -8,697,070,345,986,381,000 | Transitions to the initial state. Follows any INIT transitions
from the inital state and performs ENTRY actions as it proceeds.
Use this to pass any parameters to initialize the state machine.
p. 172 | farc/__init__.py | init | SzeMengTan/farc | python | @staticmethod
def init(me, event=None):
'Transitions to the initial state. Follows any INIT transitions\n from the inital state and performs ENTRY actions as it proceeds.\n Use this to pass any parameters to initialize the state machine.\n p. 172\n '
me.state = Hsm._perform_init_cha... |
@staticmethod
def dispatch(me, event):
"Dispatches the given event to this Hsm.\n Follows the application's state transitions\n until the event is handled or top() is reached\n p. 174\n "
Spy.on_hsm_dispatch_event(event)
t = me.state
exit_path = []
r = Hsm.RET_SUPER
w... | -8,821,831,792,432,782,000 | Dispatches the given event to this Hsm.
Follows the application's state transitions
until the event is handled or top() is reached
p. 174 | farc/__init__.py | dispatch | SzeMengTan/farc | python | @staticmethod
def dispatch(me, event):
"Dispatches the given event to this Hsm.\n Follows the application's state transitions\n until the event is handled or top() is reached\n p. 174\n "
Spy.on_hsm_dispatch_event(event)
t = me.state
exit_path = []
r = Hsm.RET_SUPER
w... |
@staticmethod
def post(event, act):
"Posts the event to the given Ahsm's event queue.\n The argument, act, is an Ahsm instance.\n "
assert isinstance(act, Ahsm)
act.postFIFO(event) | 1,225,549,252,378,367,700 | Posts the event to the given Ahsm's event queue.
The argument, act, is an Ahsm instance. | farc/__init__.py | post | SzeMengTan/farc | python | @staticmethod
def post(event, act):
"Posts the event to the given Ahsm's event queue.\n The argument, act, is an Ahsm instance.\n "
assert isinstance(act, Ahsm)
act.postFIFO(event) |
@staticmethod
def post_by_name(event, act_name):
"Posts the event to the given Ahsm's event queue.\n The argument, act, is a string of the name of the class\n to which the event is sent. The event will post to all actors\n having the given classname.\n "
assert (type(act_name) is st... | -6,567,935,478,147,241,000 | Posts the event to the given Ahsm's event queue.
The argument, act, is a string of the name of the class
to which the event is sent. The event will post to all actors
having the given classname. | farc/__init__.py | post_by_name | SzeMengTan/farc | python | @staticmethod
def post_by_name(event, act_name):
"Posts the event to the given Ahsm's event queue.\n The argument, act, is a string of the name of the class\n to which the event is sent. The event will post to all actors\n having the given classname.\n "
assert (type(act_name) is st... |
@staticmethod
def publish(event):
"Posts the event to the message queue of every Ahsm\n that is subscribed to the event's signal.\n "
if (event.signal in Framework._subscriber_table):
for act in Framework._subscriber_table[event.signal]:
act.postFIFO(event)
Framework._event... | -3,316,009,976,515,112,000 | Posts the event to the message queue of every Ahsm
that is subscribed to the event's signal. | farc/__init__.py | publish | SzeMengTan/farc | python | @staticmethod
def publish(event):
"Posts the event to the message queue of every Ahsm\n that is subscribed to the event's signal.\n "
if (event.signal in Framework._subscriber_table):
for act in Framework._subscriber_table[event.signal]:
act.postFIFO(event)
Framework._event... |
@staticmethod
def subscribe(signame, act):
'Adds the given Ahsm to the subscriber table list\n for the given signal. The argument, signame, is a string of the name\n of the Signal to which the Ahsm is subscribing. Using a string allows\n the Signal to be created in the registry if it is not a... | 7,131,938,376,864,232,000 | Adds the given Ahsm to the subscriber table list
for the given signal. The argument, signame, is a string of the name
of the Signal to which the Ahsm is subscribing. Using a string allows
the Signal to be created in the registry if it is not already. | farc/__init__.py | subscribe | SzeMengTan/farc | python | @staticmethod
def subscribe(signame, act):
'Adds the given Ahsm to the subscriber table list\n for the given signal. The argument, signame, is a string of the name\n of the Signal to which the Ahsm is subscribing. Using a string allows\n the Signal to be created in the registry if it is not a... |
@staticmethod
def addTimeEvent(tm_event, delta):
"Adds the TimeEvent to the list of time events in the Framework.\n The event will fire its signal (to the TimeEvent's target Ahsm)\n after the delay, delta.\n "
expiration = (Framework._event_loop.time() + delta)
Framework.addTimeEventAt(... | -1,549,828,390,167,262,000 | Adds the TimeEvent to the list of time events in the Framework.
The event will fire its signal (to the TimeEvent's target Ahsm)
after the delay, delta. | farc/__init__.py | addTimeEvent | SzeMengTan/farc | python | @staticmethod
def addTimeEvent(tm_event, delta):
"Adds the TimeEvent to the list of time events in the Framework.\n The event will fire its signal (to the TimeEvent's target Ahsm)\n after the delay, delta.\n "
expiration = (Framework._event_loop.time() + delta)
Framework.addTimeEventAt(... |
@staticmethod
def addTimeEventAt(tm_event, abs_time):
"Adds the TimeEvent to the list of time events in the Framework.\n The event will fire its signal (to the TimeEvent's target Ahsm)\n at the given absolute time (_event_loop.time()).\n "
assert (tm_event not in Framework._time_events.valu... | 5,152,183,799,103,508,000 | Adds the TimeEvent to the list of time events in the Framework.
The event will fire its signal (to the TimeEvent's target Ahsm)
at the given absolute time (_event_loop.time()). | farc/__init__.py | addTimeEventAt | SzeMengTan/farc | python | @staticmethod
def addTimeEventAt(tm_event, abs_time):
"Adds the TimeEvent to the list of time events in the Framework.\n The event will fire its signal (to the TimeEvent's target Ahsm)\n at the given absolute time (_event_loop.time()).\n "
assert (tm_event not in Framework._time_events.valu... |
@staticmethod
def _insortTimeEvent(tm_event, expiration):
'Inserts a TimeEvent into the list of time events,\n sorted by the next expiration of the timer.\n If the expiration time matches an existing expiration,\n we add the smallest amount of time to the given expiration\n to avoid a ke... | 9,202,879,888,713,282,000 | Inserts a TimeEvent into the list of time events,
sorted by the next expiration of the timer.
If the expiration time matches an existing expiration,
we add the smallest amount of time to the given expiration
to avoid a key collision in the Dict
and make the identically-timed events fire in a FIFO fashion. | farc/__init__.py | _insortTimeEvent | SzeMengTan/farc | python | @staticmethod
def _insortTimeEvent(tm_event, expiration):
'Inserts a TimeEvent into the list of time events,\n sorted by the next expiration of the timer.\n If the expiration time matches an existing expiration,\n we add the smallest amount of time to the given expiration\n to avoid a ke... |
@staticmethod
def removeTimeEvent(tm_event):
"Removes the TimeEvent from the list of active time events.\n Cancels the TimeEvent's callback if there is one.\n Schedules the next event's callback if there is one.\n "
for (k, v) in Framework._time_events.items():
if (v is tm_event):
... | 9,140,786,555,416,009,000 | Removes the TimeEvent from the list of active time events.
Cancels the TimeEvent's callback if there is one.
Schedules the next event's callback if there is one. | farc/__init__.py | removeTimeEvent | SzeMengTan/farc | python | @staticmethod
def removeTimeEvent(tm_event):
"Removes the TimeEvent from the list of active time events.\n Cancels the TimeEvent's callback if there is one.\n Schedules the next event's callback if there is one.\n "
for (k, v) in Framework._time_events.items():
if (v is tm_event):
... |
@staticmethod
def timeEventCallback(tm_event, expiration):
"The callback function for all TimeEvents.\n Posts the event to the event's target Ahsm.\n If the TimeEvent is periodic, re-insort the event\n in the list of active time events.\n "
assert (expiration in Framework._time_event... | 2,536,676,419,023,421,000 | The callback function for all TimeEvents.
Posts the event to the event's target Ahsm.
If the TimeEvent is periodic, re-insort the event
in the list of active time events. | farc/__init__.py | timeEventCallback | SzeMengTan/farc | python | @staticmethod
def timeEventCallback(tm_event, expiration):
"The callback function for all TimeEvents.\n Posts the event to the event's target Ahsm.\n If the TimeEvent is periodic, re-insort the event\n in the list of active time events.\n "
assert (expiration in Framework._time_event... |
@staticmethod
def add(act):
'Makes the framework aware of the given Ahsm.\n '
Framework._ahsm_registry.append(act)
assert (act.priority not in Framework._priority_dict), 'Priority MUST be unique'
Framework._priority_dict[act.priority] = act
Spy.on_framework_add(act) | 4,218,832,176,318,824,000 | Makes the framework aware of the given Ahsm. | farc/__init__.py | add | SzeMengTan/farc | python | @staticmethod
def add(act):
'\n '
Framework._ahsm_registry.append(act)
assert (act.priority not in Framework._priority_dict), 'Priority MUST be unique'
Framework._priority_dict[act.priority] = act
Spy.on_framework_add(act) |
@staticmethod
def run():
'Dispatches an event to the highest priority Ahsm\n until all event queues are empty (i.e. Run To Completion).\n '
getPriority = (lambda x: x.priority)
while True:
allQueuesEmpty = True
sorted_acts = sorted(Framework._ahsm_registry, key=getPriority)
... | 7,207,906,900,246,715,000 | Dispatches an event to the highest priority Ahsm
until all event queues are empty (i.e. Run To Completion). | farc/__init__.py | run | SzeMengTan/farc | python | @staticmethod
def run():
'Dispatches an event to the highest priority Ahsm\n until all event queues are empty (i.e. Run To Completion).\n '
getPriority = (lambda x: x.priority)
while True:
allQueuesEmpty = True
sorted_acts = sorted(Framework._ahsm_registry, key=getPriority)
... |
@staticmethod
def stop():
'EXITs all Ahsms and stops the event loop.\n '
if Framework._tm_event_handle:
Framework._tm_event_handle.cancel()
Framework._tm_event_handle = None
for act in Framework._ahsm_registry:
Framework.post(Event.EXIT, act)
Framework.run()
Framework.... | -4,242,969,735,239,040,500 | EXITs all Ahsms and stops the event loop. | farc/__init__.py | stop | SzeMengTan/farc | python | @staticmethod
def stop():
'\n '
if Framework._tm_event_handle:
Framework._tm_event_handle.cancel()
Framework._tm_event_handle = None
for act in Framework._ahsm_registry:
Framework.post(Event.EXIT, act)
Framework.run()
Framework._event_loop.stop()
Spy.on_framework_s... |
@staticmethod
def print_info():
'Prints the name and current state\n of each actor in the framework.\n Meant to be called when ctrl+T (SIGINFO/29) is issued.\n '
for act in Framework._ahsm_registry:
print(act.__class__.__name__, act.state.__name__) | -2,474,237,011,219,255,300 | Prints the name and current state
of each actor in the framework.
Meant to be called when ctrl+T (SIGINFO/29) is issued. | farc/__init__.py | print_info | SzeMengTan/farc | python | @staticmethod
def print_info():
'Prints the name and current state\n of each actor in the framework.\n Meant to be called when ctrl+T (SIGINFO/29) is issued.\n '
for act in Framework._ahsm_registry:
print(act.__class__.__name__, act.state.__name__) |
def postAt(self, act, abs_time):
'Posts this TimeEvent to the given Ahsm at a specified time.\n '
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = 0
Framework.addTimeEventAt(self, abs_time) | -3,514,636,557,849,529,300 | Posts this TimeEvent to the given Ahsm at a specified time. | farc/__init__.py | postAt | SzeMengTan/farc | python | def postAt(self, act, abs_time):
'\n '
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = 0
Framework.addTimeEventAt(self, abs_time) |
def postIn(self, act, delta):
'Posts this TimeEvent to the given Ahsm after the time delta.\n '
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = 0
Framework.addTimeEvent(self, delta) | 7,578,574,746,659,476,000 | Posts this TimeEvent to the given Ahsm after the time delta. | farc/__init__.py | postIn | SzeMengTan/farc | python | def postIn(self, act, delta):
'\n '
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = 0
Framework.addTimeEvent(self, delta) |
def postEvery(self, act, delta):
'Posts this TimeEvent to the given Ahsm after the time delta\n and every time delta thereafter until disarmed.\n '
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = delta
Framework.addTimeEvent(self, delta) | 8,641,827,318,052,131,000 | Posts this TimeEvent to the given Ahsm after the time delta
and every time delta thereafter until disarmed. | farc/__init__.py | postEvery | SzeMengTan/farc | python | def postEvery(self, act, delta):
'Posts this TimeEvent to the given Ahsm after the time delta\n and every time delta thereafter until disarmed.\n '
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = delta
Framework.addTimeEvent(self, delta) |
def disarm(self):
"Removes this TimeEvent from the Framework's active time events.\n "
self.act = None
Framework.removeTimeEvent(self) | 7,122,821,650,057,362,000 | Removes this TimeEvent from the Framework's active time events. | farc/__init__.py | disarm | SzeMengTan/farc | python | def disarm(self):
"\n "
self.act = None
Framework.removeTimeEvent(self) |
@staticmethod
def calcVariation(onetick, oneposition):
'\n (tick: OneTick, position: OnePosition) -> float\n '
created = oneposition.priceMean()
if (oneposition.side == OnePosition.SideLong):
current = onetick.bid
else:
current = onetick.ask
return (current / created) | 2,954,959,345,308,836,000 | (tick: OneTick, position: OnePosition) -> float | apps/trade/src/PositionsManager.py | calcVariation | kikei/btc-bot-ai | python | @staticmethod
def calcVariation(onetick, oneposition):
'\n \n '
created = oneposition.priceMean()
if (oneposition.side == OnePosition.SideLong):
current = onetick.bid
else:
current = onetick.ask
return (current / created) |
def _fit_imaging_from(fit: af.Fit, galaxies: List[ag.Galaxy], settings_imaging: aa.SettingsImaging=None, settings_pixelization: aa.SettingsPixelization=None, settings_inversion: aa.SettingsInversion=None, use_preloaded_grid: bool=True, use_hyper_scaling: bool=True) -> FitImaging:
'\n Returns a `FitImaging` objec... | -6,554,503,904,327,956,000 | Returns a `FitImaging` object from a PyAutoFit database `Fit` object and an instance of galaxies from a non-linear
search model-fit.
This function adds the `hyper_model_image` and `hyper_galaxy_image_path_dict` to the galaxies before performing the
fit, if they were used.
Parameters
----------
fit
A PyAutoFit dat... | autolens/aggregator/fit_imaging.py | _fit_imaging_from | Jammy2211/AutoLens | python | def _fit_imaging_from(fit: af.Fit, galaxies: List[ag.Galaxy], settings_imaging: aa.SettingsImaging=None, settings_pixelization: aa.SettingsPixelization=None, settings_inversion: aa.SettingsInversion=None, use_preloaded_grid: bool=True, use_hyper_scaling: bool=True) -> FitImaging:
'\n Returns a `FitImaging` objec... |
def __init__(self, aggregator: af.Aggregator, settings_imaging: Optional[aa.SettingsImaging]=None, settings_pixelization: Optional[aa.SettingsPixelization]=None, settings_inversion: Optional[aa.SettingsInversion]=None, use_preloaded_grid: bool=True, use_hyper_scaling: bool=True):
'\n Wraps a PyAutoFit aggreg... | -2,135,738,284,995,956,000 | Wraps a PyAutoFit aggregator in order to create generators of fits to imaging data, corresponding to the
results of a non-linear search model-fit. | autolens/aggregator/fit_imaging.py | __init__ | Jammy2211/AutoLens | python | def __init__(self, aggregator: af.Aggregator, settings_imaging: Optional[aa.SettingsImaging]=None, settings_pixelization: Optional[aa.SettingsPixelization]=None, settings_inversion: Optional[aa.SettingsInversion]=None, use_preloaded_grid: bool=True, use_hyper_scaling: bool=True):
'\n Wraps a PyAutoFit aggreg... |
def make_object_for_gen(self, fit, galaxies) -> FitImaging:
'\n Creates a `FitImaging` object from a `ModelInstance` that contains the galaxies of a sample from a non-linear\n search.\n\n Parameters\n ----------\n fit\n A PyAutoFit database Fit object containing the gen... | -5,418,655,718,074,749,000 | Creates a `FitImaging` object from a `ModelInstance` that contains the galaxies of a sample from a non-linear
search.
Parameters
----------
fit
A PyAutoFit database Fit object containing the generators of the results of PyAutoGalaxy model-fits.
galaxies
A list of galaxies corresponding to a sample of a non-lin... | autolens/aggregator/fit_imaging.py | make_object_for_gen | Jammy2211/AutoLens | python | def make_object_for_gen(self, fit, galaxies) -> FitImaging:
'\n Creates a `FitImaging` object from a `ModelInstance` that contains the galaxies of a sample from a non-linear\n search.\n\n Parameters\n ----------\n fit\n A PyAutoFit database Fit object containing the gen... |
def _velocity_to_redshift(velocity):
'\n Convert a velocity to a relativistic redshift.\n '
beta = (velocity / C_KMS)
return (np.sqrt(((1 + beta) / (1 - beta))) - 1) | -4,264,383,338,760,901,600 | Convert a velocity to a relativistic redshift. | LI/lib/python3.8/site-packages/astropy/coordinates/spectral_coordinate.py | _velocity_to_redshift | honeybhardwaj/Language_Identification | python | def _velocity_to_redshift(velocity):
'\n \n '
beta = (velocity / C_KMS)
return (np.sqrt(((1 + beta) / (1 - beta))) - 1) |
def _redshift_to_velocity(redshift):
'\n Convert a relativistic redshift to a velocity.\n '
zponesq = ((1 + redshift) ** 2)
return ((C_KMS * (zponesq - 1)) / (zponesq + 1)) | -3,123,915,812,359,021,000 | Convert a relativistic redshift to a velocity. | LI/lib/python3.8/site-packages/astropy/coordinates/spectral_coordinate.py | _redshift_to_velocity | honeybhardwaj/Language_Identification | python | def _redshift_to_velocity(redshift):
'\n \n '
zponesq = ((1 + redshift) ** 2)
return ((C_KMS * (zponesq - 1)) / (zponesq + 1)) |
def _apply_relativistic_doppler_shift(scoord, velocity):
'\n Given a `SpectralQuantity` and a velocity, return a new `SpectralQuantity`\n that is Doppler shifted by this amount.\n\n Note that the Doppler shift applied is the full relativistic one, so\n `SpectralQuantity` currently expressed in velocity ... | -837,969,382,452,347,500 | Given a `SpectralQuantity` and a velocity, return a new `SpectralQuantity`
that is Doppler shifted by this amount.
Note that the Doppler shift applied is the full relativistic one, so
`SpectralQuantity` currently expressed in velocity and not using the
relativistic convention will temporarily be converted to use the
r... | LI/lib/python3.8/site-packages/astropy/coordinates/spectral_coordinate.py | _apply_relativistic_doppler_shift | honeybhardwaj/Language_Identification | python | def _apply_relativistic_doppler_shift(scoord, velocity):
'\n Given a `SpectralQuantity` and a velocity, return a new `SpectralQuantity`\n that is Doppler shifted by this amount.\n\n Note that the Doppler shift applied is the full relativistic one, so\n `SpectralQuantity` currently expressed in velocity ... |
def update_differentials_to_match(original, velocity_reference, preserve_observer_frame=False):
'\n Given an original coordinate object, update the differentials so that\n the final coordinate is at the same location as the original coordinate\n but co-moving with the velocity reference object.\n\n If p... | 8,652,156,971,554,723,000 | Given an original coordinate object, update the differentials so that
the final coordinate is at the same location as the original coordinate
but co-moving with the velocity reference object.
If preserve_original_frame is set to True, the resulting object will be in
the frame of the original coordinate, otherwise it w... | LI/lib/python3.8/site-packages/astropy/coordinates/spectral_coordinate.py | update_differentials_to_match | honeybhardwaj/Language_Identification | python | def update_differentials_to_match(original, velocity_reference, preserve_observer_frame=False):
'\n Given an original coordinate object, update the differentials so that\n the final coordinate is at the same location as the original coordinate\n but co-moving with the velocity reference object.\n\n If p... |
def attach_zero_velocities(coord):
'\n Set the differentials to be stationary on a coordinate object.\n '
new_data = coord.cartesian.with_differentials(ZERO_VELOCITIES)
return coord.realize_frame(new_data) | 624,241,151,493,268,200 | Set the differentials to be stationary on a coordinate object. | LI/lib/python3.8/site-packages/astropy/coordinates/spectral_coordinate.py | attach_zero_velocities | honeybhardwaj/Language_Identification | python | def attach_zero_velocities(coord):
'\n \n '
new_data = coord.cartesian.with_differentials(ZERO_VELOCITIES)
return coord.realize_frame(new_data) |
@staticmethod
def _validate_coordinate(coord, label=''):
'\n Checks the type of the frame and whether a velocity differential and a\n distance has been defined on the frame object.\n\n If no distance is defined, the target is assumed to be "really far\n away", and the observer is assumed... | 4,801,924,817,370,988,000 | Checks the type of the frame and whether a velocity differential and a
distance has been defined on the frame object.
If no distance is defined, the target is assumed to be "really far
away", and the observer is assumed to be "in the solar system".
Parameters
----------
coord : `~astropy.coordinates.BaseCoordinateFra... | LI/lib/python3.8/site-packages/astropy/coordinates/spectral_coordinate.py | _validate_coordinate | honeybhardwaj/Language_Identification | python | @staticmethod
def _validate_coordinate(coord, label=):
'\n Checks the type of the frame and whether a velocity differential and a\n distance has been defined on the frame object.\n\n If no distance is defined, the target is assumed to be "really far\n away", and the observer is assumed t... |
End of preview. Expand in Data Studio
- Downloads last month
- 24