nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
IdentityPython/pysaml2
6badb32d212257bd83ffcc816f9b625f68281b47
src/saml2/authn_context/sslcert.py
python
activation_limit_usages_type__from_string
(xml_string)
return saml2.create_class_from_xml_string(ActivationLimitUsagesType_, xml_string)
[]
def activation_limit_usages_type__from_string(xml_string): return saml2.create_class_from_xml_string(ActivationLimitUsagesType_, xml_string)
[ "def", "activation_limit_usages_type__from_string", "(", "xml_string", ")", ":", "return", "saml2", ".", "create_class_from_xml_string", "(", "ActivationLimitUsagesType_", ",", "xml_string", ")" ]
https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/authn_context/sslcert.py#L344-L346
OpenAgricultureFoundation/openag-device-software
a51d2de399c0a6781ae51d0dcfaae1583d75f346
device/iot/pubsub.py
python
PubSub.load_mqtt_config
(self)
Loads mqtt config.
Loads mqtt config.
[ "Loads", "mqtt", "config", "." ]
def load_mqtt_config(self) -> None: """Loads mqtt config.""" self.logger.debug("Loading mqtt config") # Load settings from environment variables try: self.project_id = os.environ["GCLOUD_PROJECT"] self.cloud_region = os.environ["GCLOUD_REGION"] self.registry_id = os.environ["GCLOUD_DEV_REG"] self.device_id = registration.device_id() self.private_key_filepath = os.environ["IOT_PRIVATE_KEY"] self.ca_certs = os.environ["CA_CERTS"] except KeyError as e: message = "Unable to load pubsub config, key {} is required".format(e) self.logger.critical(message) raise # Initialize client id self.client_id = "projects/{}/locations/{}/registries/{}/devices/{}".format( self.project_id, self.cloud_region, self.registry_id, self.device_id ) # Initialize config topic self.config_topic = "/devices/{}/config".format(self.device_id) # Initialize commands topic self.command_topic = "/devices/{}/commands/#".format(self.device_id) # Initialize event topic test_telemetry_topic = os.environ.get("IOT_TEST_TOPIC") if test_telemetry_topic is not None: self.telemetry_topic = "/devices/{}/{}".format(self.device_id, test_telemetry_topic) self.logger.debug("Publishing to test topic: {}".format(self.telemetry_topic)) else: self.telemetry_topic = "/devices/{}/events".format(self.device_id)
[ "def", "load_mqtt_config", "(", "self", ")", "->", "None", ":", "self", ".", "logger", ".", "debug", "(", "\"Loading mqtt config\"", ")", "# Load settings from environment variables", "try", ":", "self", ".", "project_id", "=", "os", ".", "environ", "[", "\"GCLO...
https://github.com/OpenAgricultureFoundation/openag-device-software/blob/a51d2de399c0a6781ae51d0dcfaae1583d75f346/device/iot/pubsub.py#L79-L113
ring04h/wyportmap
c4201e2313504e780a7f25238eba2a2d3223e739
sqlalchemy/ext/associationproxy.py
python
_AssociationList.__iter__
(self)
Iterate over proxied values. For the actual domain objects, iterate over .col instead or just use the underlying collection directly from its property on the parent.
Iterate over proxied values.
[ "Iterate", "over", "proxied", "values", "." ]
def __iter__(self): """Iterate over proxied values. For the actual domain objects, iterate over .col instead or just use the underlying collection directly from its property on the parent. """ for member in self.col: yield self._get(member) raise StopIteration
[ "def", "__iter__", "(", "self", ")", ":", "for", "member", "in", "self", ".", "col", ":", "yield", "self", ".", "_get", "(", "member", ")", "raise", "StopIteration" ]
https://github.com/ring04h/wyportmap/blob/c4201e2313504e780a7f25238eba2a2d3223e739/sqlalchemy/ext/associationproxy.py#L582-L592
bitcraze/crazyflie-clients-python
65d433a945b097333e5681a937354045dd4b66f4
src/cfclient/utils/config_manager.py
python
ConfigManager.get_list_of_configs
(self)
return self._list_of_configs
Reload the configurations from file
Reload the configurations from file
[ "Reload", "the", "configurations", "from", "file" ]
def get_list_of_configs(self): """Reload the configurations from file""" try: configs = [os.path.basename(f) for f in glob.glob(self.configs_dir + "/[A-Za-z]*.json")] self._input_config = [] self._input_settings = [] self._list_of_configs = [] for conf in configs: logger.debug("Parsing [%s]", conf) json_data = open(self.configs_dir + "/%s" % conf) data = json.load(json_data) new_input_device = {} new_input_settings = {"updateperiod": 10, "springythrottle": True, "rp_dead_band": 0.05} for s in data["inputconfig"]["inputdevice"]: if s == "axis": for a in data["inputconfig"]["inputdevice"]["axis"]: axis = {} axis["scale"] = a["scale"] axis["offset"] = a[ "offset"] if "offset" in a else 0.0 axis["type"] = a["type"] axis["key"] = a["key"] axis["name"] = a["name"] self._translate_for_backwards_compatibility(axis) try: ids = a["ids"] except Exception: ids = [a["id"]] for id in ids: locaxis = copy.deepcopy(axis) if "ids" in a: if id == a["ids"][0]: locaxis["scale"] = locaxis[ "scale"] * -1 locaxis["id"] = id # 'type'-'id' defines unique index for axis index = "%s-%d" % (a["type"], id) new_input_device[index] = locaxis else: new_input_settings[s] = data[ "inputconfig"]["inputdevice"][s] self._input_config.append(new_input_device) self._input_settings.append(new_input_settings) json_data.close() self._list_of_configs.append(conf[:-5]) except Exception as e: logger.warning("Exception while parsing inputconfig file: %s ", e) return self._list_of_configs
[ "def", "get_list_of_configs", "(", "self", ")", ":", "try", ":", "configs", "=", "[", "os", ".", "path", ".", "basename", "(", "f", ")", "for", "f", "in", "glob", ".", "glob", "(", "self", ".", "configs_dir", "+", "\"/[A-Za-z]*.json\"", ")", "]", "se...
https://github.com/bitcraze/crazyflie-clients-python/blob/65d433a945b097333e5681a937354045dd4b66f4/src/cfclient/utils/config_manager.py#L76-L128
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/e3/papylib/papyon/papyon/media/stream.py
python
MediaStream.local_candidates_prepared
(self)
Called by the stream handler once all the local candidates are found
Called by the stream handler once all the local candidates are found
[ "Called", "by", "the", "stream", "handler", "once", "all", "the", "local", "candidates", "are", "found" ]
def local_candidates_prepared(self): """Called by the stream handler once all the local candidates are found""" if self._local_candidates_prepared: return logger.debug("Media stream %s is prepared" % self.name) self._local_candidates_prepared = True if self.prepared: self.emit("prepared")
[ "def", "local_candidates_prepared", "(", "self", ")", ":", "if", "self", ".", "_local_candidates_prepared", ":", "return", "logger", ".", "debug", "(", "\"Media stream %s is prepared\"", "%", "self", ".", "name", ")", "self", ".", "_local_candidates_prepared", "=", ...
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/papylib/papyon/papyon/media/stream.py#L248-L256
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/lib/pyxmpp/jabber/muc.py
python
MucRoomState.change_nick
(self,new_nick)
Send a nick change request to the room. :Parameters: - `new_nick`: the new nickname requested. :Types: - `new_nick`: `unicode`
Send a nick change request to the room.
[ "Send", "a", "nick", "change", "request", "to", "the", "room", "." ]
def change_nick(self,new_nick): """ Send a nick change request to the room. :Parameters: - `new_nick`: the new nickname requested. :Types: - `new_nick`: `unicode` """ new_room_jid=JID(self.room_jid.node,self.room_jid.domain,new_nick) p=Presence(to_jid=new_room_jid) self.manager.stream.send(p)
[ "def", "change_nick", "(", "self", ",", "new_nick", ")", ":", "new_room_jid", "=", "JID", "(", "self", ".", "room_jid", ".", "node", ",", "self", ".", "room_jid", ".", "domain", ",", "new_nick", ")", "p", "=", "Presence", "(", "to_jid", "=", "new_room_...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/lib/pyxmpp/jabber/muc.py#L517-L528
rndusr/stig
334f03e2e3eda7c1856dd5489f0265a47b9861b6
stig/tui/views/base.py
python
ListWidgetBase.mark
(self, toggle=False, all=False)
Mark the currently focused item or all items
Mark the currently focused item or all items
[ "Mark", "the", "currently", "focused", "item", "or", "all", "items" ]
def mark(self, toggle=False, all=False): """Mark the currently focused item or all items""" self._set_mark(True, toggle=toggle, all=all)
[ "def", "mark", "(", "self", ",", "toggle", "=", "False", ",", "all", "=", "False", ")", ":", "self", ".", "_set_mark", "(", "True", ",", "toggle", "=", "toggle", ",", "all", "=", "all", ")" ]
https://github.com/rndusr/stig/blob/334f03e2e3eda7c1856dd5489f0265a47b9861b6/stig/tui/views/base.py#L399-L401
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/data_safe/data_safe_client.py
python
DataSafeClient.list_users
(self, user_assessment_id, **kwargs)
Gets a list of users of the specified user assessment. The result contains the database user details for each user, such as user type, account status, last login time, user creation time, authentication type, user profile, and the date and time of the latest password change. It also contains the user category derived from these user details as well as privileges granted to each user. :param str user_assessment_id: (required) The OCID of the user assessment. :param int limit: (optional) For list pagination. The maximum number of items to return per page in a paginated \"List\" call. For details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/usingapi.htm#nine :param bool compartment_id_in_subtree: (optional) Default is false. When set to true, the hierarchy of compartments is traversed and all compartments and subcompartments in the tenancy are returned. Depends on the 'accessLevel' setting. :param str access_level: (optional) Valid values are RESTRICTED and ACCESSIBLE. Default is RESTRICTED. Setting this to ACCESSIBLE returns only those compartments for which the user has INSPECT permissions directly or indirectly (permissions can be on a resource in a subcompartment). When set to RESTRICTED permissions are checked and no partial results are displayed. Allowed values are: "RESTRICTED", "ACCESSIBLE" :param str user_category: (optional) A filter to return only items that match the specified user category. :param str user_key: (optional) A filter to return only items that match the specified user key. :param str account_status: (optional) A filter to return only items that match the specified account status. :param str authentication_type: (optional) A filter to return only items that match the specified authentication type. :param str user_name: (optional) A filter to return only items that match the specified user name. :param str target_id: (optional) A filter to return only items that match the specified target. :param datetime time_last_login_greater_than_or_equal_to: (optional) A filter to return users whose last login time in the database is greater than or equal to the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_last_login_less_than: (optional) A filter to return users whose last login time in the database is less than the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_user_created_greater_than_or_equal_to: (optional) A filter to return users whose creation time in the database is greater than or equal to the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_user_created_less_than: (optional) A filter to return users whose creation time in the database is less than the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_password_last_changed_greater_than_or_equal_to: (optional) A filter to return users whose last password change in the database is greater than or equal to the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_password_last_changed_less_than: (optional) A filter to return users whose last password change in the database is less than the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param str page: (optional) For list pagination. The page token representing the page at which to start retrieving results. It is usually retrieved from a previous \"List\" call. For details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/usingapi.htm#nine :param str sort_order: (optional) The sort order to use, either ascending (ASC) or descending (DESC). Allowed values are: "ASC", "DESC" :param str sort_by: (optional) The field to sort by. You can specify only one sort order (sortOrder). The default order for userName is ascending. Allowed values are: "userName", "userCategory", "accountStatus", "timeLastLogin", "targetId", "timeUserCreated", "authenticationType", "timePasswordChanged" :param str opc_request_id: (optional) Unique identifier for the request. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type list of :class:`~oci.data_safe.models.UserSummary` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/datasafe/list_users.py.html>`__ to see an example of how to use list_users API.
Gets a list of users of the specified user assessment. The result contains the database user details for each user, such as user type, account status, last login time, user creation time, authentication type, user profile, and the date and time of the latest password change. It also contains the user category derived from these user details as well as privileges granted to each user.
[ "Gets", "a", "list", "of", "users", "of", "the", "specified", "user", "assessment", ".", "The", "result", "contains", "the", "database", "user", "details", "for", "each", "user", "such", "as", "user", "type", "account", "status", "last", "login", "time", "...
def list_users(self, user_assessment_id, **kwargs): """ Gets a list of users of the specified user assessment. The result contains the database user details for each user, such as user type, account status, last login time, user creation time, authentication type, user profile, and the date and time of the latest password change. It also contains the user category derived from these user details as well as privileges granted to each user. :param str user_assessment_id: (required) The OCID of the user assessment. :param int limit: (optional) For list pagination. The maximum number of items to return per page in a paginated \"List\" call. For details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/usingapi.htm#nine :param bool compartment_id_in_subtree: (optional) Default is false. When set to true, the hierarchy of compartments is traversed and all compartments and subcompartments in the tenancy are returned. Depends on the 'accessLevel' setting. :param str access_level: (optional) Valid values are RESTRICTED and ACCESSIBLE. Default is RESTRICTED. Setting this to ACCESSIBLE returns only those compartments for which the user has INSPECT permissions directly or indirectly (permissions can be on a resource in a subcompartment). When set to RESTRICTED permissions are checked and no partial results are displayed. Allowed values are: "RESTRICTED", "ACCESSIBLE" :param str user_category: (optional) A filter to return only items that match the specified user category. :param str user_key: (optional) A filter to return only items that match the specified user key. :param str account_status: (optional) A filter to return only items that match the specified account status. :param str authentication_type: (optional) A filter to return only items that match the specified authentication type. :param str user_name: (optional) A filter to return only items that match the specified user name. :param str target_id: (optional) A filter to return only items that match the specified target. :param datetime time_last_login_greater_than_or_equal_to: (optional) A filter to return users whose last login time in the database is greater than or equal to the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_last_login_less_than: (optional) A filter to return users whose last login time in the database is less than the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_user_created_greater_than_or_equal_to: (optional) A filter to return users whose creation time in the database is greater than or equal to the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_user_created_less_than: (optional) A filter to return users whose creation time in the database is less than the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_password_last_changed_greater_than_or_equal_to: (optional) A filter to return users whose last password change in the database is greater than or equal to the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param datetime time_password_last_changed_less_than: (optional) A filter to return users whose last password change in the database is less than the date and time specified, in the format defined by `RFC3339`__. **Example:** 2016-12-19T16:39:57.600Z __ https://tools.ietf.org/html/rfc3339 :param str page: (optional) For list pagination. The page token representing the page at which to start retrieving results. It is usually retrieved from a previous \"List\" call. For details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/usingapi.htm#nine :param str sort_order: (optional) The sort order to use, either ascending (ASC) or descending (DESC). Allowed values are: "ASC", "DESC" :param str sort_by: (optional) The field to sort by. You can specify only one sort order (sortOrder). The default order for userName is ascending. Allowed values are: "userName", "userCategory", "accountStatus", "timeLastLogin", "targetId", "timeUserCreated", "authenticationType", "timePasswordChanged" :param str opc_request_id: (optional) Unique identifier for the request. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type list of :class:`~oci.data_safe.models.UserSummary` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/datasafe/list_users.py.html>`__ to see an example of how to use list_users API. """ resource_path = "/userAssessments/{userAssessmentId}/users" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "limit", "compartment_id_in_subtree", "access_level", "user_category", "user_key", "account_status", "authentication_type", "user_name", "target_id", "time_last_login_greater_than_or_equal_to", "time_last_login_less_than", "time_user_created_greater_than_or_equal_to", "time_user_created_less_than", "time_password_last_changed_greater_than_or_equal_to", "time_password_last_changed_less_than", "page", "sort_order", "sort_by", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "list_users got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "userAssessmentId": user_assessment_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) if 'access_level' in kwargs: access_level_allowed_values = ["RESTRICTED", "ACCESSIBLE"] if kwargs['access_level'] not in access_level_allowed_values: raise ValueError( "Invalid value for `access_level`, must be one of {0}".format(access_level_allowed_values) ) if 'sort_order' in kwargs: sort_order_allowed_values = ["ASC", "DESC"] if kwargs['sort_order'] not in sort_order_allowed_values: raise ValueError( "Invalid value for `sort_order`, must be one of {0}".format(sort_order_allowed_values) ) if 'sort_by' in kwargs: sort_by_allowed_values = ["userName", "userCategory", "accountStatus", "timeLastLogin", "targetId", "timeUserCreated", "authenticationType", "timePasswordChanged"] if kwargs['sort_by'] not in sort_by_allowed_values: raise ValueError( "Invalid value for `sort_by`, must be one of {0}".format(sort_by_allowed_values) ) query_params = { "limit": kwargs.get("limit", missing), "compartmentIdInSubtree": kwargs.get("compartment_id_in_subtree", missing), "accessLevel": kwargs.get("access_level", missing), "userCategory": kwargs.get("user_category", missing), "userKey": kwargs.get("user_key", missing), "accountStatus": kwargs.get("account_status", missing), "authenticationType": kwargs.get("authentication_type", missing), "userName": kwargs.get("user_name", missing), "targetId": kwargs.get("target_id", missing), "timeLastLoginGreaterThanOrEqualTo": kwargs.get("time_last_login_greater_than_or_equal_to", missing), "timeLastLoginLessThan": kwargs.get("time_last_login_less_than", missing), "timeUserCreatedGreaterThanOrEqualTo": kwargs.get("time_user_created_greater_than_or_equal_to", missing), "timeUserCreatedLessThan": kwargs.get("time_user_created_less_than", missing), "timePasswordLastChangedGreaterThanOrEqualTo": kwargs.get("time_password_last_changed_greater_than_or_equal_to", missing), "timePasswordLastChangedLessThan": kwargs.get("time_password_last_changed_less_than", missing), "page": kwargs.get("page", missing), "sortOrder": kwargs.get("sort_order", missing), "sortBy": kwargs.get("sort_by", missing) } query_params = {k: v for (k, v) in six.iteritems(query_params) if v is not missing and v is not None} header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, query_params=query_params, header_params=header_params, response_type="list[UserSummary]") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, query_params=query_params, header_params=header_params, response_type="list[UserSummary]")
[ "def", "list_users", "(", "self", ",", "user_assessment_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/userAssessments/{userAssessmentId}/users\"", "method", "=", "\"GET\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/data_safe/data_safe_client.py#L4785-L5017
isnowfy/pydown
71ecc891868cd2a34b7e5fe662c99474f2d0fd7f
main.py
python
slides_split
(slides)
[]
def slides_split(slides): data = '' css = '' for item in slides.split('\n'): if item.startswith('!SLIDE'): yield css, data css = ' '.join(item.split(' ')[1:]) data = '' else: data += item+'\n' yield css, data
[ "def", "slides_split", "(", "slides", ")", ":", "data", "=", "''", "css", "=", "''", "for", "item", "in", "slides", ".", "split", "(", "'\\n'", ")", ":", "if", "item", ".", "startswith", "(", "'!SLIDE'", ")", ":", "yield", "css", ",", "data", "css"...
https://github.com/isnowfy/pydown/blob/71ecc891868cd2a34b7e5fe662c99474f2d0fd7f/main.py#L25-L35
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/site-packages/setuptools/command/build_py.py
python
build_py.build_package_data
(self)
Copy data files into build directory
Copy data files into build directory
[ "Copy", "data", "files", "into", "build", "directory" ]
def build_package_data(self): """Copy data files into build directory""" for package, src_dir, build_dir, filenames in self.data_files: for filename in filenames: target = os.path.join(build_dir, filename) self.mkpath(os.path.dirname(target)) srcfile = os.path.join(src_dir, filename) outf, copied = self.copy_file(srcfile, target) srcfile = os.path.abspath(srcfile) if (copied and srcfile in self.distribution.convert_2to3_doctests): self.__doctests_2to3.append(outf)
[ "def", "build_package_data", "(", "self", ")", ":", "for", "package", ",", "src_dir", ",", "build_dir", ",", "filenames", "in", "self", ".", "data_files", ":", "for", "filename", "in", "filenames", ":", "target", "=", "os", ".", "path", ".", "join", "(",...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/site-packages/setuptools/command/build_py.py#L116-L127
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/progress.py
python
Bar.__init__
( self, label="", width=32, hide=None, empty_char=BAR_EMPTY_CHAR, filled_char=BAR_FILLED_CHAR, expected_size=None, every=1, )
[]
def __init__( self, label="", width=32, hide=None, empty_char=BAR_EMPTY_CHAR, filled_char=BAR_FILLED_CHAR, expected_size=None, every=1, ): self.label = label self.width = width self.hide = hide # Only show bar in terminals by default (better for piping, logging etc.) if hide is None: try: self.hide = not STREAM.isatty() except AttributeError: # output does not support isatty() self.hide = True self.empty_char = empty_char self.filled_char = filled_char self.expected_size = expected_size self.every = every self.start = time.time() self.ittimes = [] self.eta = 0 self.etadelta = time.time() self.etadisp = self.format_time(self.eta) self.last_progress = 0 if self.expected_size: self.show(0)
[ "def", "__init__", "(", "self", ",", "label", "=", "\"\"", ",", "width", "=", "32", ",", "hide", "=", "None", ",", "empty_char", "=", "BAR_EMPTY_CHAR", ",", "filled_char", "=", "BAR_FILLED_CHAR", ",", "expected_size", "=", "None", ",", "every", "=", "1",...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/progress.py#L60-L90
deepinsight/insightface
c0b25f998a649f662c7136eb389abcacd7900e9d
python-package/insightface/utils/filesystem.py
python
try_import_cv2
()
return try_import('cv2', msg)
Try import cv2 at runtime. Returns ------- cv2 module if found. Raise ImportError otherwise
Try import cv2 at runtime.
[ "Try", "import", "cv2", "at", "runtime", "." ]
def try_import_cv2(): """Try import cv2 at runtime. Returns ------- cv2 module if found. Raise ImportError otherwise """ msg = "cv2 is required, you can install by package manager, e.g. 'apt-get', \ or `pip install opencv-python --user` (note that this is unofficial PYPI package)." return try_import('cv2', msg)
[ "def", "try_import_cv2", "(", ")", ":", "msg", "=", "\"cv2 is required, you can install by package manager, e.g. 'apt-get', \\\n or `pip install opencv-python --user` (note that this is unofficial PYPI package).\"", "return", "try_import", "(", "'cv2'", ",", "msg", ")" ]
https://github.com/deepinsight/insightface/blob/c0b25f998a649f662c7136eb389abcacd7900e9d/python-package/insightface/utils/filesystem.py#L54-L65
iterative/dvc
13238e97168007cb5ba21966368457776274b9ca
dvc/machine/backend/terraform.py
python
TerraformBackend.rename
(self, name: str, new: str, **config)
rename a dvc machine instance to a new name
rename a dvc machine instance to a new name
[ "rename", "a", "dvc", "machine", "instance", "to", "a", "new", "name" ]
def rename(self, name: str, new: str, **config): """rename a dvc machine instance to a new name""" import shutil mtype = "iterative_machine" new_dir = os.path.join(self.tmp_dir, new) old_dir = os.path.join(self.tmp_dir, name) if os.path.exists(new_dir): raise DvcException(f"rename failed: path {new_dir} already exists") if not os.path.exists(old_dir): return with self.make_tpi(name) as tpi: tpi.state_mv(f"{mtype}.{name}", f"{mtype}.{new}", **config) shutil.move(old_dir, new_dir)
[ "def", "rename", "(", "self", ",", "name", ":", "str", ",", "new", ":", "str", ",", "*", "*", "config", ")", ":", "import", "shutil", "mtype", "=", "\"iterative_machine\"", "new_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "tmp_dir", ...
https://github.com/iterative/dvc/blob/13238e97168007cb5ba21966368457776274b9ca/dvc/machine/backend/terraform.py#L86-L103
apeterswu/RL4NMT
3c66a2d8142abc5ce73db63e05d3cc9bf4663b65
tensor2tensor/layers/common_attention.py
python
combine_last_two_dimensions
(x)
return ret
Reshape x so that the last two dimension become one. Args: x: a Tensor with shape [..., a, b] Returns: a Tensor with shape [..., ab]
Reshape x so that the last two dimension become one.
[ "Reshape", "x", "so", "that", "the", "last", "two", "dimension", "become", "one", "." ]
def combine_last_two_dimensions(x): """Reshape x so that the last two dimension become one. Args: x: a Tensor with shape [..., a, b] Returns: a Tensor with shape [..., ab] """ old_shape = x.get_shape().dims a, b = old_shape[-2:] new_shape = old_shape[:-2] + [a * b if a and b else None] ret = tf.reshape(x, tf.concat([tf.shape(x)[:-2], [-1]], 0)) ret.set_shape(new_shape) return ret
[ "def", "combine_last_two_dimensions", "(", "x", ")", ":", "old_shape", "=", "x", ".", "get_shape", "(", ")", ".", "dims", "a", ",", "b", "=", "old_shape", "[", "-", "2", ":", "]", "new_shape", "=", "old_shape", "[", ":", "-", "2", "]", "+", "[", ...
https://github.com/apeterswu/RL4NMT/blob/3c66a2d8142abc5ce73db63e05d3cc9bf4663b65/tensor2tensor/layers/common_attention.py#L766-L780
pabigot/pyxb
14737c23a125fd12c954823ad64fc4497816fae3
pyxb/namespace/__init__.py
python
Namespace.initialNamespaceContext
(self)
return self.__initialNamespaceContext
Obtain the namespace context to be used when creating components in this namespace. Usually applies only to built-in namespaces, but is also used in the autotests when creating a namespace without a xs:schema element. . Note that we must create the instance dynamically, since the information that goes into it has cross-dependencies that can't be resolved until this module has been completely loaded.
Obtain the namespace context to be used when creating components in this namespace.
[ "Obtain", "the", "namespace", "context", "to", "be", "used", "when", "creating", "components", "in", "this", "namespace", "." ]
def initialNamespaceContext (self): """Obtain the namespace context to be used when creating components in this namespace. Usually applies only to built-in namespaces, but is also used in the autotests when creating a namespace without a xs:schema element. . Note that we must create the instance dynamically, since the information that goes into it has cross-dependencies that can't be resolved until this module has been completely loaded.""" if self.__initialNamespaceContext is None: isn = { } if self.__contextInScopeNamespaces is not None: for (k, v) in six.iteritems(self.__contextInScopeNamespaces): isn[k] = self.__identifyNamespace(v) kw = { 'target_namespace' : self , 'default_namespace' : self.__identifyNamespace(self.__contextDefaultNamespace) , 'in_scope_namespaces' : isn } self.__initialNamespaceContext = resolution.NamespaceContext(None, **kw) return self.__initialNamespaceContext
[ "def", "initialNamespaceContext", "(", "self", ")", ":", "if", "self", ".", "__initialNamespaceContext", "is", "None", ":", "isn", "=", "{", "}", "if", "self", ".", "__contextInScopeNamespaces", "is", "not", "None", ":", "for", "(", "k", ",", "v", ")", "...
https://github.com/pabigot/pyxb/blob/14737c23a125fd12c954823ad64fc4497816fae3/pyxb/namespace/__init__.py#L993-L1011
openbmc/openbmc
5f4109adae05f4d6925bfe960007d52f98c61086
poky/bitbake/lib/toaster/orm/models.py
python
Target.clone_sdk_artifacts_from
(self, target)
Clone TargetSDKFile objects from target and associate them with this target.
Clone TargetSDKFile objects from target and associate them with this target.
[ "Clone", "TargetSDKFile", "objects", "from", "target", "and", "associate", "them", "with", "this", "target", "." ]
def clone_sdk_artifacts_from(self, target): """ Clone TargetSDKFile objects from target and associate them with this target. """ sdk_files = target.targetsdkfile_set.all() for sdk_file in sdk_files: sdk_file.pk = None sdk_file.target = self sdk_file.save()
[ "def", "clone_sdk_artifacts_from", "(", "self", ",", "target", ")", ":", "sdk_files", "=", "target", ".", "targetsdkfile_set", ".", "all", "(", ")", "for", "sdk_file", "in", "sdk_files", ":", "sdk_file", ".", "pk", "=", "None", "sdk_file", ".", "target", "...
https://github.com/openbmc/openbmc/blob/5f4109adae05f4d6925bfe960007d52f98c61086/poky/bitbake/lib/toaster/orm/models.py#L928-L937
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/FeedMitreAttackv2/Integrations/FeedMitreAttackv2/FeedMitreAttackv2.py
python
create_relationship
(item_json, id_to_name)
return None
Create a single relation with the given arguments.
Create a single relation with the given arguments.
[ "Create", "a", "single", "relation", "with", "the", "given", "arguments", "." ]
def create_relationship(item_json, id_to_name): """ Create a single relation with the given arguments. """ a_type = item_json.get('source_ref').split('--')[0] a_type = MITRE_TYPE_TO_DEMISTO_TYPE.get(a_type) b_type = item_json.get('target_ref').split('--')[0] b_type = MITRE_TYPE_TO_DEMISTO_TYPE.get(b_type) mapping_fields = { 'description': item_json.get('description'), 'lastseenbysource': item_json.get('modified'), 'firstseenbysource': item_json.get('created') } if item_json.get('relationship_type') not in RELATIONSHIP_TYPES: demisto.debug(f"Invalid relation type: {item_json.get('relationship_type')}") return entity_a = id_to_name.get(item_json.get('source_ref')) entity_b = id_to_name.get(item_json.get('target_ref')) if entity_b and entity_a: return EntityRelationship(name=item_json.get('relationship_type'), entity_a=entity_a, entity_a_type=a_type, entity_b=entity_b, entity_b_type=b_type, fields=mapping_fields) return None
[ "def", "create_relationship", "(", "item_json", ",", "id_to_name", ")", ":", "a_type", "=", "item_json", ".", "get", "(", "'source_ref'", ")", ".", "split", "(", "'--'", ")", "[", "0", "]", "a_type", "=", "MITRE_TYPE_TO_DEMISTO_TYPE", ".", "get", "(", "a_t...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/FeedMitreAttackv2/Integrations/FeedMitreAttackv2/FeedMitreAttackv2.py#L319-L348
BMW-InnovationLab/BMW-TensorFlow-Training-GUI
4f10d1f00f9ac312ca833e5b28fd0f8952cfee17
training_api/research/object_detection/utils/np_box_mask_list_ops.py
python
concatenate
(box_mask_lists, fields=None)
return box_list_to_box_mask_list( np_box_list_ops.concatenate(boxlists=box_mask_lists, fields=fields))
Concatenate list of box_mask_lists. This op concatenates a list of input box_mask_lists into a larger box_mask_list. It also handles concatenation of box_mask_list fields as long as the field tensor shapes are equal except for the first dimension. Args: box_mask_lists: list of np_box_mask_list.BoxMaskList objects fields: optional list of fields to also concatenate. By default, all fields from the first BoxMaskList in the list are included in the concatenation. Returns: a box_mask_list with number of boxes equal to sum([box_mask_list.num_boxes() for box_mask_list in box_mask_list]) Raises: ValueError: if box_mask_lists is invalid (i.e., is not a list, is empty, or contains non box_mask_list objects), or if requested fields are not contained in all box_mask_lists
Concatenate list of box_mask_lists.
[ "Concatenate", "list", "of", "box_mask_lists", "." ]
def concatenate(box_mask_lists, fields=None): """Concatenate list of box_mask_lists. This op concatenates a list of input box_mask_lists into a larger box_mask_list. It also handles concatenation of box_mask_list fields as long as the field tensor shapes are equal except for the first dimension. Args: box_mask_lists: list of np_box_mask_list.BoxMaskList objects fields: optional list of fields to also concatenate. By default, all fields from the first BoxMaskList in the list are included in the concatenation. Returns: a box_mask_list with number of boxes equal to sum([box_mask_list.num_boxes() for box_mask_list in box_mask_list]) Raises: ValueError: if box_mask_lists is invalid (i.e., is not a list, is empty, or contains non box_mask_list objects), or if requested fields are not contained in all box_mask_lists """ if fields is not None: if 'masks' not in fields: fields.append('masks') return box_list_to_box_mask_list( np_box_list_ops.concatenate(boxlists=box_mask_lists, fields=fields))
[ "def", "concatenate", "(", "box_mask_lists", ",", "fields", "=", "None", ")", ":", "if", "fields", "is", "not", "None", ":", "if", "'masks'", "not", "in", "fields", ":", "fields", ".", "append", "(", "'masks'", ")", "return", "box_list_to_box_mask_list", "...
https://github.com/BMW-InnovationLab/BMW-TensorFlow-Training-GUI/blob/4f10d1f00f9ac312ca833e5b28fd0f8952cfee17/training_api/research/object_detection/utils/np_box_mask_list_ops.py#L340-L366
mozilla/crontabber
d3a116cf2b70fa0d1030f671ceaf5cf11e825aa8
crontabber/app.py
python
CronTabberBase.time_to_run
(self, class_, time_)
return False
return true if it's time to run the job. This is true if there is no previous information about its last run or if the last time it ran and set its next_run to a date that is now past.
return true if it's time to run the job. This is true if there is no previous information about its last run or if the last time it ran and set its next_run to a date that is now past.
[ "return", "true", "if", "it", "s", "time", "to", "run", "the", "job", ".", "This", "is", "true", "if", "there", "is", "no", "previous", "information", "about", "its", "last", "run", "or", "if", "the", "last", "time", "it", "ran", "and", "set", "its",...
def time_to_run(self, class_, time_): """return true if it's time to run the job. This is true if there is no previous information about its last run or if the last time it ran and set its next_run to a date that is now past. """ app_name = class_.app_name try: info = self.job_state_database[app_name] except KeyError: if time_: h, m = [int(x) for x in time_.split(':')] # only run if this hour and minute is < now now = utc_now() if now.hour > h: return True elif now.hour == h and now.minute >= m: return True return False else: # no past information, run now return True next_run = info['next_run'] if not next_run: # It has never run before. # If it has an active ongoing status it means two # independent threads tried to start it. The second one # (by a tiny time margin) will have a job_class whose # `ongoing` value has already been set. # If that's the case, let it through because it will # commence and break due to RowLevelLockError in the # state's __setitem__ method. return bool(info['ongoing']) if next_run < utc_now(): return True return False
[ "def", "time_to_run", "(", "self", ",", "class_", ",", "time_", ")", ":", "app_name", "=", "class_", ".", "app_name", "try", ":", "info", "=", "self", ".", "job_state_database", "[", "app_name", "]", "except", "KeyError", ":", "if", "time_", ":", "h", ...
https://github.com/mozilla/crontabber/blob/d3a116cf2b70fa0d1030f671ceaf5cf11e825aa8/crontabber/app.py#L1195-L1232
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/codeintel2/lang_perl.py
python
PerlLangIntel.async_eval_at_trg
(self, buf, trg, ctlr)
[]
def async_eval_at_trg(self, buf, trg, ctlr): if _xpcom_: trg = UnwrapObject(trg) ctlr = UnwrapObject(ctlr) assert trg.lang == "Perl" ctlr.start(buf, trg) if trg.id == ("Perl", TRG_FORM_CPLN, "available-imports"): evalr = PerlImportsEvaluator(ctlr, buf, trg) buf.mgr.request_eval(evalr) return # Remaining triggers all use this parsed CITDL expr. # Extract the leading CITDL expression (and possible filter, # i.e. '$', '@', ...). try: citdl_expr, filter \ = self.citdl_expr_and_prefix_filter_from_trg(buf, trg) except CodeIntelError as ex: ctlr.error(str(ex)) ctlr.done("error") return # Perl's trg_from_pos doesn't distinguish btwn "package-subs" # and "object-subs" trigger type -- calling them both "*-subs". # Let's do so here. if trg.type == "*-subs": assert citdl_expr if isident(citdl_expr[0]): trg.type = "package-subs" else: trg.type = "object-subs" if trg.id == ("Perl", TRG_FORM_CPLN, "package-members"): # [prefix]SomePackage::<|> # Note: This trigger has the "prefix" extra attr which could # be used instead of the leading CITDL expr parse. line = buf.accessor.line_from_pos(trg.pos) evalr = PerlPackageMembersTreeEvaluator(ctlr, buf, trg, citdl_expr, line, filter) buf.mgr.request_eval(evalr) elif trg.id == ("Perl", TRG_FORM_CPLN, "package-subs"): # SomePackage-><|> assert not filter, "shouldn't be Perl filter prefix for " \ "'complete-package-subs': %r" % filter line = buf.accessor.line_from_pos(trg.pos) evalr = PerlPackageSubsTreeEvaluator( ctlr, buf, trg, citdl_expr, line) buf.mgr.request_eval(evalr) # TODO: Might want to handle TRG_FORM_DEFN differently. else: if citdl_expr is None: ctlr.info("no CITDL expression found for %s" % trg) ctlr.done("no trigger") return line = buf.accessor.line_from_pos(trg.pos) if trg.id[1] == TRG_FORM_DEFN and citdl_expr[0] == '$': current_pos = trg.pos lim = buf.accessor.length() while buf.accessor.style_at_pos(current_pos) == ScintillaConstants.SCE_PL_SCALAR and current_pos < lim: current_pos += 1 c = buf.accessor.char_at_pos(current_pos) if c == '[': citdl_expr = '@' + citdl_expr[1:] elif c == '{': citdl_expr = '%' + citdl_expr[1:] evalr = PerlTreeEvaluator(ctlr, buf, trg, citdl_expr, line, filter) buf.mgr.request_eval(evalr)
[ "def", "async_eval_at_trg", "(", "self", ",", "buf", ",", "trg", ",", "ctlr", ")", ":", "if", "_xpcom_", ":", "trg", "=", "UnwrapObject", "(", "trg", ")", "ctlr", "=", "UnwrapObject", "(", "ctlr", ")", "assert", "trg", ".", "lang", "==", "\"Perl\"", ...
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/codeintel2/lang_perl.py#L938-L1006
zhaoolee/StarsAndClown
b2d4039cad2f9232b691e5976f787b49a0a2c113
node_modules/npmi/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetLdflags
(self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir)
return ldflags, intermediate_manifest, manifest_files
Returns the flags that need to be added to link commands, and the manifest files.
Returns the flags that need to be added to link commands, and the manifest files.
[ "Returns", "the", "flags", "that", "need", "to", "be", "added", "to", "link", "commands", "and", "the", "manifest", "files", "." ]
def GetLdflags(self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir): """Returns the flags that need to be added to link commands, and the manifest files.""" config = self._TargetConfig(config) ldflags = [] ld = self._GetWrapper(self, self.msvs_settings[config], 'VCLinkerTool', append=ldflags) self._GetDefFileAsLdflags(ldflags, gyp_to_build_path) ld('GenerateDebugInformation', map={'true': '/DEBUG'}) ld('TargetMachine', map={'1': 'X86', '17': 'X64', '3': 'ARM'}, prefix='/MACHINE:') ldflags.extend(self._GetAdditionalLibraryDirectories( 'VCLinkerTool', config, gyp_to_build_path)) ld('DelayLoadDLLs', prefix='/DELAYLOAD:') ld('TreatLinkerWarningAsErrors', prefix='/WX', map={'true': '', 'false': ':NO'}) out = self.GetOutputName(config, expand_special) if out: ldflags.append('/OUT:' + out) pdb = self.GetPDBName(config, expand_special, output_name + '.pdb') if pdb: ldflags.append('/PDB:' + pdb) pgd = self.GetPGDName(config, expand_special) if pgd: ldflags.append('/PGD:' + pgd) map_file = self.GetMapFileName(config, expand_special) ld('GenerateMapFile', map={'true': '/MAP:' + map_file if map_file else '/MAP'}) ld('MapExports', map={'true': '/MAPINFO:EXPORTS'}) ld('AdditionalOptions', prefix='') minimum_required_version = self._Setting( ('VCLinkerTool', 'MinimumRequiredVersion'), config, default='') if minimum_required_version: minimum_required_version = ',' + minimum_required_version ld('SubSystem', map={'1': 'CONSOLE%s' % minimum_required_version, '2': 'WINDOWS%s' % minimum_required_version}, prefix='/SUBSYSTEM:') stack_reserve_size = self._Setting( ('VCLinkerTool', 'StackReserveSize'), config, default='') if stack_reserve_size: stack_commit_size = self._Setting( ('VCLinkerTool', 'StackCommitSize'), config, default='') if stack_commit_size: stack_commit_size = ',' + stack_commit_size ldflags.append('/STACK:%s%s' % (stack_reserve_size, stack_commit_size)) ld('TerminalServerAware', map={'1': ':NO', '2': ''}, prefix='/TSAWARE') ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL') ld('BaseAddress', prefix='/BASE:') ld('FixedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/FIXED') ld('RandomizedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/DYNAMICBASE') ld('DataExecutionPrevention', map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT') ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:') ld('ForceSymbolReferences', prefix='/INCLUDE:') ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:') ld('LinkTimeCodeGeneration', map={'1': '', '2': ':PGINSTRUMENT', '3': ':PGOPTIMIZE', '4': ':PGUPDATE'}, prefix='/LTCG') ld('IgnoreDefaultLibraryNames', prefix='/NODEFAULTLIB:') ld('ResourceOnlyDLL', map={'true': '/NOENTRY'}) ld('EntryPointSymbol', prefix='/ENTRY:') ld('Profile', map={'true': '/PROFILE'}) ld('LargeAddressAware', map={'1': ':NO', '2': ''}, prefix='/LARGEADDRESSAWARE') # TODO(scottmg): This should sort of be somewhere else (not really a flag). ld('AdditionalDependencies', prefix='') if self.GetArch(config) == 'x86': safeseh_default = 'true' else: safeseh_default = None ld('ImageHasSafeExceptionHandlers', map={'false': ':NO', 'true': ''}, prefix='/SAFESEH', default=safeseh_default) # If the base address is not specifically controlled, DYNAMICBASE should # be on by default. base_flags = filter(lambda x: 'DYNAMICBASE' in x or x == '/FIXED', ldflags) if not base_flags: ldflags.append('/DYNAMICBASE') # If the NXCOMPAT flag has not been specified, default to on. Despite the # documentation that says this only defaults to on when the subsystem is # Vista or greater (which applies to the linker), the IDE defaults it on # unless it's explicitly off. if not filter(lambda x: 'NXCOMPAT' in x, ldflags): ldflags.append('/NXCOMPAT') have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags) manifest_flags, intermediate_manifest, manifest_files = \ self._GetLdManifestFlags(config, manifest_base_name, gyp_to_build_path, is_executable and not have_def_file, build_dir) ldflags.extend(manifest_flags) return ldflags, intermediate_manifest, manifest_files
[ "def", "GetLdflags", "(", "self", ",", "config", ",", "gyp_to_build_path", ",", "expand_special", ",", "manifest_base_name", ",", "output_name", ",", "is_executable", ",", "build_dir", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", ...
https://github.com/zhaoolee/StarsAndClown/blob/b2d4039cad2f9232b691e5976f787b49a0a2c113/node_modules/npmi/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L556-L657
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
area_t.__eq__
(self, *args)
return _idaapi.area_t___eq__(self, *args)
__eq__(self, r) -> bool
__eq__(self, r) -> bool
[ "__eq__", "(", "self", "r", ")", "-", ">", "bool" ]
def __eq__(self, *args): """ __eq__(self, r) -> bool """ return _idaapi.area_t___eq__(self, *args)
[ "def", "__eq__", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "area_t___eq__", "(", "self", ",", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L20744-L20748
lad1337/XDM
0c1b7009fe00f06f102a6f67c793478f515e7efe
site-packages/logilab/astng/as_string.py
python
AsStringVisitor.visit_yield
(self, node)
return 'yield' + yi_val
yield an ast.Yield node as string
yield an ast.Yield node as string
[ "yield", "an", "ast", ".", "Yield", "node", "as", "string" ]
def visit_yield(self, node): """yield an ast.Yield node as string""" yi_val = node.value and (" " + node.value.accept(self)) or "" return 'yield' + yi_val
[ "def", "visit_yield", "(", "self", ",", "node", ")", ":", "yi_val", "=", "node", ".", "value", "and", "(", "\" \"", "+", "node", ".", "value", ".", "accept", "(", "self", ")", ")", "or", "\"\"", "return", "'yield'", "+", "yi_val" ]
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/logilab/astng/as_string.py#L385-L388
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/fabmetheus_utilities/geometry/geometry_utilities/boolean_solid.py
python
getLoopsIntersectionByPair
(importRadius, loopsFirst, loopsLast)
return triangle_mesh.getDescendingAreaOrientedLoops(allPoints, corners, importRadius)
Get intersection loops for a pair of loop lists.
Get intersection loops for a pair of loop lists.
[ "Get", "intersection", "loops", "for", "a", "pair", "of", "loop", "lists", "." ]
def getLoopsIntersectionByPair(importRadius, loopsFirst, loopsLast): 'Get intersection loops for a pair of loop lists.' halfImportRadius = 0.5 * importRadius # so that there are no misses on shallow angles radiusSide = 0.01 * importRadius corners = [] corners += getInsetPointsByInsetLoops(loopsFirst, True, loopsLast, radiusSide) corners += getInsetPointsByInsetLoops(loopsLast, True, loopsFirst, radiusSide) allPoints = corners[:] allPoints += getInsetPointsByInsetLoops(getInBetweenLoopsFromLoops(loopsFirst, halfImportRadius), True, loopsLast, radiusSide) allPoints += getInsetPointsByInsetLoops(getInBetweenLoopsFromLoops(loopsLast, halfImportRadius), True, loopsFirst, radiusSide) return triangle_mesh.getDescendingAreaOrientedLoops(allPoints, corners, importRadius)
[ "def", "getLoopsIntersectionByPair", "(", "importRadius", ",", "loopsFirst", ",", "loopsLast", ")", ":", "halfImportRadius", "=", "0.5", "*", "importRadius", "# so that there are no misses on shallow angles", "radiusSide", "=", "0.01", "*", "importRadius", "corners", "=",...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/geometry/geometry_utilities/boolean_solid.py#L148-L158
viewfinderco/viewfinder
453845b5d64ab5b3b826c08b02546d1ca0a07c14
backend/db/health_report.py
python
HealthCriteria.GetCriteriaList
(cls)
return cls._criteria_list
Gets the list of criteria for server health checks. This is implemented as a class method to ensure that the static counters variable is completely loaded before accessing it, rather than depending on python module loading order.
Gets the list of criteria for server health checks. This is implemented as a class method to ensure that the static counters variable is completely loaded before accessing it, rather than depending on python module loading order.
[ "Gets", "the", "list", "of", "criteria", "for", "server", "health", "checks", ".", "This", "is", "implemented", "as", "a", "class", "method", "to", "ensure", "that", "the", "static", "counters", "variable", "is", "completely", "loaded", "before", "accessing", ...
def GetCriteriaList(cls): """Gets the list of criteria for server health checks. This is implemented as a class method to ensure that the static counters variable is completely loaded before accessing it, rather than depending on python module loading order. """ if hasattr(cls, '_criteria_list'): return cls._criteria_list cls._criteria_list = [ HealthCriteria('Errors', 'Error threshold exceeded.', ErrorCriteria, [counters.viewfinder.errors.error], 5), HealthCriteria('ReqFail', 'Failed Request threshold exceeded.', RequestsFailedCriteria, [counters.viewfinder.service.req_per_min, counters.viewfinder.service.fail_per_min], 5), HealthCriteria('OpRetries', 'Operation retry threshold exceeded.', OperationRetriesCriteria, [counters.viewfinder.operation.ops_per_min, counters.viewfinder.operation.retries_per_min], 5), HealthCriteria('MissingMetrics', 'Metrics collection failed.', MissingMetricsCriteria, [], 3), ] return cls._criteria_list
[ "def", "GetCriteriaList", "(", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'_criteria_list'", ")", ":", "return", "cls", ".", "_criteria_list", "cls", ".", "_criteria_list", "=", "[", "HealthCriteria", "(", "'Errors'", ",", "'Error threshold exceeded.'",...
https://github.com/viewfinderco/viewfinder/blob/453845b5d64ab5b3b826c08b02546d1ca0a07c14/backend/db/health_report.py#L161-L192
christiansandberg/canopen
a142fb583f236e0ea3c561af32f72ab1c423b95b
canopen/objectdictionary/__init__.py
python
Array.add_member
(self, variable: "Variable")
Adds a :class:`~canopen.objectdictionary.Variable` to the record.
Adds a :class:`~canopen.objectdictionary.Variable` to the record.
[ "Adds", "a", ":", "class", ":", "~canopen", ".", "objectdictionary", ".", "Variable", "to", "the", "record", "." ]
def add_member(self, variable: "Variable") -> None: """Adds a :class:`~canopen.objectdictionary.Variable` to the record.""" variable.parent = self self.subindices[variable.subindex] = variable self.names[variable.name] = variable
[ "def", "add_member", "(", "self", ",", "variable", ":", "\"Variable\"", ")", "->", "None", ":", "variable", ".", "parent", "=", "self", "self", ".", "subindices", "[", "variable", ".", "subindex", "]", "=", "variable", "self", ".", "names", "[", "variabl...
https://github.com/christiansandberg/canopen/blob/a142fb583f236e0ea3c561af32f72ab1c423b95b/canopen/objectdictionary/__init__.py#L262-L266
google/apitools
31cad2d904f356872d2965687e84b2d87ee2cdd3
apitools/base/py/gzip.py
python
GzipFile.__init__
(self, filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)
Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobj, which can be a regular file, an io.BytesIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file object. When fileobj is not None, the filename argument is only used to be included in the gzip file header, which may includes the original filename of the uncompressed file. It defaults to the filename of fileobj, if discernible; otherwise, it defaults to the empty string, and in this case the original filename is not included in the header. The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb', depending on whether the file will be read or written. The default is the mode of fileobj if discernible; otherwise, the default is 'rb'. A mode of 'r' is equivalent to one of 'rb', and similarly for 'w' and 'wb', and 'a' and 'ab'. The compresslevel argument is an integer from 0 to 9 controlling the level of compression; 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression. 0 is no compression at all. The default is 9. The mtime argument is an optional numeric timestamp to be written to the stream when compressing. All gzip compressed streams are required to contain a timestamp. If omitted or None, the current time is used. This module ignores the timestamp when decompressing; however, some programs, such as gunzip, make use of it. The format of the timestamp is the same as that of the return value of time.time() and of the st_mtime member of the object returned by os.stat().
Constructor for the GzipFile class.
[ "Constructor", "for", "the", "GzipFile", "class", "." ]
def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None): """Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobj, which can be a regular file, an io.BytesIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file object. When fileobj is not None, the filename argument is only used to be included in the gzip file header, which may includes the original filename of the uncompressed file. It defaults to the filename of fileobj, if discernible; otherwise, it defaults to the empty string, and in this case the original filename is not included in the header. The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb', depending on whether the file will be read or written. The default is the mode of fileobj if discernible; otherwise, the default is 'rb'. A mode of 'r' is equivalent to one of 'rb', and similarly for 'w' and 'wb', and 'a' and 'ab'. The compresslevel argument is an integer from 0 to 9 controlling the level of compression; 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression. 0 is no compression at all. The default is 9. The mtime argument is an optional numeric timestamp to be written to the stream when compressing. All gzip compressed streams are required to contain a timestamp. If omitted or None, the current time is used. This module ignores the timestamp when decompressing; however, some programs, such as gunzip, make use of it. The format of the timestamp is the same as that of the return value of time.time() and of the st_mtime member of the object returned by os.stat(). """ if mode and ('t' in mode or 'U' in mode): raise ValueError("Invalid mode: {!r}".format(mode)) if mode and 'b' not in mode: mode += 'b' if fileobj is None: fileobj = self.myfileobj = builtins.open(filename, mode or 'rb') if filename is None: filename = getattr(fileobj, 'name', '') if not isinstance(filename, six.string_types): filename = '' if mode is None: mode = getattr(fileobj, 'mode', 'rb') if mode.startswith('r'): self.mode = READ # Set flag indicating start of a new member self._new_member = True # Buffer data read from gzip file. extrastart is offset in # stream where buffer starts. extrasize is number of # bytes remaining in buffer from current stream position. self.extrabuf = b"" self.extrasize = 0 self.extrastart = 0 self.name = filename # Starts small, scales exponentially self.min_readsize = 100 fileobj = _PaddedFile(fileobj) elif mode.startswith(('w', 'a')): self.mode = WRITE self._init_write(filename) self.compress = zlib.compressobj(compresslevel, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0) else: raise ValueError("Invalid mode: {!r}".format(mode)) self.fileobj = fileobj self.offset = 0 self.mtime = mtime if self.mode == WRITE: self._write_gzip_header()
[ "def", "__init__", "(", "self", ",", "filename", "=", "None", ",", "mode", "=", "None", ",", "compresslevel", "=", "9", ",", "fileobj", "=", "None", ",", "mtime", "=", "None", ")", ":", "if", "mode", "and", "(", "'t'", "in", "mode", "or", "'U'", ...
https://github.com/google/apitools/blob/31cad2d904f356872d2965687e84b2d87ee2cdd3/apitools/base/py/gzip.py#L118-L202
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/utils/loaders.py
python
CodeEntityLoader._get_query_builder_label_identifier
(cls, identifier, classes, operator='==', project='*')
return builder
Return the query builder instance that attempts to map the identifier onto an entity of the orm class, defined for this loader class, interpreting the identifier as a LABEL like identifier :param identifier: the LABEL identifier :param classes: a tuple of orm classes to which the identifier should be mapped :param operator: the operator to use in the query :param project: the property or properties to project for entities matching the query :returns: the query builder instance that should retrieve the entity corresponding to the identifier :raises ValueError: if the identifier is invalid :raises aiida.common.NotExistent: if the orm base class does not support a LABEL like identifier
Return the query builder instance that attempts to map the identifier onto an entity of the orm class, defined for this loader class, interpreting the identifier as a LABEL like identifier
[ "Return", "the", "query", "builder", "instance", "that", "attempts", "to", "map", "the", "identifier", "onto", "an", "entity", "of", "the", "orm", "class", "defined", "for", "this", "loader", "class", "interpreting", "the", "identifier", "as", "a", "LABEL", ...
def _get_query_builder_label_identifier(cls, identifier, classes, operator='==', project='*'): """ Return the query builder instance that attempts to map the identifier onto an entity of the orm class, defined for this loader class, interpreting the identifier as a LABEL like identifier :param identifier: the LABEL identifier :param classes: a tuple of orm classes to which the identifier should be mapped :param operator: the operator to use in the query :param project: the property or properties to project for entities matching the query :returns: the query builder instance that should retrieve the entity corresponding to the identifier :raises ValueError: if the identifier is invalid :raises aiida.common.NotExistent: if the orm base class does not support a LABEL like identifier """ from aiida.common.escaping import escape_for_sql_like from aiida.orm import Computer try: identifier, _, machinename = identifier.partition('@') except AttributeError: raise ValueError('the identifier needs to be a string') if operator == 'like': identifier = f'{escape_for_sql_like(identifier)}%' builder = QueryBuilder() builder.append(cls=classes, tag='code', project=project, filters={'label': {operator: identifier}}) if machinename: builder.append(Computer, filters={'label': {'==': machinename}}, with_node='code') return builder
[ "def", "_get_query_builder_label_identifier", "(", "cls", ",", "identifier", ",", "classes", ",", "operator", "=", "'=='", ",", "project", "=", "'*'", ")", ":", "from", "aiida", ".", "common", ".", "escaping", "import", "escape_for_sql_like", "from", "aiida", ...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/utils/loaders.py#L640-L670
CyberDiscovery/cyberdisc-bot
e7d3a0789148aec1ef3e4153955a8c6f4d2cf219
cdbot/cogs/fun.py
python
Fun.angryj
(self, ctx: Context, *, text: str)
Creates an image of Angry Agent J with the specified text.
Creates an image of Angry Agent J with the specified text.
[ "Creates", "an", "image", "of", "Angry", "Agent", "J", "with", "the", "specified", "text", "." ]
async def angryj(self, ctx: Context, *, text: str): """ Creates an image of Angry Agent J with the specified text. """ await self.create_text_image(ctx, "AngryJ", text)
[ "async", "def", "angryj", "(", "self", ",", "ctx", ":", "Context", ",", "*", ",", "text", ":", "str", ")", ":", "await", "self", ".", "create_text_image", "(", "ctx", ",", "\"AngryJ\"", ",", "text", ")" ]
https://github.com/CyberDiscovery/cyberdisc-bot/blob/e7d3a0789148aec1ef3e4153955a8c6f4d2cf219/cdbot/cogs/fun.py#L570-L574
antonylesuisse/qweb
2d6964a3e5cae90414c4f873eb770591f569dfe0
ajaxterm/ajaxterm.py
python
Terminal.esc_0x08
(self,s)
[]
def esc_0x08(self,s): self.cx=max(0,self.cx-1)
[ "def", "esc_0x08", "(", "self", ",", "s", ")", ":", "self", ".", "cx", "=", "max", "(", "0", ",", "self", ".", "cx", "-", "1", ")" ]
https://github.com/antonylesuisse/qweb/blob/2d6964a3e5cae90414c4f873eb770591f569dfe0/ajaxterm/ajaxterm.py#L143-L144
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/contrib/gis/geos/geometry.py
python
GEOSGeometry.union
(self, other)
return self._topology(capi.geos_union(self.ptr, other.ptr))
Returns a Geometry representing all the points in this Geometry and other.
Returns a Geometry representing all the points in this Geometry and other.
[ "Returns", "a", "Geometry", "representing", "all", "the", "points", "in", "this", "Geometry", "and", "other", "." ]
def union(self, other): "Returns a Geometry representing all the points in this Geometry and other." return self._topology(capi.geos_union(self.ptr, other.ptr))
[ "def", "union", "(", "self", ",", "other", ")", ":", "return", "self", ".", "_topology", "(", "capi", ".", "geos_union", "(", "self", ".", "ptr", ",", "other", ".", "ptr", ")", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/contrib/gis/geos/geometry.py#L623-L625
tribe29/checkmk
6260f2512e159e311f426e16b84b19d0b8e9ad0c
cmk/base/agent_based/checking/_cluster_modes.py
python
_unfit_for_clustering
(**_kw)
A cluster_check_function that displays a generic warning
A cluster_check_function that displays a generic warning
[ "A", "cluster_check_function", "that", "displays", "a", "generic", "warning" ]
def _unfit_for_clustering(**_kw) -> CheckResult: """A cluster_check_function that displays a generic warning""" yield Result( state=State.UNKNOWN, summary=( "This service does not implement a native cluster mode. Please change your " "configuration using the rule 'Aggregation options for clustered services', " "and select one of the other available aggregation modes." ), )
[ "def", "_unfit_for_clustering", "(", "*", "*", "_kw", ")", "->", "CheckResult", ":", "yield", "Result", "(", "state", "=", "State", ".", "UNKNOWN", ",", "summary", "=", "(", "\"This service does not implement a native cluster mode. Please change your \"", "\"configurati...
https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/base/agent_based/checking/_cluster_modes.py#L52-L61
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/dts/transfer_device_client.py
python
TransferDeviceClient.create_transfer_device
(self, id, create_transfer_device_details, **kwargs)
Create a new Transfer Device :param str id: (required) ID of the Transfer Job :param oci.dts.models.CreateTransferDeviceDetails create_transfer_device_details: (required) Creates a New Transfer Device :param str opc_retry_token: (optional) :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.dts.models.NewTransferDevice` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/dts/create_transfer_device.py.html>`__ to see an example of how to use create_transfer_device API.
Create a new Transfer Device
[ "Create", "a", "new", "Transfer", "Device" ]
def create_transfer_device(self, id, create_transfer_device_details, **kwargs): """ Create a new Transfer Device :param str id: (required) ID of the Transfer Job :param oci.dts.models.CreateTransferDeviceDetails create_transfer_device_details: (required) Creates a New Transfer Device :param str opc_retry_token: (optional) :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.dts.models.NewTransferDevice` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/dts/create_transfer_device.py.html>`__ to see an example of how to use create_transfer_device API. """ resource_path = "/transferJobs/{id}/transferDevices" method = "POST" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_retry_token" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "create_transfer_device got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "id": id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "opc-retry-token": kwargs.get("opc_retry_token", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_retry_token_if_needed(header_params) self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=create_transfer_device_details, response_type="NewTransferDevice") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=create_transfer_device_details, response_type="NewTransferDevice")
[ "def", "create_transfer_device", "(", "self", ",", "id", ",", "create_transfer_device_details", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/transferJobs/{id}/transferDevices\"", "method", "=", "\"POST\"", "# Don't accept unknown kwargs", "expected_kwargs", ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/dts/transfer_device_client.py#L101-L183
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/difflib.py
python
SequenceMatcher.get_grouped_opcodes
(self, n=3)
Isolate change clusters by eliminating ranges with no changes. Return a generator of groups with up to n lines of context. Each group is in the same format as returned by get_opcodes(). >>> from pprint import pprint >>> a = list(map(str, range(1,40))) >>> b = a[:] >>> b[8:8] = ['i'] # Make an insertion >>> b[20] += 'x' # Make a replacement >>> b[23:28] = [] # Make a deletion >>> b[30] += 'y' # Make another replacement >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes())) [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)], [('equal', 16, 19, 17, 20), ('replace', 19, 20, 20, 21), ('equal', 20, 22, 21, 23), ('delete', 22, 27, 23, 23), ('equal', 27, 30, 23, 26)], [('equal', 31, 34, 27, 30), ('replace', 34, 35, 30, 31), ('equal', 35, 38, 31, 34)]]
Isolate change clusters by eliminating ranges with no changes.
[ "Isolate", "change", "clusters", "by", "eliminating", "ranges", "with", "no", "changes", "." ]
def get_grouped_opcodes(self, n=3): """ Isolate change clusters by eliminating ranges with no changes. Return a generator of groups with up to n lines of context. Each group is in the same format as returned by get_opcodes(). >>> from pprint import pprint >>> a = list(map(str, range(1,40))) >>> b = a[:] >>> b[8:8] = ['i'] # Make an insertion >>> b[20] += 'x' # Make a replacement >>> b[23:28] = [] # Make a deletion >>> b[30] += 'y' # Make another replacement >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes())) [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)], [('equal', 16, 19, 17, 20), ('replace', 19, 20, 20, 21), ('equal', 20, 22, 21, 23), ('delete', 22, 27, 23, 23), ('equal', 27, 30, 23, 26)], [('equal', 31, 34, 27, 30), ('replace', 34, 35, 30, 31), ('equal', 35, 38, 31, 34)]] """ codes = self.get_opcodes() if not codes: codes = [("equal", 0, 1, 0, 1)] # Fixup leading and trailing groups if they show no changes. if codes[0][0] == 'equal': tag, i1, i2, j1, j2 = codes[0] codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2 if codes[-1][0] == 'equal': tag, i1, i2, j1, j2 = codes[-1] codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n) nn = n + n group = [] for tag, i1, i2, j1, j2 in codes: # End the current group and start a new one whenever # there is a large range with no changes. if tag == 'equal' and i2-i1 > nn: group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n))) yield group group = [] i1, j1 = max(i1, i2-n), max(j1, j2-n) group.append((tag, i1, i2, j1 ,j2)) if group and not (len(group)==1 and group[0][0] == 'equal'): yield group
[ "def", "get_grouped_opcodes", "(", "self", ",", "n", "=", "3", ")", ":", "codes", "=", "self", ".", "get_opcodes", "(", ")", "if", "not", "codes", ":", "codes", "=", "[", "(", "\"equal\"", ",", "0", ",", "1", ",", "0", ",", "1", ")", "]", "# Fi...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/difflib.py#L547-L595
hhyo/Archery
c9b057d37e47894ca8531e5cd10afdb064cd0122
sql/engines/__init__.py
python
EngineBase.get_execute_percentage
(self)
获取执行进度
获取执行进度
[ "获取执行进度" ]
def get_execute_percentage(self): """获取执行进度"""
[ "def", "get_execute_percentage", "(", "self", ")", ":" ]
https://github.com/hhyo/Archery/blob/c9b057d37e47894ca8531e5cd10afdb064cd0122/sql/engines/__init__.py#L132-L133
Qirky/FoxDot
76318f9630bede48ff3994146ed644affa27bfa4
FoxDot/lib/Workspace/Simple/SimpleEditor.py
python
Editor.alt_return
(self, event)
return
Evaluates current line of code
Evaluates current line of code
[ "Evaluates", "current", "line", "of", "code" ]
def alt_return(self, event): """ Evaluates current line of code """ row = self.text.get_current_row() code = self.text.get_block_text(row, row) if code: execute(code) self.flash(row, row) return
[ "def", "alt_return", "(", "self", ",", "event", ")", ":", "row", "=", "self", ".", "text", ".", "get_current_row", "(", ")", "code", "=", "self", ".", "text", ".", "get_block_text", "(", "row", ",", "row", ")", "if", "code", ":", "execute", "(", "c...
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/Workspace/Simple/SimpleEditor.py#L153-L160
open-mmlab/mmdetection
ff9bc39913cb3ff5dde79d3933add7dc2561bab7
mmdet/core/export/onnx_helper.py
python
get_k_for_topk
(k, size)
return ret_k
Get k of TopK for onnx exporting. The K of TopK in TensorRT should not be a Tensor, while in ONNX Runtime it could be a Tensor.Due to dynamic shape feature, we have to decide whether to do TopK and what K it should be while exporting to ONNX. If returned K is less than zero, it means we do not have to do TopK operation. Args: k (int or Tensor): The set k value for nms from config file. size (Tensor or torch.Size): The number of elements of \ TopK's input tensor Returns: tuple: (int or Tensor): The final K for TopK.
Get k of TopK for onnx exporting.
[ "Get", "k", "of", "TopK", "for", "onnx", "exporting", "." ]
def get_k_for_topk(k, size): """Get k of TopK for onnx exporting. The K of TopK in TensorRT should not be a Tensor, while in ONNX Runtime it could be a Tensor.Due to dynamic shape feature, we have to decide whether to do TopK and what K it should be while exporting to ONNX. If returned K is less than zero, it means we do not have to do TopK operation. Args: k (int or Tensor): The set k value for nms from config file. size (Tensor or torch.Size): The number of elements of \ TopK's input tensor Returns: tuple: (int or Tensor): The final K for TopK. """ ret_k = -1 if k <= 0 or size <= 0: return ret_k if torch.onnx.is_in_onnx_export(): is_trt_backend = os.environ.get('ONNX_BACKEND') == 'MMCVTensorRT' if is_trt_backend: # TensorRT does not support dynamic K with TopK op if 0 < k < size: ret_k = k else: # Always keep topk op for dynamic input in onnx for ONNX Runtime ret_k = torch.where(k < size, k, size) elif k < size: ret_k = k else: # ret_k is -1 pass return ret_k
[ "def", "get_k_for_topk", "(", "k", ",", "size", ")", ":", "ret_k", "=", "-", "1", "if", "k", "<=", "0", "or", "size", "<=", "0", ":", "return", "ret_k", "if", "torch", ".", "onnx", ".", "is_in_onnx_export", "(", ")", ":", "is_trt_backend", "=", "os...
https://github.com/open-mmlab/mmdetection/blob/ff9bc39913cb3ff5dde79d3933add7dc2561bab7/mmdet/core/export/onnx_helper.py#L46-L79
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/suds/mx/appender.py
python
ContentAppender.append
(self, parent, content)
Select an appender and append the content to parent. @param parent: A parent node. @type parent: L{Element} @param content: The content to append. @type content: L{Content}
Select an appender and append the content to parent.
[ "Select", "an", "appender", "and", "append", "the", "content", "to", "parent", "." ]
def append(self, parent, content): """ Select an appender and append the content to parent. @param parent: A parent node. @type parent: L{Element} @param content: The content to append. @type content: L{Content} """ appender = self.default for a in self.appenders: if a[0] == content.value: appender = a[1] break appender.append(parent, content)
[ "def", "append", "(", "self", ",", "parent", ",", "content", ")", ":", "appender", "=", "self", ".", "default", "for", "a", "in", "self", ".", "appenders", ":", "if", "a", "[", "0", "]", "==", "content", ".", "value", ":", "appender", "=", "a", "...
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/suds/mx/appender.py#L89-L102
tenable/poc
361b6b191eda0bdc4f7338a58c2e2fe79bb8afca
Ubiquiti/UniFi_Protect/cve_2020_8213_unifi_protect_username_discovery.py
python
test_username
(username, password, conn, headers, valid_usernames, valid_passwords)
return None
Test passed username and password and store valid usernames and valid username / password combinations in the passed lists.
Test passed username and password and store valid usernames and valid username / password combinations in the passed lists.
[ "Test", "passed", "username", "and", "password", "and", "store", "valid", "usernames", "and", "valid", "username", "/", "password", "combinations", "in", "the", "passed", "lists", "." ]
def test_username(username, password, conn, headers, valid_usernames, valid_passwords): """ Test passed username and password and store valid usernames and valid username / password combinations in the passed lists. """ debug("Trying username: {}".format(username)) data = {} data["username"] = username data["password"] = password body = json.dumps(data) try: conn.request("POST", "/api/auth", body=body, headers=headers) except OSError: exit("OSError sending to target port. Use --no-ssl or -n if target port is not an SSL port.") start = time.time() res = None while time.time() - start < TIMEOUT: try: res = conn.getresponse() except http.client.ResponseNotReady: continue except http.client.RemoteDisconnected: exit("Remote disconnected when getting response from target port. Do not use --no-ssl or -n if target port is an SSL port.") res.read() break if not res: debug("Response to authentication request for username '{}' timed out after {} seconds".format(username, TIMEOUT)) return None if res.status == 400: return False if res.status == 401: print("[!] Found potentially valid username: {}".format(username)) valid_usernames.append(username) return True if res.status == 200: print("[!] Found valid username / password: {} / {}".format(username, password)) valid_usernames.append(username) valid_passwords.append({"username":username, "password":password}) return True debug("Unexpected response: {} {}".format(res.status, res.reason)) return None
[ "def", "test_username", "(", "username", ",", "password", ",", "conn", ",", "headers", ",", "valid_usernames", ",", "valid_passwords", ")", ":", "debug", "(", "\"Trying username: {}\"", ".", "format", "(", "username", ")", ")", "data", "=", "{", "}", "data",...
https://github.com/tenable/poc/blob/361b6b191eda0bdc4f7338a58c2e2fe79bb8afca/Ubiquiti/UniFi_Protect/cve_2020_8213_unifi_protect_username_discovery.py#L107-L150
shuup/shuup
25f78cfe370109b9885b903e503faac295c7b7f2
shuup/admin/modules/orders/views/shipment.py
python
OrderCreateShipmentView.create_shipment
(self, order, product_quantities, shipment)
return order.create_shipment(product_quantities=product_quantities, shipment=shipment)
This function exists so subclasses can implement custom logic without overriding the entire form_valid method. :param order: Order to create the shipment for. :type order: shuup.core.models.Order :param product_quantities: a dict mapping Product instances to quantities to ship. :type product_quantities: dict[shuup.shop.models.Product, decimal.Decimal] :param shipment: unsaved Shipment for ShipmentProduct's. :type shipment: shuup.core.models.Shipment :return: Saved, complete Shipment object. :rtype: shuup.core.models.Shipment
This function exists so subclasses can implement custom logic without overriding the entire form_valid method.
[ "This", "function", "exists", "so", "subclasses", "can", "implement", "custom", "logic", "without", "overriding", "the", "entire", "form_valid", "method", "." ]
def create_shipment(self, order, product_quantities, shipment): """ This function exists so subclasses can implement custom logic without overriding the entire form_valid method. :param order: Order to create the shipment for. :type order: shuup.core.models.Order :param product_quantities: a dict mapping Product instances to quantities to ship. :type product_quantities: dict[shuup.shop.models.Product, decimal.Decimal] :param shipment: unsaved Shipment for ShipmentProduct's. :type shipment: shuup.core.models.Shipment :return: Saved, complete Shipment object. :rtype: shuup.core.models.Shipment """ return order.create_shipment(product_quantities=product_quantities, shipment=shipment)
[ "def", "create_shipment", "(", "self", ",", "order", ",", "product_quantities", ",", "shipment", ")", ":", "return", "order", ".", "create_shipment", "(", "product_quantities", "=", "product_quantities", ",", "shipment", "=", "shipment", ")" ]
https://github.com/shuup/shuup/blob/25f78cfe370109b9885b903e503faac295c7b7f2/shuup/admin/modules/orders/views/shipment.py#L116-L130
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas/datastructures/mesh/operations/weld.py
python
mesh_unweld_edges
(mesh, edges)
Unwelds a mesh along edges. Parameters ---------- mesh : Mesh A mesh. edges: list List of edges as tuples of vertex keys.
Unwelds a mesh along edges.
[ "Unwelds", "a", "mesh", "along", "edges", "." ]
def mesh_unweld_edges(mesh, edges): """Unwelds a mesh along edges. Parameters ---------- mesh : Mesh A mesh. edges: list List of edges as tuples of vertex keys. """ # set of vertices in edges to unweld vertices = set([i for edge in edges for i in edge]) # to store changes to do all at once vertex_changes = {} for vkey in vertices: # maps between old mesh face index and new network vertex index old_to_new = {nbr: i for i, nbr in enumerate(mesh.vertex_faces(vkey))} new_to_old = {i: nbr for i, nbr in enumerate(mesh.vertex_faces(vkey))} # get adjacency network of faces around the vertex excluding adjacency # through the edges to unweld network_edges = [] for nbr in mesh.vertex_neighbors(vkey): if not mesh.is_edge_on_boundary(vkey, nbr) and (vkey, nbr) not in edges and (nbr, vkey) not in edges: network_edges.append((old_to_new[mesh.halfedge[vkey][nbr]], old_to_new[mesh.halfedge[nbr][vkey]])) adjacency = adjacency_from_edges(network_edges) for key, values in adjacency.items(): adjacency[key] = {value: None for value in values} # include non connected vertices edge_vertices = list(set([i for edge in network_edges for i in edge])) for i in range(len(mesh.vertex_faces(vkey))): if i not in edge_vertices: adjacency[i] = {} # collect the disconnected parts around the vertex due to unwelding vertex_changes[vkey] = [[new_to_old[key] for key in part] for part in connected_components(adjacency)] for vkey, changes in vertex_changes.items(): # for each disconnected part replace the vertex by a new vertex in the # faces of the part for change in changes: mesh_substitute_vertex_in_faces(mesh, vkey, mesh.add_vertex(attr_dict=mesh.vertex[vkey]), change) # delete old vertices mesh.delete_vertex(vkey)
[ "def", "mesh_unweld_edges", "(", "mesh", ",", "edges", ")", ":", "# set of vertices in edges to unweld", "vertices", "=", "set", "(", "[", "i", "for", "edge", "in", "edges", "for", "i", "in", "edge", "]", ")", "# to store changes to do all at once", "vertex_change...
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas/datastructures/mesh/operations/weld.py#L56-L106
tensorly/tensorly
87b435b3f3343447b49d47ebb5461118f6c8a9ab
tensorly/tenalg/einsum_tenalg/generalised_inner_product.py
python
inner
(tensor1, tensor2, n_modes=None)
return T.einsum(equation, tensor1, tensor2)
Generalised inner products between tensors Takes the inner product between the last (respectively first) `n_modes` of `tensor1` (respectively `tensor2`) Parameters ---------- tensor1, tensor2 : tensor n_modes : int, default is None * if None, the traditional inner product is returned (i.e. a float) * otherwise, the product between the `n_modes` last modes of `tensor1` and the `n_modes` first modes of `tensor2` is returned. The resulting tensor's order is `ndim(tensor1) - n_modes`. Returns ------- inner_product : float if n_modes is None, tensor otherwise
Generalised inner products between tensors
[ "Generalised", "inner", "products", "between", "tensors" ]
def inner(tensor1, tensor2, n_modes=None): """Generalised inner products between tensors Takes the inner product between the last (respectively first) `n_modes` of `tensor1` (respectively `tensor2`) Parameters ---------- tensor1, tensor2 : tensor n_modes : int, default is None * if None, the traditional inner product is returned (i.e. a float) * otherwise, the product between the `n_modes` last modes of `tensor1` and the `n_modes` first modes of `tensor2` is returned. The resulting tensor's order is `ndim(tensor1) - n_modes`. Returns ------- inner_product : float if n_modes is None, tensor otherwise """ # Traditional inner product if n_modes is None: if tensor1.shape != tensor2.shape: raise ValueError('Taking a generalised product between two tensors without specifying common modes' ' is equivalent to taking inner product.' 'This requires tensor1.shape == tensor2.shape.' 'However, got tensor1.shape={} and tensor2.shape={}'.format(tensor1.shape, tensor2.shape)) return T.sum(tensor1*tensor2) shape_t1 = list(T.shape(tensor1)) shape_t2 = list(T.shape(tensor2)) offset = len(shape_t1) - n_modes if shape_t1[offset:] != shape_t2[:n_modes]: raise ValueError('Incorrect shapes for inner product along {} common modes.' 'tensor_1.shape={}, tensor_2.shape={}'.format(n_modes, shape_t1, shape_t2)) # Inner product along `n_modes` common modes start = ord('a') modes_t1 = ''.join(chr(i+start) for i in range(T.ndim(tensor1))) modes_t2 = ''.join(chr(i + start + offset) for i in range(T.ndim(tensor2))) output_modes = modes_t1[:offset] + modes_t2[n_modes:] equation = f'{modes_t1},{modes_t2}->{output_modes}' return T.einsum(equation, tensor1, tensor2)
[ "def", "inner", "(", "tensor1", ",", "tensor2", ",", "n_modes", "=", "None", ")", ":", "# Traditional inner product", "if", "n_modes", "is", "None", ":", "if", "tensor1", ".", "shape", "!=", "tensor2", ".", "shape", ":", "raise", "ValueError", "(", "'Takin...
https://github.com/tensorly/tensorly/blob/87b435b3f3343447b49d47ebb5461118f6c8a9ab/tensorly/tenalg/einsum_tenalg/generalised_inner_product.py#L8-L53
ebroecker/canmatrix
219a19adf4639b0b4fd5328f039563c6d4060887
src/canmatrix/formats/arxml.py
python
decode_can_helper
(ea, float_factory, ignore_cluster_info)
return found_matrixes
[]
def decode_can_helper(ea, float_factory, ignore_cluster_info): found_matrixes = {} if ignore_cluster_info is True: ccs = [lxml.etree.Element("ignoreClusterInfo")] # type: typing.Sequence[_Element] else: ccs = ea.findall('CAN-CLUSTER') headers_are_littleendian = containters_are_little_endian(ea) nodes = {} # type: typing.Dict[_Element, canmatrix.Ecu] for cc in ccs: # type: _Element db = canmatrix.CanMatrix() # Defines not jet imported... db.add_ecu_defines("NWM-Stationsadresse", 'HEX 0 63') db.add_ecu_defines("NWM-Knoten", 'ENUM "nein","ja"') db.add_signal_defines("LongName", 'STRING') db.add_frame_defines("GenMsgDelayTime", 'INT 0 65535') db.add_frame_defines("GenMsgNrOfRepetitions", 'INT 0 65535') db.add_frame_defines("GenMsgStartValue", 'STRING') db.add_frame_defines("GenMsgStartDelayTime", 'INT 0 65535') db.add_frame_defines( "GenMsgSendType", 'ENUM "cyclicX","spontanX","cyclicIfActiveX","spontanWithDelay","cyclicAndSpontanX","cyclicAndSpontanWithDelay","spontanWithRepitition","cyclicIfActiveAndSpontanWD","cyclicIfActiveFast","cyclicWithRepeatOnDemand","none"') if ignore_cluster_info is True: can_frame_trig = ea.findall('CAN-FRAME-TRIGGERING') bus_name = "" else: speed = ea.get_child(cc, "SPEED") baudrate_elem = ea.find("BAUDRATE", cc) fd_baudrate_elem = ea.find("CAN-FD-BAUDRATE", cc) logger.debug("Busname: " + ea.get_element_name(cc)) bus_name = ea.get_element_name(cc) if speed is not None: db.baudrate = int(speed.text) elif baudrate_elem is not None: db.baudrate = int(baudrate_elem.text) logger.debug("Baudrate: " + str(db.baudrate)) if fd_baudrate_elem is not None: db.fd_baudrate = int(fd_baudrate_elem.text) can_frame_trig = ea.selector(cc, "/CAN-PHYSICAL-CHANNEL//CAN-FRAME-TRIGGERING") multiplex_translation = {} # type: typing.Dict[str, str] for frameTrig in can_frame_trig: # type: _Element frame = get_frame(frameTrig, ea, multiplex_translation, float_factory, headers_are_littleendian) if frame is not None: comm_direction = ea.selector(frameTrig, ">>FRAME-PORT-REF/COMMUNICATION-DIRECTION") if len(comm_direction) > 0: ecu_elem = ea.get_ecu_instance(element=comm_direction[0]) if ecu_elem is not None: if ecu_elem in nodes: ecu = nodes[ecu_elem] else: ecu = process_ecu(ecu_elem, ea) nodes[ecu_elem] = ecu if comm_direction[0].text == "OUT": frame.add_transmitter(ecu.name) else: frame.add_receiver(ecu.name) db.add_ecu(ecu) db.add_frame(frame) for frame in db.frames: if frame.is_pdu_container: continue sig_value_hash = dict() for sig in frame.signals: sig.receivers = list(set(frame.receivers).intersection(sig.receivers)) try: sig_value_hash[sig.name] = sig.phys2raw() except AttributeError: sig_value_hash[sig.name] = 0 frame_data = frame.encode(sig_value_hash) frame.add_attribute("GenMsgStartValue", "".join(["%02x" % x for x in frame_data])) # frame.update_receiver() found_matrixes[bus_name] = db return found_matrixes
[ "def", "decode_can_helper", "(", "ea", ",", "float_factory", ",", "ignore_cluster_info", ")", ":", "found_matrixes", "=", "{", "}", "if", "ignore_cluster_info", "is", "True", ":", "ccs", "=", "[", "lxml", ".", "etree", ".", "Element", "(", "\"ignoreClusterInfo...
https://github.com/ebroecker/canmatrix/blob/219a19adf4639b0b4fd5328f039563c6d4060887/src/canmatrix/formats/arxml.py#L1795-L1875
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
is_debugger_memory
(*args)
return _idaapi.is_debugger_memory(*args)
is_debugger_memory(ea) -> bool
is_debugger_memory(ea) -> bool
[ "is_debugger_memory", "(", "ea", ")", "-", ">", "bool" ]
def is_debugger_memory(*args): """ is_debugger_memory(ea) -> bool """ return _idaapi.is_debugger_memory(*args)
[ "def", "is_debugger_memory", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "is_debugger_memory", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L24236-L24240
evait-security/weeman
4aff9c0332a8cfba4124f033cff0a85d0dcb849d
lib/bs4/element.py
python
PageElement._is_xml
(self)
return self.parent._is_xml
Is this element part of an XML tree or an HTML tree? This is used when mapping a formatter name ("minimal") to an appropriate function (one that performs entity-substitution on the contents of <script> and <style> tags, or not). It can be inefficient, but it should be called very rarely.
Is this element part of an XML tree or an HTML tree?
[ "Is", "this", "element", "part", "of", "an", "XML", "tree", "or", "an", "HTML", "tree?" ]
def _is_xml(self): """Is this element part of an XML tree or an HTML tree? This is used when mapping a formatter name ("minimal") to an appropriate function (one that performs entity-substitution on the contents of <script> and <style> tags, or not). It can be inefficient, but it should be called very rarely. """ if self.known_xml is not None: # Most of the time we will have determined this when the # document is parsed. return self.known_xml # Otherwise, it's likely that this element was created by # direct invocation of the constructor from within the user's # Python code. if self.parent is None: # This is the top-level object. It should have .known_xml set # from tree creation. If not, take a guess--BS is usually # used on HTML markup. return getattr(self, 'is_xml', False) return self.parent._is_xml
[ "def", "_is_xml", "(", "self", ")", ":", "if", "self", ".", "known_xml", "is", "not", "None", ":", "# Most of the time we will have determined this when the", "# document is parsed.", "return", "self", ".", "known_xml", "# Otherwise, it's likely that this element was created ...
https://github.com/evait-security/weeman/blob/4aff9c0332a8cfba4124f033cff0a85d0dcb849d/lib/bs4/element.py#L171-L192
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/physics/robot_physics_randomizer.py
python
RobotPhysicsRandomizer.__init__
(self, body, links=None, joints=None, **kwargs)
Initialize the robot physics randomizer. Args: body (Body): multi-body object. links (int, list of int, LinkPhysicsRandomizer, list of LinkPhysicsRandomizer, None): link id(s) or link physics randomizer(s). joints (int, list of int, JointPhysicsRandomizer, list JointPhysicsRandomizer, None): joint id(s) or joint physics randomizer. **kwargs (dict): range of possible physical properties. If given one value, that property won't be randomized. Each range is a tuple of two values `[lower_bound, upper_bound]`.
Initialize the robot physics randomizer.
[ "Initialize", "the", "robot", "physics", "randomizer", "." ]
def __init__(self, body, links=None, joints=None, **kwargs): """ Initialize the robot physics randomizer. Args: body (Body): multi-body object. links (int, list of int, LinkPhysicsRandomizer, list of LinkPhysicsRandomizer, None): link id(s) or link physics randomizer(s). joints (int, list of int, JointPhysicsRandomizer, list JointPhysicsRandomizer, None): joint id(s) or joint physics randomizer. **kwargs (dict): range of possible physical properties. If given one value, that property won't be randomized. Each range is a tuple of two values `[lower_bound, upper_bound]`. """ super(RobotPhysicsRandomizer, self).__init__(body) self.links = links self.joints = joints
[ "def", "__init__", "(", "self", ",", "body", ",", "links", "=", "None", ",", "joints", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "RobotPhysicsRandomizer", ",", "self", ")", ".", "__init__", "(", "body", ")", "self", ".", "links", ...
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/physics/robot_physics_randomizer.py#L33-L48
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/flaskbb/utils/helpers.py
python
ReverseProxyPathFix.__call__
(self, environ, start_response)
return self.app(environ, start_response)
[]
def __call__(self, environ, start_response): script_name = environ.get('HTTP_X_SCRIPT_NAME', '') if script_name: environ['SCRIPT_NAME'] = script_name path_info = environ.get('PATH_INFO', '') if path_info and path_info.startswith(script_name): environ['PATH_INFO'] = path_info[len(script_name):] server = environ.get('HTTP_X_FORWARDED_SERVER_CUSTOM', environ.get('HTTP_X_FORWARDED_SERVER', '')) if server: environ['HTTP_HOST'] = server scheme = environ.get('HTTP_X_SCHEME', '') if scheme: environ['wsgi.url_scheme'] = scheme if self.force_https: environ['wsgi.url_scheme'] = 'https' return self.app(environ, start_response)
[ "def", "__call__", "(", "self", ",", "environ", ",", "start_response", ")", ":", "script_name", "=", "environ", ".", "get", "(", "'HTTP_X_SCRIPT_NAME'", ",", "''", ")", "if", "script_name", ":", "environ", "[", "'SCRIPT_NAME'", "]", "=", "script_name", "path...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/flaskbb/utils/helpers.py#L668-L688
pyvista/pyvista
012dbb95a9aae406c3cd4cd94fc8c477f871e426
pyvista/core/errors.py
python
DeprecationError.__init__
(self, message='This feature has been depreciated')
Empty init.
Empty init.
[ "Empty", "init", "." ]
def __init__(self, message='This feature has been depreciated'): """Empty init.""" RuntimeError.__init__(self, message)
[ "def", "__init__", "(", "self", ",", "message", "=", "'This feature has been depreciated'", ")", ":", "RuntimeError", ".", "__init__", "(", "self", ",", "message", ")" ]
https://github.com/pyvista/pyvista/blob/012dbb95a9aae406c3cd4cd94fc8c477f871e426/pyvista/core/errors.py#L36-L38
ShannonAI/glyce
2ecefe68dcbe45d19c3fd043e02d04d337afdc15
glyce/utils/file_utils.py
python
s3_etag
(url: str)
return s3_object.e_tag
Check ETag on S3 object.
Check ETag on S3 object.
[ "Check", "ETag", "on", "S3", "object", "." ]
def s3_etag(url: str) -> Optional[str]: """Check ETag on S3 object.""" s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag
[ "def", "s3_etag", "(", "url", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "s3_resource", "=", "boto3", ".", "resource", "(", "\"s3\"", ")", "bucket_name", ",", "s3_path", "=", "split_s3_path", "(", "url", ")", "s3_object", "=", "s3_resource"...
https://github.com/ShannonAI/glyce/blob/2ecefe68dcbe45d19c3fd043e02d04d337afdc15/glyce/utils/file_utils.py#L154-L159
travisgoodspeed/goodfet
1750cc1e8588af5470385e52fa098ca7364c2863
client/GoodFETSPI.py
python
GoodFETSPIFlash.SPIjedecmanstr
(self)
return man
Grab the JEDEC manufacturer string. Call after SPIjedec().
Grab the JEDEC manufacturer string. Call after SPIjedec().
[ "Grab", "the", "JEDEC", "manufacturer", "string", ".", "Call", "after", "SPIjedec", "()", "." ]
def SPIjedecmanstr(self): """Grab the JEDEC manufacturer string. Call after SPIjedec().""" man=self.JEDECmanufacturers.get(self.JEDECmanufacturer) if man==0: man="UNKNOWN"; return man;
[ "def", "SPIjedecmanstr", "(", "self", ")", ":", "man", "=", "self", ".", "JEDECmanufacturers", ".", "get", "(", "self", ".", "JEDECmanufacturer", ")", "if", "man", "==", "0", ":", "man", "=", "\"UNKNOWN\"", "return", "man" ]
https://github.com/travisgoodspeed/goodfet/blob/1750cc1e8588af5470385e52fa098ca7364c2863/client/GoodFETSPI.py#L343-L348
daoluan/decode-Django
d46a858b45b56de48b0355f50dd9e45402d04cfd
Django-1.5.1/django/db/backends/__init__.py
python
set_dirty
(self)
Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit.
Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit.
[ "Sets", "a", "dirty", "flag", "for", "the", "current", "thread", "and", "code", "streak", ".", "This", "can", "be", "used", "to", "decide", "in", "a", "managed", "block", "of", "code", "to", "decide", "whether", "there", "are", "open", "changes", "waitin...
def set_dirty(self): """ Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit. """ if self._dirty is not None: self._dirty = True else: raise TransactionManagementError("This code isn't under transaction " "management")
[ "def", "set_dirty", "(", "self", ")", ":", "if", "self", ".", "_dirty", "is", "not", "None", ":", "self", ".", "_dirty", "=", "True", "else", ":", "raise", "TransactionManagementError", "(", "\"This code isn't under transaction \"", "\"management\"", ")" ]
https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/db/backends/__init__.py#L186-L196
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/lib/codeintel2/rubycile.py
python
scan_multilang
(tokens, module_elem)
return csl_tokens, css_tokens, tokenizer.has_ruby_code()
Build the Ruby module CIX element tree. "tokens" is a generator of UDL tokens for this UDL-based multi-lang document. "module_elem" is the <module> element of a CIX element tree on which the Ruby module should be built. This should return a tuple of: * the list of the CSL and CSS tokens in the token stream, * whether or not the document contains any Ruby tokens (style UDL_SSL...)
Build the Ruby module CIX element tree.
[ "Build", "the", "Ruby", "module", "CIX", "element", "tree", "." ]
def scan_multilang(tokens, module_elem): """Build the Ruby module CIX element tree. "tokens" is a generator of UDL tokens for this UDL-based multi-lang document. "module_elem" is the <module> element of a CIX element tree on which the Ruby module should be built. This should return a tuple of: * the list of the CSL and CSS tokens in the token stream, * whether or not the document contains any Ruby tokens (style UDL_SSL...) """ tokenizer = ruby_lexer.RubyMultiLangLexer(tokens) parser = ruby_parser.Parser(tokenizer, "RHTML") parse_tree = parser.parse() parser_cix.produce_elementTree_contents_cix(parse_tree, module_elem) csl_tokens = tokenizer.get_csl_tokens() css_tokens = tokenizer.get_css_tokens() return csl_tokens, css_tokens, tokenizer.has_ruby_code()
[ "def", "scan_multilang", "(", "tokens", ",", "module_elem", ")", ":", "tokenizer", "=", "ruby_lexer", ".", "RubyMultiLangLexer", "(", "tokens", ")", "parser", "=", "ruby_parser", ".", "Parser", "(", "tokenizer", ",", "\"RHTML\"", ")", "parse_tree", "=", "parse...
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/lib/codeintel2/rubycile.py#L283-L302
postgres/pgadmin4
374c5e952fa594d749fadf1f88076c1cba8c5f64
web/pgadmin/browser/server_groups/servers/tablespaces/__init__.py
python
TablespaceView.variable_options
(self, gid, sid)
return make_json_response( data=rset['rows'], status=200 )
Args: gid: sid: Returns: This function will return list of variables available for table spaces.
Args: gid: sid:
[ "Args", ":", "gid", ":", "sid", ":" ]
def variable_options(self, gid, sid): """ Args: gid: sid: Returns: This function will return list of variables available for table spaces. """ ver = self.manager.version if ver >= 90600: SQL = render_template( "/".join(['tablespaces/sql/9.6_plus', 'variables.sql']) ) else: SQL = render_template( "/".join([self.template_path, 'variables.sql']) ) status, rset = self.conn.execute_dict(SQL) if not status: return internal_server_error(errormsg=rset) return make_json_response( data=rset['rows'], status=200 )
[ "def", "variable_options", "(", "self", ",", "gid", ",", "sid", ")", ":", "ver", "=", "self", ".", "manager", ".", "version", "if", "ver", ">=", "90600", ":", "SQL", "=", "render_template", "(", "\"/\"", ".", "join", "(", "[", "'tablespaces/sql/9.6_plus'...
https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/browser/server_groups/servers/tablespaces/__init__.py#L616-L643
pm4py/pm4py-core
7807b09a088b02199cd0149d724d0e28793971bf
pm4py/streaming/algo/discovery/dfg/algorithm.py
python
apply
(variant=DEFAULT_VARIANT, parameters=None)
return exec_utils.get_variant(variant).apply(parameters=parameters)
Discovers a DFG from an event stream Parameters -------------- variant Variant of the algorithm (default: Variants.FREQUENCY) Returns -------------- stream_dfg_obj Streaming DFG discovery object
Discovers a DFG from an event stream
[ "Discovers", "a", "DFG", "from", "an", "event", "stream" ]
def apply(variant=DEFAULT_VARIANT, parameters=None): """ Discovers a DFG from an event stream Parameters -------------- variant Variant of the algorithm (default: Variants.FREQUENCY) Returns -------------- stream_dfg_obj Streaming DFG discovery object """ if parameters is None: parameters = {} return exec_utils.get_variant(variant).apply(parameters=parameters)
[ "def", "apply", "(", "variant", "=", "DEFAULT_VARIANT", ",", "parameters", "=", "None", ")", ":", "if", "parameters", "is", "None", ":", "parameters", "=", "{", "}", "return", "exec_utils", ".", "get_variant", "(", "variant", ")", ".", "apply", "(", "par...
https://github.com/pm4py/pm4py-core/blob/7807b09a088b02199cd0149d724d0e28793971bf/pm4py/streaming/algo/discovery/dfg/algorithm.py#L29-L46
ryanmcgrath/twython
0c405604285364457f3c309969f11ba68163bd05
twython/endpoints.py
python
EndpointsMixin.create_block
(self, **params)
return self.post('blocks/create', params=params)
Blocks the specified user from following the authenticating user. Docs: https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-blocks-create
Blocks the specified user from following the authenticating user.
[ "Blocks", "the", "specified", "user", "from", "following", "the", "authenticating", "user", "." ]
def create_block(self, **params): """Blocks the specified user from following the authenticating user. Docs: https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-blocks-create """ return self.post('blocks/create', params=params)
[ "def", "create_block", "(", "self", ",", "*", "*", "params", ")", ":", "return", "self", ".", "post", "(", "'blocks/create'", ",", "params", "=", "params", ")" ]
https://github.com/ryanmcgrath/twython/blob/0c405604285364457f3c309969f11ba68163bd05/twython/endpoints.py#L590-L597
kbandla/dpkt
7a91ae53bb20563607f32e6781ef40d2efe6520d
dpkt/dns.py
python
DNS.pack_q
(self, buf, q)
return buf + pack_name(q.name, len(buf), self.label_ptrs) + struct.pack('>HH', q.type, q.cls)
Append packed DNS question and return buf.
Append packed DNS question and return buf.
[ "Append", "packed", "DNS", "question", "and", "return", "buf", "." ]
def pack_q(self, buf, q): """Append packed DNS question and return buf.""" return buf + pack_name(q.name, len(buf), self.label_ptrs) + struct.pack('>HH', q.type, q.cls)
[ "def", "pack_q", "(", "self", ",", "buf", ",", "q", ")", ":", "return", "buf", "+", "pack_name", "(", "q", ".", "name", ",", "len", "(", "buf", ")", ",", "self", ".", "label_ptrs", ")", "+", "struct", ".", "pack", "(", "'>HH'", ",", "q", ".", ...
https://github.com/kbandla/dpkt/blob/7a91ae53bb20563607f32e6781ef40d2efe6520d/dpkt/dns.py#L325-L327
gnuradio/pybombs
17044241bf835b93571026b112f179f2db7448a4
pybombs/config_file.py
python
PBConfigFile.save
(self, newdata=None)
Write the contents of the data cache to the file.
Write the contents of the data cache to the file.
[ "Write", "the", "contents", "of", "the", "data", "cache", "to", "the", "file", "." ]
def save(self, newdata=None): " Write the contents of the data cache to the file. " if newdata is not None: assert isinstance(newdata, dict) self.data = newdata fpath = os.path.split(self._filename)[0] if len(fpath): sysutils.mkdirp_writable(fpath) with open(self._filename, 'w') as fn: self.yaml.dump(self.data, fn)
[ "def", "save", "(", "self", ",", "newdata", "=", "None", ")", ":", "if", "newdata", "is", "not", "None", ":", "assert", "isinstance", "(", "newdata", ",", "dict", ")", "self", ".", "data", "=", "newdata", "fpath", "=", "os", ".", "path", ".", "spli...
https://github.com/gnuradio/pybombs/blob/17044241bf835b93571026b112f179f2db7448a4/pybombs/config_file.py#L95-L104
t4ngo/dragonfly
3c885cbf1a63b373fd725d4bbfcb716e162dc92c
dragonfly/grammar/grammar_base.py
python
Grammar.disable
(self)
Disable this grammar so that it is not active to receive recognitions.
Disable this grammar so that it is not active to receive recognitions.
[ "Disable", "this", "grammar", "so", "that", "it", "is", "not", "active", "to", "receive", "recognitions", "." ]
def disable(self): """ Disable this grammar so that it is not active to receive recognitions. """ self._enabled = False
[ "def", "disable", "(", "self", ")", ":", "self", ".", "_enabled", "=", "False" ]
https://github.com/t4ngo/dragonfly/blob/3c885cbf1a63b373fd725d4bbfcb716e162dc92c/dragonfly/grammar/grammar_base.py#L127-L133
CuriousAI/mean-teacher
546348ff863c998c26be4339021425df973b4a36
tensorflow/mean_teacher/model.py
python
tower
(inputs, is_training, dropout_probability, input_noise, normalize_input, flip_horizontally, translate, num_logits, is_initialization=False, name=None)
[]
def tower(inputs, is_training, dropout_probability, input_noise, normalize_input, flip_horizontally, translate, num_logits, is_initialization=False, name=None): with tf.name_scope(name, "tower"): default_conv_args = dict( padding='SAME', kernel_size=[3, 3], activation_fn=nn.lrelu, init=is_initialization ) training_mode_funcs = [ nn.random_translate, nn.flip_randomly, nn.gaussian_noise, slim.dropout, wn.fully_connected, wn.conv2d ] training_args = dict( is_training=is_training ) with \ slim.arg_scope([wn.conv2d], **default_conv_args), \ slim.arg_scope(training_mode_funcs, **training_args): net = inputs assert_shape(net, [None, 32, 32, 3]) net = tf.cond(normalize_input, lambda: slim.layer_norm(net, scale=False, center=False, scope='normalize_inputs'), lambda: net) assert_shape(net, [None, 32, 32, 3]) net = nn.flip_randomly(net, horizontally=flip_horizontally, vertically=False, name='random_flip') net = tf.cond(translate, lambda: nn.random_translate(net, scale=2, name='random_translate'), lambda: net) net = nn.gaussian_noise(net, scale=input_noise, name='gaussian_noise') net = wn.conv2d(net, 128, scope="conv_1_1") net = wn.conv2d(net, 128, scope="conv_1_2") net = wn.conv2d(net, 128, scope="conv_1_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_1') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_1') assert_shape(net, [None, 16, 16, 128]) net = wn.conv2d(net, 256, scope="conv_2_1") net = wn.conv2d(net, 256, scope="conv_2_2") net = wn.conv2d(net, 256, scope="conv_2_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_2') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_2') assert_shape(net, [None, 8, 8, 256]) net = wn.conv2d(net, 512, padding='VALID', scope="conv_3_1") assert_shape(net, [None, 6, 6, 512]) net = wn.conv2d(net, 256, kernel_size=[1, 1], scope="conv_3_2") net = wn.conv2d(net, 128, kernel_size=[1, 1], scope="conv_3_3") net = slim.avg_pool2d(net, [6, 6], scope='avg_pool') assert_shape(net, [None, 1, 1, 128]) net = slim.flatten(net) assert_shape(net, [None, 128]) primary_logits = wn.fully_connected(net, 10, init=is_initialization) secondary_logits = wn.fully_connected(net, 10, init=is_initialization) with tf.control_dependencies([tf.assert_greater_equal(num_logits, 1), tf.assert_less_equal(num_logits, 2)]): secondary_logits = tf.case([ (tf.equal(num_logits, 1), lambda: primary_logits), (tf.equal(num_logits, 2), lambda: secondary_logits), ], exclusive=True, default=lambda: primary_logits) assert_shape(primary_logits, [None, 10]) assert_shape(secondary_logits, [None, 10]) return primary_logits, secondary_logits
[ "def", "tower", "(", "inputs", ",", "is_training", ",", "dropout_probability", ",", "input_noise", ",", "normalize_input", ",", "flip_horizontally", ",", "translate", ",", "num_logits", ",", "is_initialization", "=", "False", ",", "name", "=", "None", ")", ":", ...
https://github.com/CuriousAI/mean-teacher/blob/546348ff863c998c26be4339021425df973b4a36/tensorflow/mean_teacher/model.py#L357-L442
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/pyplot.py
python
bone
()
Set the colormap to "bone". This changes the default colormap as well as the colormap of the current image if there is one. See ``help(colormaps)`` for more information.
Set the colormap to "bone".
[ "Set", "the", "colormap", "to", "bone", "." ]
def bone(): """ Set the colormap to "bone". This changes the default colormap as well as the colormap of the current image if there is one. See ``help(colormaps)`` for more information. """ set_cmap("bone")
[ "def", "bone", "(", ")", ":", "set_cmap", "(", "\"bone\"", ")" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/pyplot.py#L3099-L3106
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/prompt_toolkit/document.py
python
Document.selection_range_at_line
(self, row)
If the selection spans a portion of the given line, return a (from, to) tuple. The returned upper boundary is not included in the selection, so `(0, 0)` is an empty selection. `(0, 1)`, is a one character selection. Returns None if the selection doesn't cover this line at all.
If the selection spans a portion of the given line, return a (from, to) tuple.
[ "If", "the", "selection", "spans", "a", "portion", "of", "the", "given", "line", "return", "a", "(", "from", "to", ")", "tuple", "." ]
def selection_range_at_line(self, row): """ If the selection spans a portion of the given line, return a (from, to) tuple. The returned upper boundary is not included in the selection, so `(0, 0)` is an empty selection. `(0, 1)`, is a one character selection. Returns None if the selection doesn't cover this line at all. """ if self.selection: line = self.lines[row] row_start = self.translate_row_col_to_index(row, 0) row_end = self.translate_row_col_to_index(row, len(line)) from_, to = sorted([self.cursor_position, self.selection.original_cursor_position]) # Take the intersection of the current line and the selection. intersection_start = max(row_start, from_) intersection_end = min(row_end, to) if intersection_start <= intersection_end: if self.selection.type == SelectionType.LINES: intersection_start = row_start intersection_end = row_end elif self.selection.type == SelectionType.BLOCK: _, col1 = self.translate_index_to_position(from_) _, col2 = self.translate_index_to_position(to) col1, col2 = sorted([col1, col2]) if col1 > len(line): return # Block selection doesn't cross this line. intersection_start = self.translate_row_col_to_index(row, col1) intersection_end = self.translate_row_col_to_index(row, col2) _, from_column = self.translate_index_to_position(intersection_start) _, to_column = self.translate_index_to_position(intersection_end) # In Vi mode, the upper boundary is always included. For Emacs # mode, that's not the case. if vi_mode(): to_column += 1 return from_column, to_column
[ "def", "selection_range_at_line", "(", "self", ",", "row", ")", ":", "if", "self", ".", "selection", ":", "line", "=", "self", ".", "lines", "[", "row", "]", "row_start", "=", "self", ".", "translate_row_col_to_index", "(", "row", ",", "0", ")", "row_end...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/prompt_toolkit/document.py#L830-L875
holoviz/geoviews
b7a5ce742ebc5d7576e4dbd0249aafc0f1d0fb88
geoviews/data/iris.py
python
CubeInterface.length
(cls, dataset)
return np.product([len(d.points) for d in dataset.data.coords(dim_coords=True)], dtype=np.intp)
Returns the total number of samples in the dataset.
Returns the total number of samples in the dataset.
[ "Returns", "the", "total", "number", "of", "samples", "in", "the", "dataset", "." ]
def length(cls, dataset): """ Returns the total number of samples in the dataset. """ return np.product([len(d.points) for d in dataset.data.coords(dim_coords=True)], dtype=np.intp)
[ "def", "length", "(", "cls", ",", "dataset", ")", ":", "return", "np", ".", "product", "(", "[", "len", "(", "d", ".", "points", ")", "for", "d", "in", "dataset", ".", "data", ".", "coords", "(", "dim_coords", "=", "True", ")", "]", ",", "dtype",...
https://github.com/holoviz/geoviews/blob/b7a5ce742ebc5d7576e4dbd0249aafc0f1d0fb88/geoviews/data/iris.py#L350-L354
mrlesmithjr/Ansible
d44f0dc0d942bdf3bf7334b307e6048f0ee16e36
roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pkg_resources/_vendor/appdirs.py
python
site_data_dir
(appname=None, appauthor=None, version=None, multipath=False)
return path
Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical user data directories are: Mac OS X: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
Return full path to the user-shared data dir for this application.
[ "Return", "full", "path", "to", "the", "user", "-", "shared", "data", "dir", "for", "this", "application", "." ]
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): """Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical user data directories are: Mac OS X: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == 'darwin': path = os.path.expanduser('/Library/Application Support') if appname: path = os.path.join(path, appname) else: # XDG default for $XDG_DATA_DIRS # only first, if multipath is False path = os.getenv('XDG_DATA_DIRS', os.pathsep.join(['/usr/local/share', '/usr/share'])) pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path if appname and version: path = os.path.join(path, version) return path
[ "def", "site_data_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "multipath", "=", "False", ")", ":", "if", "system", "==", "\"win32\"", ":", "if", "appauthor", "is", "None", ":", "appauthor", "=", "...
https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pkg_resources/_vendor/appdirs.py#L100-L163
kivy/kivy
fbf561f73ddba9941b1b7e771f86264c6e6eef36
kivy/vector.py
python
Vector.normalize
(self)
return self / self.length()
Returns a new vector that has the same direction as vec, but has a length of one. >>> v = Vector(88, 33).normalize() >>> v [0.93632917756904444, 0.3511234415883917] >>> v.length() 1.0
Returns a new vector that has the same direction as vec, but has a length of one.
[ "Returns", "a", "new", "vector", "that", "has", "the", "same", "direction", "as", "vec", "but", "has", "a", "length", "of", "one", "." ]
def normalize(self): '''Returns a new vector that has the same direction as vec, but has a length of one. >>> v = Vector(88, 33).normalize() >>> v [0.93632917756904444, 0.3511234415883917] >>> v.length() 1.0 ''' if self[0] == 0. and self[1] == 0.: return Vector(0., 0.) return self / self.length()
[ "def", "normalize", "(", "self", ")", ":", "if", "self", "[", "0", "]", "==", "0.", "and", "self", "[", "1", "]", "==", "0.", ":", "return", "Vector", "(", "0.", ",", "0.", ")", "return", "self", "/", "self", ".", "length", "(", ")" ]
https://github.com/kivy/kivy/blob/fbf561f73ddba9941b1b7e771f86264c6e6eef36/kivy/vector.py#L265-L278
pyeventsourcing/eventsourcing
f5a36f434ab2631890092b6c7714b8fb8c94dc7c
eventsourcing/persistence.py
python
EventStore.get
( self, originator_id: UUID, gt: Optional[int] = None, lte: Optional[int] = None, desc: bool = False, limit: Optional[int] = None, )
return cast( Iterator[TDomainEvent], map( self.mapper.to_domain_event, self.recorder.select_events( originator_id=originator_id, gt=gt, lte=lte, desc=desc, limit=limit, ), ), )
Retrieves domain events from aggregate sequence.
Retrieves domain events from aggregate sequence.
[ "Retrieves", "domain", "events", "from", "aggregate", "sequence", "." ]
def get( self, originator_id: UUID, gt: Optional[int] = None, lte: Optional[int] = None, desc: bool = False, limit: Optional[int] = None, ) -> Iterator[TDomainEvent]: """ Retrieves domain events from aggregate sequence. """ return cast( Iterator[TDomainEvent], map( self.mapper.to_domain_event, self.recorder.select_events( originator_id=originator_id, gt=gt, lte=lte, desc=desc, limit=limit, ), ), )
[ "def", "get", "(", "self", ",", "originator_id", ":", "UUID", ",", "gt", ":", "Optional", "[", "int", "]", "=", "None", ",", "lte", ":", "Optional", "[", "int", "]", "=", "None", ",", "desc", ":", "bool", "=", "False", ",", "limit", ":", "Optiona...
https://github.com/pyeventsourcing/eventsourcing/blob/f5a36f434ab2631890092b6c7714b8fb8c94dc7c/eventsourcing/persistence.py#L545-L568
knownsec/Pocsuite
877d1b1604629b8dcd6e53b167c3c98249e5e94f
pocsuite/thirdparty/requests/packages/urllib3/packages/ordered_dict.py
python
OrderedDict.viewvalues
(self)
return ValuesView(self)
od.viewvalues() -> an object providing a view on od's values
od.viewvalues() -> an object providing a view on od's values
[ "od", ".", "viewvalues", "()", "-", ">", "an", "object", "providing", "a", "view", "on", "od", "s", "values" ]
def viewvalues(self): "od.viewvalues() -> an object providing a view on od's values" return ValuesView(self)
[ "def", "viewvalues", "(", "self", ")", ":", "return", "ValuesView", "(", "self", ")" ]
https://github.com/knownsec/Pocsuite/blob/877d1b1604629b8dcd6e53b167c3c98249e5e94f/pocsuite/thirdparty/requests/packages/urllib3/packages/ordered_dict.py#L253-L255
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-35/fabmetheus_utilities/settings.py
python
HelpPage.getOpenFromAfterWWW
( self, afterWWW )
return self.openPage
Get the open help page function from the afterWWW of the address after the www.
Get the open help page function from the afterWWW of the address after the www.
[ "Get", "the", "open", "help", "page", "function", "from", "the", "afterWWW", "of", "the", "address", "after", "the", "www", "." ]
def getOpenFromAfterWWW( self, afterWWW ): "Get the open help page function from the afterWWW of the address after the www." self.hypertextAddress = 'http://www.' + afterWWW return self.openPage
[ "def", "getOpenFromAfterWWW", "(", "self", ",", "afterWWW", ")", ":", "self", ".", "hypertextAddress", "=", "'http://www.'", "+", "afterWWW", "return", "self", ".", "openPage" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/settings.py#L1170-L1173
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/backends/backend_agg.py
python
RendererAgg.draw_mathtext
(self, gc, x, y, s, prop, angle)
Draw the math text using matplotlib.mathtext
Draw the math text using matplotlib.mathtext
[ "Draw", "the", "math", "text", "using", "matplotlib", ".", "mathtext" ]
def draw_mathtext(self, gc, x, y, s, prop, angle): """ Draw the math text using matplotlib.mathtext """ ox, oy, width, height, descent, font_image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) xd = descent * sin(radians(angle)) yd = descent * cos(radians(angle)) x = np.round(x + ox + xd) y = np.round(y - oy + yd) self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
[ "def", "draw_mathtext", "(", "self", ",", "gc", ",", "x", ",", "y", ",", "s", ",", "prop", ",", "angle", ")", ":", "ox", ",", "oy", ",", "width", ",", "height", ",", "descent", ",", "font_image", ",", "used_characters", "=", "self", ".", "mathtext_...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/backends/backend_agg.py#L154-L165
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/ntpath.py
python
relpath
(path, start=curdir)
return join(*rel_list)
Return a relative version of a path
Return a relative version of a path
[ "Return", "a", "relative", "version", "of", "a", "path" ]
def relpath(path, start=curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_is_unc, start_prefix, start_list = _abspath_split(start) path_is_unc, path_prefix, path_list = _abspath_split(path) if path_is_unc ^ start_is_unc: raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start)) if path_prefix.lower() != start_prefix.lower(): if path_is_unc: raise ValueError("path is on UNC root %s, start on UNC root %s" % (path_prefix, start_prefix)) else: raise ValueError("path is on drive %s, start on drive %s" % (path_prefix, start_prefix)) # Work out how much of the filepath is shared by start and path. i = 0 for e1, e2 in zip(start_list, path_list): if e1.lower() != e2.lower(): break i += 1 rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list)
[ "def", "relpath", "(", "path", ",", "start", "=", "curdir", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "\"no path specified\"", ")", "start_is_unc", ",", "start_prefix", ",", "start_list", "=", "_abspath_split", "(", "start", ")", "path_...
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/ntpath.py#L511-L540
CharlesShang/FastMaskRCNN
bdae07702acccd85803e658f5e49690981efcdb2
libs/nets/resnet_v1.py
python
resnet_v1
(inputs, blocks, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, reuse=None, scope=None)
Generator for v1 ResNet models. This function generates a family of ResNet v1 models. See the resnet_v1_*() methods for specific model instantiations, obtained by selecting different block instantiations that produce ResNets of various depths. Training for image classification on Imagenet is usually done with [224, 224] inputs, resulting in [7, 7] feature maps at the output of the last ResNet block for the ResNets defined in [1] that have nominal stride equal to 32. However, for dense prediction tasks we advise that one uses inputs with spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In this case the feature maps at the ResNet output will have spatial shape [(height - 1) / output_stride + 1, (width - 1) / output_stride + 1] and corners exactly aligned with the input image corners, which greatly facilitates alignment of the features to the image. Using as input [225, 225] images results in [8, 8] feature maps at the output of the last ResNet block. For dense prediction tasks, the ResNet needs to run in fully-convolutional (FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all have nominal stride equal to 32 and a good choice in FCN mode is to use output_stride=16 in order to increase the density of the computed features at small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. blocks: A list of length equal to the number of ResNet blocks. Each element is a resnet_utils.Block object describing the units in the block. num_classes: Number of predicted classes for classification tasks. If None we return the features before the logit layer. is_training: whether is training or not. global_pool: If True, we perform global average pooling before computing the logits. Set to True for image classification, False for dense prediction. output_stride: If None, then the output will be computed at the nominal network stride. If output_stride is not None, it specifies the requested ratio of input to output spatial resolution. include_root_block: If True, include the initial convolution followed by max-pooling, if False excludes it. spatial_squeeze: if True, logits is of shape [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: net: A rank-4 tensor of size [batch, height_out, width_out, channels_out]. If global_pool is False, then height_out and width_out are reduced by a factor of output_stride compared to the respective height_in and width_in, else both height_out and width_out equal one. If num_classes is None, then net is the output of the last ResNet block, potentially after global average pooling. If num_classes is not None, net contains the pre-softmax activations. end_points: A dictionary from components of the network to the corresponding activation. Raises: ValueError: If the target output_stride is not valid.
Generator for v1 ResNet models.
[ "Generator", "for", "v1", "ResNet", "models", "." ]
def resnet_v1(inputs, blocks, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, reuse=None, scope=None): """Generator for v1 ResNet models. This function generates a family of ResNet v1 models. See the resnet_v1_*() methods for specific model instantiations, obtained by selecting different block instantiations that produce ResNets of various depths. Training for image classification on Imagenet is usually done with [224, 224] inputs, resulting in [7, 7] feature maps at the output of the last ResNet block for the ResNets defined in [1] that have nominal stride equal to 32. However, for dense prediction tasks we advise that one uses inputs with spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In this case the feature maps at the ResNet output will have spatial shape [(height - 1) / output_stride + 1, (width - 1) / output_stride + 1] and corners exactly aligned with the input image corners, which greatly facilitates alignment of the features to the image. Using as input [225, 225] images results in [8, 8] feature maps at the output of the last ResNet block. For dense prediction tasks, the ResNet needs to run in fully-convolutional (FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all have nominal stride equal to 32 and a good choice in FCN mode is to use output_stride=16 in order to increase the density of the computed features at small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. blocks: A list of length equal to the number of ResNet blocks. Each element is a resnet_utils.Block object describing the units in the block. num_classes: Number of predicted classes for classification tasks. If None we return the features before the logit layer. is_training: whether is training or not. global_pool: If True, we perform global average pooling before computing the logits. Set to True for image classification, False for dense prediction. output_stride: If None, then the output will be computed at the nominal network stride. If output_stride is not None, it specifies the requested ratio of input to output spatial resolution. include_root_block: If True, include the initial convolution followed by max-pooling, if False excludes it. spatial_squeeze: if True, logits is of shape [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: net: A rank-4 tensor of size [batch, height_out, width_out, channels_out]. If global_pool is False, then height_out and width_out are reduced by a factor of output_stride compared to the respective height_in and width_in, else both height_out and width_out equal one. If num_classes is None, then net is the output of the last ResNet block, potentially after global average pooling. If num_classes is not None, net contains the pre-softmax activations. end_points: A dictionary from components of the network to the corresponding activation. Raises: ValueError: If the target output_stride is not valid. """ with tf.variable_scope(scope, 'resnet_v1', [inputs], reuse=reuse) as sc: end_points_collection = sc.name + '_end_points' with slim.arg_scope([slim.conv2d, bottleneck, resnet_utils.stack_blocks_dense], outputs_collections=end_points_collection): with slim.arg_scope([slim.batch_norm], is_training=is_training): net = inputs if include_root_block: if output_stride is not None: if output_stride % 4 != 0: raise ValueError('The output_stride needs to be a multiple of 4.') output_stride /= 4 net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1') net = slim.max_pool2d(net, [3, 3], stride=2, scope='pool1') net = resnet_utils.stack_blocks_dense(net, blocks, output_stride) if global_pool: # Global average pooling. net = tf.reduce_mean(net, [1, 2], name='pool5', keep_dims=True) if num_classes is not None: net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='logits') if spatial_squeeze: logits = tf.squeeze(net, [1, 2], name='SpatialSqueeze') # Convert end_points_collection into a dictionary of end_points. end_points = slim.utils.convert_collection_to_dict(end_points_collection) if num_classes is not None: end_points['predictions'] = slim.softmax(logits, scope='predictions') return logits, end_points
[ "def", "resnet_v1", "(", "inputs", ",", "blocks", ",", "num_classes", "=", "None", ",", "is_training", "=", "True", ",", "global_pool", "=", "True", ",", "output_stride", "=", "None", ",", "include_root_block", "=", "True", ",", "spatial_squeeze", "=", "True...
https://github.com/CharlesShang/FastMaskRCNN/blob/bdae07702acccd85803e658f5e49690981efcdb2/libs/nets/resnet_v1.py#L115-L209
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/feature_extraction_utils.py
python
FeatureExtractionMixin.to_json_string
(self)
return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
Serializes this instance to a JSON string. Returns: `str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
Serializes this instance to a JSON string.
[ "Serializes", "this", "instance", "to", "a", "JSON", "string", "." ]
def to_json_string(self) -> str: """ Serializes this instance to a JSON string. Returns: `str`: String containing all the attributes that make up this feature_extractor instance in JSON format. """ dictionary = self.to_dict() for key, value in dictionary.items(): if isinstance(value, np.ndarray): dictionary[key] = value.tolist() # make sure private name "_processor_class" is correctly # saved as "processor_class" if dictionary.get("_processor_class", None) is not None: dictionary["processor_class"] = dictionary.pop("_processor_class") return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
[ "def", "to_json_string", "(", "self", ")", "->", "str", ":", "dictionary", "=", "self", ".", "to_dict", "(", ")", "for", "key", ",", "value", "in", "dictionary", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "np", ".", "ndarray"...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/feature_extraction_utils.py#L477-L495
UKPLab/sentence-transformers
2158fff3aa96651b10fe367c41fdd5008a33c5c6
sentence_transformers/readers/STSDataReader.py
python
STSDataReader.get_examples
(self, filename, max_examples=0)
return examples
filename specified which data split to use (train.csv, dev.csv, test.csv).
filename specified which data split to use (train.csv, dev.csv, test.csv).
[ "filename", "specified", "which", "data", "split", "to", "use", "(", "train", ".", "csv", "dev", ".", "csv", "test", ".", "csv", ")", "." ]
def get_examples(self, filename, max_examples=0): """ filename specified which data split to use (train.csv, dev.csv, test.csv). """ filepath = os.path.join(self.dataset_folder, filename) with gzip.open(filepath, 'rt', encoding='utf8') if filename.endswith('.gz') else open(filepath, encoding="utf-8") as fIn: data = csv.reader(fIn, delimiter=self.delimiter, quoting=self.quoting) examples = [] for id, row in enumerate(data): score = float(row[self.score_col_idx]) if self.normalize_scores: # Normalize to a 0...1 value score = (score - self.min_score) / (self.max_score - self.min_score) s1 = row[self.s1_col_idx] s2 = row[self.s2_col_idx] examples.append(InputExample(guid=filename+str(id), texts=[s1, s2], label=score)) if max_examples > 0 and len(examples) >= max_examples: break return examples
[ "def", "get_examples", "(", "self", ",", "filename", ",", "max_examples", "=", "0", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dataset_folder", ",", "filename", ")", "with", "gzip", ".", "open", "(", "filepath", ",", ...
https://github.com/UKPLab/sentence-transformers/blob/2158fff3aa96651b10fe367c41fdd5008a33c5c6/sentence_transformers/readers/STSDataReader.py#L24-L44
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/contrib/gis/gdal/layer.py
python
Layer.get_fields
(self, field_name)
return [feat.get(field_name) for feat in self]
Returns a list containing the given field name for every Feature in the Layer.
Returns a list containing the given field name for every Feature in the Layer.
[ "Returns", "a", "list", "containing", "the", "given", "field", "name", "for", "every", "Feature", "in", "the", "Layer", "." ]
def get_fields(self, field_name): """ Returns a list containing the given field name for every Feature in the Layer. """ if not field_name in self.fields: raise OGRException('invalid field name: %s' % field_name) return [feat.get(field_name) for feat in self]
[ "def", "get_fields", "(", "self", ",", "field_name", ")", ":", "if", "not", "field_name", "in", "self", ".", "fields", ":", "raise", "OGRException", "(", "'invalid field name: %s'", "%", "field_name", ")", "return", "[", "feat", ".", "get", "(", "field_name"...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/contrib/gis/gdal/layer.py#L190-L197
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/ADT/MolKit/pdb2pqr/src/psize.py
python
Psize.parseInput
(self, filename)
Parse input structure file in PDB or PQR format
Parse input structure file in PDB or PQR format
[ "Parse", "input", "structure", "file", "in", "PDB", "or", "PQR", "format" ]
def parseInput(self, filename): """ Parse input structure file in PDB or PQR format """ file = open(filename, "r") self.parseLines(file.readlines())
[ "def", "parseInput", "(", "self", ",", "filename", ")", ":", "file", "=", "open", "(", "filename", ",", "\"r\"", ")", "self", ".", "parseLines", "(", "file", ".", "readlines", "(", ")", ")" ]
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/ADT/MolKit/pdb2pqr/src/psize.py#L98-L101
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/nbformat/sign.py
python
signature_removed
(nb)
Context manager for operating on a notebook with its signature removed Used for excluding the previous signature when computing a notebook's signature.
Context manager for operating on a notebook with its signature removed Used for excluding the previous signature when computing a notebook's signature.
[ "Context", "manager", "for", "operating", "on", "a", "notebook", "with", "its", "signature", "removed", "Used", "for", "excluding", "the", "previous", "signature", "when", "computing", "a", "notebook", "s", "signature", "." ]
def signature_removed(nb): """Context manager for operating on a notebook with its signature removed Used for excluding the previous signature when computing a notebook's signature. """ save_signature = nb['metadata'].pop('signature', None) try: yield finally: if save_signature is not None: nb['metadata']['signature'] = save_signature
[ "def", "signature_removed", "(", "nb", ")", ":", "save_signature", "=", "nb", "[", "'metadata'", "]", ".", "pop", "(", "'signature'", ",", "None", ")", "try", ":", "yield", "finally", ":", "if", "save_signature", "is", "not", "None", ":", "nb", "[", "'...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/nbformat/sign.py#L299-L309
open-mmlab/mmdetection3d
c7272063e818bcf33aebc498a017a95c8d065143
mmdet3d/core/bbox/transforms.py
python
bbox3d2result
(bboxes, scores, labels, attrs=None)
return result_dict
Convert detection results to a list of numpy arrays. Args: bboxes (torch.Tensor): Bounding boxes with shape of (n, 5). labels (torch.Tensor): Labels with shape of (n, ). scores (torch.Tensor): Scores with shape of (n, ). attrs (torch.Tensor, optional): Attributes with shape of (n, ). \ Defaults to None. Returns: dict[str, torch.Tensor]: Bounding box results in cpu mode. - boxes_3d (torch.Tensor): 3D boxes. - scores (torch.Tensor): Prediction scores. - labels_3d (torch.Tensor): Box labels. - attrs_3d (torch.Tensor, optional): Box attributes.
Convert detection results to a list of numpy arrays.
[ "Convert", "detection", "results", "to", "a", "list", "of", "numpy", "arrays", "." ]
def bbox3d2result(bboxes, scores, labels, attrs=None): """Convert detection results to a list of numpy arrays. Args: bboxes (torch.Tensor): Bounding boxes with shape of (n, 5). labels (torch.Tensor): Labels with shape of (n, ). scores (torch.Tensor): Scores with shape of (n, ). attrs (torch.Tensor, optional): Attributes with shape of (n, ). \ Defaults to None. Returns: dict[str, torch.Tensor]: Bounding box results in cpu mode. - boxes_3d (torch.Tensor): 3D boxes. - scores (torch.Tensor): Prediction scores. - labels_3d (torch.Tensor): Box labels. - attrs_3d (torch.Tensor, optional): Box attributes. """ result_dict = dict( boxes_3d=bboxes.to('cpu'), scores_3d=scores.cpu(), labels_3d=labels.cpu()) if attrs is not None: result_dict['attrs_3d'] = attrs.cpu() return result_dict
[ "def", "bbox3d2result", "(", "bboxes", ",", "scores", ",", "labels", ",", "attrs", "=", "None", ")", ":", "result_dict", "=", "dict", "(", "boxes_3d", "=", "bboxes", ".", "to", "(", "'cpu'", ")", ",", "scores_3d", "=", "scores", ".", "cpu", "(", ")",...
https://github.com/open-mmlab/mmdetection3d/blob/c7272063e818bcf33aebc498a017a95c8d065143/mmdet3d/core/bbox/transforms.py#L50-L76
suurjaak/Skyperious
6a4f264dbac8d326c2fa8aeb5483dbca987860bf
skyperious/gui.py
python
ChatContentSTC.IsMessageShown
(self, message_id)
return (message_id in self._message_positions)
Returns whether the specified message is currently shown.
Returns whether the specified message is currently shown.
[ "Returns", "whether", "the", "specified", "message", "is", "currently", "shown", "." ]
def IsMessageShown(self, message_id): """Returns whether the specified message is currently shown.""" return (message_id in self._message_positions)
[ "def", "IsMessageShown", "(", "self", ",", "message_id", ")", ":", "return", "(", "message_id", "in", "self", ".", "_message_positions", ")" ]
https://github.com/suurjaak/Skyperious/blob/6a4f264dbac8d326c2fa8aeb5483dbca987860bf/skyperious/gui.py#L8096-L8098
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/email/_header_value_parser.py
python
get_local_part
(value)
return local_part, value
local-part = dot-atom / quoted-string / obs-local-part
local-part = dot-atom / quoted-string / obs-local-part
[ "local", "-", "part", "=", "dot", "-", "atom", "/", "quoted", "-", "string", "/", "obs", "-", "local", "-", "part" ]
def get_local_part(value): """ local-part = dot-atom / quoted-string / obs-local-part """ local_part = LocalPart() leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise errors.HeaderParseError( "expected local-part but found '{}'".format(value)) try: token, value = get_dot_atom(value) except errors.HeaderParseError: try: token, value = get_word(value) except errors.HeaderParseError: if value[0] != '\\' and value[0] in PHRASE_ENDS: raise token = TokenList() if leader is not None: token[:0] = [leader] local_part.append(token) if value and (value[0]=='\\' or value[0] not in PHRASE_ENDS): obs_local_part, value = get_obs_local_part(str(local_part) + value) if obs_local_part.token_type == 'invalid-obs-local-part': local_part.defects.append(errors.InvalidHeaderDefect( "local-part is not dot-atom, quoted-string, or obs-local-part")) else: local_part.defects.append(errors.ObsoleteHeaderDefect( "local-part is not a dot-atom (contains CFWS)")) local_part[0] = obs_local_part try: local_part.value.encode('ascii') except UnicodeEncodeError: local_part.defects.append(errors.NonASCIILocalPartDefect( "local-part contains non-ASCII characters)")) return local_part, value
[ "def", "get_local_part", "(", "value", ")", ":", "local_part", "=", "LocalPart", "(", ")", "leader", "=", "None", "if", "value", "[", "0", "]", "in", "CFWS_LEADER", ":", "leader", ",", "value", "=", "get_cfws", "(", "value", ")", "if", "not", "value", ...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/email/_header_value_parser.py#L1791-L1828
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/distutils/archive_util.py
python
_get_gid
(name)
return None
Returns a gid, given a group name.
Returns a gid, given a group name.
[ "Returns", "a", "gid", "given", "a", "group", "name", "." ]
def _get_gid(name): """Returns a gid, given a group name.""" if getgrnam is None or name is None: return None try: result = getgrnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "def", "_get_gid", "(", "name", ")", ":", "if", "getgrnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getgrnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "i...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/distutils/archive_util.py#L27-L37
ring04h/wyportmap
c4201e2313504e780a7f25238eba2a2d3223e739
sqlalchemy/sql/elements.py
python
ColumnElement.label
(self, name)
return Label(name, self, self.type)
Produce a column label, i.e. ``<columnname> AS <name>``. This is a shortcut to the :func:`~.expression.label` function. if 'name' is None, an anonymous label name will be generated.
Produce a column label, i.e. ``<columnname> AS <name>``.
[ "Produce", "a", "column", "label", "i", ".", "e", ".", "<columnname", ">", "AS", "<name", ">", "." ]
def label(self, name): """Produce a column label, i.e. ``<columnname> AS <name>``. This is a shortcut to the :func:`~.expression.label` function. if 'name' is None, an anonymous label name will be generated. """ return Label(name, self, self.type)
[ "def", "label", "(", "self", ",", "name", ")", ":", "return", "Label", "(", "name", ",", "self", ",", "self", ".", "type", ")" ]
https://github.com/ring04h/wyportmap/blob/c4201e2313504e780a7f25238eba2a2d3223e739/sqlalchemy/sql/elements.py#L774-L782
JacquesLucke/animation_nodes
b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1
animation_nodes/nodes/mesh/offset_polygons.py
python
OffsetPolygonsNode.drawAdvanced
(self, layout)
[]
def drawAdvanced(self, layout): layout.prop(self, "pivotSource", text = "Local Pivots") if self.pivotSource == "CUSTOM_MATRICES" and "LOCAL_AXIS" not in self.rotationMode: layout.label(text = "Try to change the rotation mode.", icon = "INFO") self.drawAdvanced_MatrixTransformationProperties(layout)
[ "def", "drawAdvanced", "(", "self", ",", "layout", ")", ":", "layout", ".", "prop", "(", "self", ",", "\"pivotSource\"", ",", "text", "=", "\"Local Pivots\"", ")", "if", "self", ".", "pivotSource", "==", "\"CUSTOM_MATRICES\"", "and", "\"LOCAL_AXIS\"", "not", ...
https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/mesh/offset_polygons.py#L48-L54
enthought/comtypes
8f3abc93c213fccdf9cae54aa88bfc1dfc17b8e9
comtypes/client/_code_cache.py
python
_is_writeable
(path)
return os.access(path[0], os.W_OK)
Check if the first part, if any, on path is a directory in which we can create files.
Check if the first part, if any, on path is a directory in which we can create files.
[ "Check", "if", "the", "first", "part", "if", "any", "on", "path", "is", "a", "directory", "in", "which", "we", "can", "create", "files", "." ]
def _is_writeable(path): """Check if the first part, if any, on path is a directory in which we can create files.""" if not path: return False # TODO: should we add os.X_OK flag as well? It seems unnecessary on Windows. return os.access(path[0], os.W_OK)
[ "def", "_is_writeable", "(", "path", ")", ":", "if", "not", "path", ":", "return", "False", "# TODO: should we add os.X_OK flag as well? It seems unnecessary on Windows.", "return", "os", ".", "access", "(", "path", "[", "0", "]", ",", "os", ".", "W_OK", ")" ]
https://github.com/enthought/comtypes/blob/8f3abc93c213fccdf9cae54aa88bfc1dfc17b8e9/comtypes/client/_code_cache.py#L114-L120
abhik/pebl
5e7d694eb1e4f90e0f1410000b958ba62698a268
src/pebl/result.py
python
LearnerResult.tofile
(self, filename=None)
Save the result to a python pickle file. The result can be later read using the result.fromfile function.
Save the result to a python pickle file.
[ "Save", "the", "result", "to", "a", "python", "pickle", "file", "." ]
def tofile(self, filename=None): """Save the result to a python pickle file. The result can be later read using the result.fromfile function. """ filename = filename or config.get('result.filename') with open(filename, 'w') as fp: cPickle.dump(self, fp)
[ "def", "tofile", "(", "self", ",", "filename", "=", "None", ")", ":", "filename", "=", "filename", "or", "config", ".", "get", "(", "'result.filename'", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fp", ":", "cPickle", ".", "dump", "...
https://github.com/abhik/pebl/blob/5e7d694eb1e4f90e0f1410000b958ba62698a268/src/pebl/result.py#L131-L139
msr-fiddle/pipedream
7db6a1c3e64996d5b319faec6ca38cb31bfea1c4
profiler/translation/seq2seq/inference/beam_search.py
python
SequenceGenerator.__init__
(self, model, beam_size=5, max_seq_len=100, cuda=False, len_norm_factor=0.6, len_norm_const=5, cov_penalty_factor=0.1)
Constructor for the SequenceGenerator. Beam search decoding supports coverage penalty and length normalization. For details, refer to Section 7 of the GNMT paper (https://arxiv.org/pdf/1609.08144.pdf). :param model: model which implements generate method :param beam_size: decoder beam size :param max_seq_len: maximum decoder sequence length :param cuda: whether to use cuda :param len_norm_factor: length normalization factor :param len_norm_const: length normalization constant :param cov_penalty_factor: coverage penalty factor
Constructor for the SequenceGenerator.
[ "Constructor", "for", "the", "SequenceGenerator", "." ]
def __init__(self, model, beam_size=5, max_seq_len=100, cuda=False, len_norm_factor=0.6, len_norm_const=5, cov_penalty_factor=0.1): """ Constructor for the SequenceGenerator. Beam search decoding supports coverage penalty and length normalization. For details, refer to Section 7 of the GNMT paper (https://arxiv.org/pdf/1609.08144.pdf). :param model: model which implements generate method :param beam_size: decoder beam size :param max_seq_len: maximum decoder sequence length :param cuda: whether to use cuda :param len_norm_factor: length normalization factor :param len_norm_const: length normalization constant :param cov_penalty_factor: coverage penalty factor """ self.model = model self.cuda = cuda self.beam_size = beam_size self.max_seq_len = max_seq_len self.len_norm_factor = len_norm_factor self.len_norm_const = len_norm_const self.cov_penalty_factor = cov_penalty_factor self.batch_first = self.model.batch_first gnmt_print(key=mlperf_log.EVAL_HP_BEAM_SIZE, value=self.beam_size) gnmt_print(key=mlperf_log.EVAL_HP_MAX_SEQ_LEN, value=self.max_seq_len) gnmt_print(key=mlperf_log.EVAL_HP_LEN_NORM_CONST, value=self.len_norm_const) gnmt_print(key=mlperf_log.EVAL_HP_LEN_NORM_FACTOR, value=self.len_norm_factor) gnmt_print(key=mlperf_log.EVAL_HP_COV_PENALTY_FACTOR, value=self.cov_penalty_factor)
[ "def", "__init__", "(", "self", ",", "model", ",", "beam_size", "=", "5", ",", "max_seq_len", "=", "100", ",", "cuda", "=", "False", ",", "len_norm_factor", "=", "0.6", ",", "len_norm_const", "=", "5", ",", "cov_penalty_factor", "=", "0.1", ")", ":", "...
https://github.com/msr-fiddle/pipedream/blob/7db6a1c3e64996d5b319faec6ca38cb31bfea1c4/profiler/translation/seq2seq/inference/beam_search.py#L16-L54
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/beetsplug/bpd/gstplayer.py
python
GstPlayer._get_state
(self)
return self.player.get_state(Gst.CLOCK_TIME_NONE)[1]
Returns the current state flag of the playbin.
Returns the current state flag of the playbin.
[ "Returns", "the", "current", "state", "flag", "of", "the", "playbin", "." ]
def _get_state(self): """Returns the current state flag of the playbin.""" # gst's get_state function returns a 3-tuple; we just want the # status flag in position 1. return self.player.get_state(Gst.CLOCK_TIME_NONE)[1]
[ "def", "_get_state", "(", "self", ")", ":", "# gst's get_state function returns a 3-tuple; we just want the", "# status flag in position 1.", "return", "self", ".", "player", ".", "get_state", "(", "Gst", ".", "CLOCK_TIME_NONE", ")", "[", "1", "]" ]
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/beetsplug/bpd/gstplayer.py#L92-L96
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/concurrent/futures/_base.py
python
Future.result
(self, timeout=None)
Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. Returns: The result of the call that the future represents. Raises: CancelledError: If the future was cancelled. TimeoutError: If the future didn't finish executing before the given timeout. Exception: If the call raised then that exception will be raised.
Return the result of the call that the future represents.
[ "Return", "the", "result", "of", "the", "call", "that", "the", "future", "represents", "." ]
def result(self, timeout=None): """Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. Returns: The result of the call that the future represents. Raises: CancelledError: If the future was cancelled. TimeoutError: If the future didn't finish executing before the given timeout. Exception: If the call raised then that exception will be raised. """ with self._condition: if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self.__get_result() self._condition.wait(timeout) if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self.__get_result() else: raise TimeoutError()
[ "def", "result", "(", "self", ",", "timeout", "=", "None", ")", ":", "with", "self", ".", "_condition", ":", "if", "self", ".", "_state", "in", "[", "CANCELLED", ",", "CANCELLED_AND_NOTIFIED", "]", ":", "raise", "CancelledError", "(", ")", "elif", "self"...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/concurrent/futures/_base.py#L380-L409
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/matching/wrappers.py
python
InverseMatcher.is_active
(self)
return self._id < self.limit
[]
def is_active(self): return self._id < self.limit
[ "def", "is_active", "(", "self", ")", ":", "return", "self", ".", "_id", "<", "self", ".", "limit" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/matching/wrappers.py#L355-L356
qutip/qutip
52d01da181a21b810c3407812c670f35fdc647e8
qutip/visualization.py
python
matrix_histogram_complex
(M, xlabels=None, ylabels=None, title=None, limits=None, phase_limits=None, colorbar=True, fig=None, ax=None, threshold=None)
return fig, ax
Draw a histogram for the amplitudes of matrix M, using the argument of each element for coloring the bars, with the given x and y labels and title. Parameters ---------- M : Matrix of Qobj The matrix to visualize xlabels : list of strings list of x labels ylabels : list of strings list of y labels title : string title of the plot (optional) limits : list/array with two float numbers The z-axis limits [min, max] (optional) phase_limits : list/array with two float numbers The phase-axis (colorbar) limits [min, max] (optional) ax : a matplotlib axes instance The axes context in which the plot will be drawn. threshold: float (None) Threshold for when bars of smaller height should be transparent. If not set, all bars are colored according to the color map. Returns ------- fig, ax : tuple A tuple of the matplotlib figure and axes instances used to produce the figure. Raises ------ ValueError Input argument is not valid.
Draw a histogram for the amplitudes of matrix M, using the argument of each element for coloring the bars, with the given x and y labels and title.
[ "Draw", "a", "histogram", "for", "the", "amplitudes", "of", "matrix", "M", "using", "the", "argument", "of", "each", "element", "for", "coloring", "the", "bars", "with", "the", "given", "x", "and", "y", "labels", "and", "title", "." ]
def matrix_histogram_complex(M, xlabels=None, ylabels=None, title=None, limits=None, phase_limits=None, colorbar=True, fig=None, ax=None, threshold=None): """ Draw a histogram for the amplitudes of matrix M, using the argument of each element for coloring the bars, with the given x and y labels and title. Parameters ---------- M : Matrix of Qobj The matrix to visualize xlabels : list of strings list of x labels ylabels : list of strings list of y labels title : string title of the plot (optional) limits : list/array with two float numbers The z-axis limits [min, max] (optional) phase_limits : list/array with two float numbers The phase-axis (colorbar) limits [min, max] (optional) ax : a matplotlib axes instance The axes context in which the plot will be drawn. threshold: float (None) Threshold for when bars of smaller height should be transparent. If not set, all bars are colored according to the color map. Returns ------- fig, ax : tuple A tuple of the matplotlib figure and axes instances used to produce the figure. Raises ------ ValueError Input argument is not valid. """ if isinstance(M, Qobj): # extract matrix data from Qobj M = M.full() n = np.size(M) xpos, ypos = np.meshgrid(range(M.shape[0]), range(M.shape[1])) xpos = xpos.T.flatten() - 0.5 ypos = ypos.T.flatten() - 0.5 zpos = np.zeros(n) dx = dy = 0.8 * np.ones(n) Mvec = M.flatten() dz = abs(Mvec) # make small numbers real, to avoid random colors idx, = np.where(abs(Mvec) < 0.001) Mvec[idx] = abs(Mvec[idx]) if phase_limits: # check that limits is a list type phase_min = phase_limits[0] phase_max = phase_limits[1] else: phase_min = -pi phase_max = pi norm = mpl.colors.Normalize(phase_min, phase_max) cmap = complex_phase_cmap() colors = cmap(norm(angle(Mvec))) if threshold is not None: colors[:, 3] = 1 * (dz > threshold) if ax is None: fig = plt.figure() ax = _axes3D(fig, azim=-35, elev=35) ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors) if title and fig: ax.set_title(title) # x axis xtics = -0.5 + np.arange(M.shape[0]) ax.axes.w_xaxis.set_major_locator(plt.FixedLocator(xtics)) if xlabels: nxlabels = len(xlabels) if nxlabels != len(xtics): raise ValueError(f"got {nxlabels} xlabels but needed {len(xtics)}") ax.set_xticklabels(xlabels) ax.tick_params(axis='x', labelsize=12) # y axis ytics = -0.5 + np.arange(M.shape[1]) ax.axes.w_yaxis.set_major_locator(plt.FixedLocator(ytics)) if ylabels: nylabels = len(ylabels) if nylabels != len(ytics): raise ValueError(f"got {nylabels} ylabels but needed {len(ytics)}") ax.set_yticklabels(ylabels) ax.tick_params(axis='y', labelsize=12) # z axis if limits and isinstance(limits, list): ax.set_zlim3d(limits) else: ax.set_zlim3d([0, 1]) # use min/max # ax.set_zlabel('abs') # color axis if colorbar: cax, kw = mpl.colorbar.make_axes(ax, shrink=.75, pad=.0) cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm) cb.set_ticks([-pi, -pi / 2, 0, pi / 2, pi]) cb.set_ticklabels( (r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$')) cb.set_label('arg') return fig, ax
[ "def", "matrix_histogram_complex", "(", "M", ",", "xlabels", "=", "None", ",", "ylabels", "=", "None", ",", "title", "=", "None", ",", "limits", "=", "None", ",", "phase_limits", "=", "None", ",", "colorbar", "=", "True", ",", "fig", "=", "None", ",", ...
https://github.com/qutip/qutip/blob/52d01da181a21b810c3407812c670f35fdc647e8/qutip/visualization.py#L728-L853
snipsco/ntm-lasagne
65c950b01f52afb87cf3dccc963d8bbc5b1dbf69
utils/generators.py
python
DyckWordsTask.get_random_non_dyck
(self, n)
return w
Return a random balanced non-Dyck word of semilength `n` The algorithm is based on the bijection between words in the language `L = S(u^{n-1} d^{n+1})` and the balanced words of length 2n that are not Dyck words. This transformation is given by the reflection of the letters after the first letter that violates the Dyck property (i.e. the first right parenthesis that does not have a matching left counterpart). The reflexion transformation is defined by transforming any left parenthesis in a right one and vice-versa. To summarize, here is the pseudo-code for this algorithm: - Pick a random word `w` in the language `L = S(u^{n-1} d^{n+1})` - Find the first letter violating the Dyck property - Apply the reflection transformation to the following letters
Return a random balanced non-Dyck word of semilength `n`
[ "Return", "a", "random", "balanced", "non", "-", "Dyck", "word", "of", "semilength", "n" ]
def get_random_non_dyck(self, n): """ Return a random balanced non-Dyck word of semilength `n` The algorithm is based on the bijection between words in the language `L = S(u^{n-1} d^{n+1})` and the balanced words of length 2n that are not Dyck words. This transformation is given by the reflection of the letters after the first letter that violates the Dyck property (i.e. the first right parenthesis that does not have a matching left counterpart). The reflexion transformation is defined by transforming any left parenthesis in a right one and vice-versa. To summarize, here is the pseudo-code for this algorithm: - Pick a random word `w` in the language `L = S(u^{n-1} d^{n+1})` - Find the first letter violating the Dyck property - Apply the reflection transformation to the following letters """ w = [0] * (n - 1) + [1] * (n + 1) np.random.shuffle(w) stack, reflection = (0, False) for i in range(2 * n): if reflection: w[i] = 1 * (not w[i]) else: if w[i]: stack -= 1 else: stack += 1 reflection = (stack < 0) return w
[ "def", "get_random_non_dyck", "(", "self", ",", "n", ")", ":", "w", "=", "[", "0", "]", "*", "(", "n", "-", "1", ")", "+", "[", "1", "]", "*", "(", "n", "+", "1", ")", "np", ".", "random", ".", "shuffle", "(", "w", ")", "stack", ",", "ref...
https://github.com/snipsco/ntm-lasagne/blob/65c950b01f52afb87cf3dccc963d8bbc5b1dbf69/utils/generators.py#L278-L307
tensorflow/graphics
86997957324bfbdd85848daae989b4c02588faa0
tensorflow_graphics/util/asserts.py
python
assert_at_least_k_non_zero_entries
( tensor: type_alias.TensorLike, k: int = 1, name: str = 'assert_at_least_k_non_zero_entries')
Checks if `tensor` has at least k non-zero entries in the last dimension. Given a tensor with `M` dimensions in its last axis, this function checks whether at least `k` out of `M` dimensions are non-zero. Note: In the following, A1 to An are optional batch dimensions. Args: tensor: A tensor of shape `[A1, ..., An, M]`. k: An integer, corresponding to the minimum number of non-zero entries. name: A name for this op. Defaults to 'assert_at_least_k_non_zero_entries'. Raises: InvalidArgumentError: If `tensor` has less than `k` non-zero entries in its last axis. Returns: The input tensor, with dependence on the assertion operator in the graph.
Checks if `tensor` has at least k non-zero entries in the last dimension.
[ "Checks", "if", "tensor", "has", "at", "least", "k", "non", "-", "zero", "entries", "in", "the", "last", "dimension", "." ]
def assert_at_least_k_non_zero_entries( tensor: type_alias.TensorLike, k: int = 1, name: str = 'assert_at_least_k_non_zero_entries') -> tf.Tensor: """Checks if `tensor` has at least k non-zero entries in the last dimension. Given a tensor with `M` dimensions in its last axis, this function checks whether at least `k` out of `M` dimensions are non-zero. Note: In the following, A1 to An are optional batch dimensions. Args: tensor: A tensor of shape `[A1, ..., An, M]`. k: An integer, corresponding to the minimum number of non-zero entries. name: A name for this op. Defaults to 'assert_at_least_k_non_zero_entries'. Raises: InvalidArgumentError: If `tensor` has less than `k` non-zero entries in its last axis. Returns: The input tensor, with dependence on the assertion operator in the graph. """ if not FLAGS[tfg_flags.TFG_ADD_ASSERTS_TO_GRAPH].value: return tensor with tf.name_scope(name): tensor = tf.convert_to_tensor(value=tensor) indicator = tf.cast(tf.math.greater(tensor, 0.0), dtype=tensor.dtype) indicator_sum = tf.reduce_sum(input_tensor=indicator, axis=-1) assert_op = tf.debugging.assert_greater_equal( indicator_sum, tf.cast(k, dtype=tensor.dtype)) with tf.control_dependencies([assert_op]): return tf.identity(tensor)
[ "def", "assert_at_least_k_non_zero_entries", "(", "tensor", ":", "type_alias", ".", "TensorLike", ",", "k", ":", "int", "=", "1", ",", "name", ":", "str", "=", "'assert_at_least_k_non_zero_entries'", ")", "->", "tf", ".", "Tensor", ":", "if", "not", "FLAGS", ...
https://github.com/tensorflow/graphics/blob/86997957324bfbdd85848daae989b4c02588faa0/tensorflow_graphics/util/asserts.py#L274-L309
beurtschipper/crackcoin
73ae99b8f6957f1df3f4549074beaf616e4588d7
crackcoin/networks.py
python
crackcoinNetwork.handleServerInput
(self, data, ip)
Handle crackcoin packets
Handle crackcoin packets
[ "Handle", "crackcoin", "packets" ]
def handleServerInput(self, data, ip): ''' Handle crackcoin packets ''' # reply to broadcast packets if hasPacketPrefix(data, packet_sync_request): # todo: do proper sync, not send everything transactions = crackcoin.db.doQuery("SELECT hash from transactions WHERE hash != 'd34db33f'", result='all') # everything except genesis transaction for transaction in transactions: transactionHash = transaction[0] # send transaction transactionJSON = crackcoin.transactions.getJSONForTransaction(transactionHash) crackcoin.network.sendToNode(ip, packet_payment_new + zlib.compress(transactionJSON) ) # send current confirmation difficulty,addition = crackcoin.db.doQuery("select difficulty,addition from confirmations where transactionHash = ?", (transactionHash,), result='one') data = "%s,%s,%s" % (transactionHash,str(difficulty),addition) crackcoin.network.sendToNode(ip, packet_payment_confirmation + data) if hasPacketPrefix(data, packet_payment_new): crackcoin.transactions.addTransactionJSON( zlib.decompress(data[len(packet_payment_new):]) ) if hasPacketPrefix(data, packet_payment_confirmation): crackcoin.transactions.addConfirmationCSV(data[len(packet_payment_confirmation):])
[ "def", "handleServerInput", "(", "self", ",", "data", ",", "ip", ")", ":", "# reply to broadcast packets", "if", "hasPacketPrefix", "(", "data", ",", "packet_sync_request", ")", ":", "# todo: do proper sync, not send everything", "transactions", "=", "crackcoin", ".", ...
https://github.com/beurtschipper/crackcoin/blob/73ae99b8f6957f1df3f4549074beaf616e4588d7/crackcoin/networks.py#L51-L76
lazylibrarian/LazyLibrarian
ae3c14e9db9328ce81765e094ab2a14ed7155624
cherrypy/lib/sessions.py
python
Session.save
(self)
Save session data.
Save session data.
[ "Save", "session", "data", "." ]
def save(self): """Save session data.""" try: # If session data has never been loaded then it's never been # accessed: no need to save it if self.loaded: t = datetime.timedelta(seconds=self.timeout * 60) expiration_time = self.now() + t if self.debug: cherrypy.log('Saving session %r with expiry %s' % (self.id, expiration_time), 'TOOLS.SESSIONS') self._save(expiration_time) else: if self.debug: cherrypy.log( 'Skipping save of session %r (no session loaded).' % self.id, 'TOOLS.SESSIONS') finally: if self.locked: # Always release the lock if the user didn't release it self.release_lock() if self.debug: cherrypy.log('Lock released after save.', 'TOOLS.SESSIONS')
[ "def", "save", "(", "self", ")", ":", "try", ":", "# If session data has never been loaded then it's never been", "# accessed: no need to save it", "if", "self", ".", "loaded", ":", "t", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "self", ".", "timeout...
https://github.com/lazylibrarian/LazyLibrarian/blob/ae3c14e9db9328ce81765e094ab2a14ed7155624/cherrypy/lib/sessions.py#L241-L264
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/netatmo/sensor.py
python
NetatmoSensor.async_update_callback
(self)
Update the entity's state.
Update the entity's state.
[ "Update", "the", "entity", "s", "state", "." ]
def async_update_callback(self) -> None: """Update the entity's state.""" data = self._data.get_last_data(station_id=self._station_id, exclude=3600).get( self._id ) if data is None: if self.state: _LOGGER.debug( "No data found for %s - %s (%s)", self.name, self._device_name, self._id, ) self._attr_native_value = None return try: state = data[self.entity_description.netatmo_name] if self.entity_description.key in {"temperature", "pressure", "sum_rain_1"}: self._attr_native_value = round(state, 1) elif self.entity_description.key in {"windangle_value", "gustangle_value"}: self._attr_native_value = fix_angle(state) elif self.entity_description.key in {"windangle", "gustangle"}: self._attr_native_value = process_angle(fix_angle(state)) elif self.entity_description.key == "rf_status": self._attr_native_value = process_rf(state) elif self.entity_description.key == "wifi_status": self._attr_native_value = process_wifi(state) elif self.entity_description.key == "health_idx": self._attr_native_value = process_health(state) else: self._attr_native_value = state except KeyError: if self.state: _LOGGER.debug( "No %s data found for %s", self.entity_description.key, self._device_name, ) self._attr_native_value = None return self.async_write_ha_state()
[ "def", "async_update_callback", "(", "self", ")", "->", "None", ":", "data", "=", "self", ".", "_data", ".", "get_last_data", "(", "station_id", "=", "self", ".", "_station_id", ",", "exclude", "=", "3600", ")", ".", "get", "(", "self", ".", "_id", ")"...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/netatmo/sensor.py#L530-L573
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/SearchKippt/kippt/requests/cookies.py
python
RequestsCookieJar.copy
(self)
return new_cj
Return a copy of this RequestsCookieJar.
Return a copy of this RequestsCookieJar.
[ "Return", "a", "copy", "of", "this", "RequestsCookieJar", "." ]
def copy(self): """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.update(self) return new_cj
[ "def", "copy", "(", "self", ")", ":", "new_cj", "=", "RequestsCookieJar", "(", ")", "new_cj", ".", "update", "(", "self", ")", "return", "new_cj" ]
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/SearchKippt/kippt/requests/cookies.py#L326-L330
google-research/language
61fa7260ac7d690d11ef72ca863e45a37c0bdc80
language/nql/nql/util.py
python
ModelBuilder.build_estimator
(self, model_dir=None, params=None)
return tf.estimator.Estimator( model_fn=self.build_model_fn(), model_dir=model_dir, params=params)
Produce an Estimator for this Model. Args: model_dir: passed in to Estimator - location of tmp files used by Estimator to checkpoint models params: passed in to estimator - dict of model_fn parameters Returns: a tf.estimator.Estimator
Produce an Estimator for this Model.
[ "Produce", "an", "Estimator", "for", "this", "Model", "." ]
def build_estimator(self, model_dir=None, params=None): """Produce an Estimator for this Model. Args: model_dir: passed in to Estimator - location of tmp files used by Estimator to checkpoint models params: passed in to estimator - dict of model_fn parameters Returns: a tf.estimator.Estimator """ return tf.estimator.Estimator( model_fn=self.build_model_fn(), model_dir=model_dir, params=params)
[ "def", "build_estimator", "(", "self", ",", "model_dir", "=", "None", ",", "params", "=", "None", ")", ":", "return", "tf", ".", "estimator", ".", "Estimator", "(", "model_fn", "=", "self", ".", "build_model_fn", "(", ")", ",", "model_dir", "=", "model_d...
https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/nql/nql/util.py#L218-L230
napari/napari
dbf4158e801fa7a429de8ef1cdee73bf6d64c61e
napari/utils/colormaps/vendored/cm.py
python
revcmap
(data)
return data_r
Can only handle specification *data* in dictionary format.
Can only handle specification *data* in dictionary format.
[ "Can", "only", "handle", "specification", "*", "data", "*", "in", "dictionary", "format", "." ]
def revcmap(data): """Can only handle specification *data* in dictionary format.""" data_r = {} for key, val in data.items(): if callable(val): valnew = _reverser(val) # This doesn't work: lambda x: val(1-x) # The same "val" (the first one) is used # each time, so the colors are identical # and the result is shades of gray. else: # Flip x and exchange the y values facing x = 0 and x = 1. valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)] data_r[key] = valnew return data_r
[ "def", "revcmap", "(", "data", ")", ":", "data_r", "=", "{", "}", "for", "key", ",", "val", "in", "data", ".", "items", "(", ")", ":", "if", "callable", "(", "val", ")", ":", "valnew", "=", "_reverser", "(", "val", ")", "# This doesn't work: lambda x...
https://github.com/napari/napari/blob/dbf4158e801fa7a429de8ef1cdee73bf6d64c61e/napari/utils/colormaps/vendored/cm.py#L46-L60
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/manifolds/local_frame.py
python
LocalCoFrame.at
(self, point)
return self._basis.at(point).dual_basis()
r""" Return the value of ``self`` at a given point on the base space, this value being a basis of the dual vector bundle at this point. INPUT: - ``point`` -- :class:`~sage.manifolds.point.ManifoldPoint`; point `p` in the domain `U` of the coframe (denoted `f` hereafter) OUTPUT: - :class:`~sage.tensor.modules.free_module_basis.FreeModuleCoBasis` representing the basis `f(p)` of the vector space `E^*_p`, dual to the vector bundle fiber `E_p` EXAMPLES: Cobasis of a vector bundle fiber:: sage: M = Manifold(2, 'M', structure='top', start_index=1) sage: X.<x,y> = M.chart() sage: E = M.vector_bundle(2, 'E') sage: e = E.local_frame('e') sage: e_dual = e.coframe(); e_dual Local coframe (E|_M, (e^1,e^2)) sage: p = M.point((-1,2), name='p') sage: e_dual_p = e_dual.at(p) ; e_dual_p Dual basis (e^1,e^2) on the Fiber of E at Point p on the 2-dimensional topological manifold M sage: type(e_dual_p) <class 'sage.tensor.modules.free_module_basis.FreeModuleCoBasis'> sage: e_dual_p[1] Linear form e^1 on the Fiber of E at Point p on the 2-dimensional topological manifold M sage: e_dual_p[2] Linear form e^2 on the Fiber of E at Point p on the 2-dimensional topological manifold M sage: e_dual_p is e.at(p).dual_basis() True
r""" Return the value of ``self`` at a given point on the base space, this value being a basis of the dual vector bundle at this point.
[ "r", "Return", "the", "value", "of", "self", "at", "a", "given", "point", "on", "the", "base", "space", "this", "value", "being", "a", "basis", "of", "the", "dual", "vector", "bundle", "at", "this", "point", "." ]
def at(self, point): r""" Return the value of ``self`` at a given point on the base space, this value being a basis of the dual vector bundle at this point. INPUT: - ``point`` -- :class:`~sage.manifolds.point.ManifoldPoint`; point `p` in the domain `U` of the coframe (denoted `f` hereafter) OUTPUT: - :class:`~sage.tensor.modules.free_module_basis.FreeModuleCoBasis` representing the basis `f(p)` of the vector space `E^*_p`, dual to the vector bundle fiber `E_p` EXAMPLES: Cobasis of a vector bundle fiber:: sage: M = Manifold(2, 'M', structure='top', start_index=1) sage: X.<x,y> = M.chart() sage: E = M.vector_bundle(2, 'E') sage: e = E.local_frame('e') sage: e_dual = e.coframe(); e_dual Local coframe (E|_M, (e^1,e^2)) sage: p = M.point((-1,2), name='p') sage: e_dual_p = e_dual.at(p) ; e_dual_p Dual basis (e^1,e^2) on the Fiber of E at Point p on the 2-dimensional topological manifold M sage: type(e_dual_p) <class 'sage.tensor.modules.free_module_basis.FreeModuleCoBasis'> sage: e_dual_p[1] Linear form e^1 on the Fiber of E at Point p on the 2-dimensional topological manifold M sage: e_dual_p[2] Linear form e^2 on the Fiber of E at Point p on the 2-dimensional topological manifold M sage: e_dual_p is e.at(p).dual_basis() True """ return self._basis.at(point).dual_basis()
[ "def", "at", "(", "self", ",", "point", ")", ":", "return", "self", ".", "_basis", ".", "at", "(", "point", ")", ".", "dual_basis", "(", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/manifolds/local_frame.py#L303-L345
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3cfg.py
python
S3Config.get_br_case_activity_updates
(self)
return self.br.get("case_activity_updates", False)
Use case activity update journal (inline-component)
Use case activity update journal (inline-component)
[ "Use", "case", "activity", "update", "journal", "(", "inline", "-", "component", ")" ]
def get_br_case_activity_updates(self): """ Use case activity update journal (inline-component) """ return self.br.get("case_activity_updates", False)
[ "def", "get_br_case_activity_updates", "(", "self", ")", ":", "return", "self", ".", "br", ".", "get", "(", "\"case_activity_updates\"", ",", "False", ")" ]
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3cfg.py#L3164-L3168
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/html5lib/html5parser.py
python
impliedTagToken
(name, type="EndTag", attributes=None, selfClosing=False)
return {"type": tokenTypes[type], "name": name, "data": attributes, "selfClosing": selfClosing}
[]
def impliedTagToken(name, type="EndTag", attributes=None, selfClosing=False): if attributes is None: attributes = {} return {"type": tokenTypes[type], "name": name, "data": attributes, "selfClosing": selfClosing}
[ "def", "impliedTagToken", "(", "name", ",", "type", "=", "\"EndTag\"", ",", "attributes", "=", "None", ",", "selfClosing", "=", "False", ")", ":", "if", "attributes", "is", "None", ":", "attributes", "=", "{", "}", "return", "{", "\"type\"", ":", "tokenT...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/html5lib/html5parser.py#L2785-L2790
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/tqdm/tqdm/keras.py
python
TqdmCallback.display
(self)
Displays in the current cell in Notebooks.
Displays in the current cell in Notebooks.
[ "Displays", "in", "the", "current", "cell", "in", "Notebooks", "." ]
def display(self): """Displays in the current cell in Notebooks.""" container = getattr(self.epoch_bar, 'container', None) if container is None: return from .notebook import display display(container) batch_bar = getattr(self, 'batch_bar', None) if batch_bar is not None: display(batch_bar.container)
[ "def", "display", "(", "self", ")", ":", "container", "=", "getattr", "(", "self", ".", "epoch_bar", ",", "'container'", ",", "None", ")", "if", "container", "is", "None", ":", "return", "from", ".", "notebook", "import", "display", "display", "(", "cont...
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/tqdm/tqdm/keras.py#L100-L109