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
facelessuser/pymdown-extensions
7a9d548ed3aa921e77fbedd202947ba884cca04c
pymdownx/critic.py
python
CriticExtension.__init__
(self, *args, **kwargs)
Initialize.
Initialize.
[ "Initialize", "." ]
def __init__(self, *args, **kwargs): """Initialize.""" self.config = { 'mode': ['view', "Critic mode to run in ('view', 'accept', or 'reject') - Default: view "], 'raw_view': [False, "Raw view keeps the output as the raw markup for view mode - Default False"] } super(CriticExtension, self).__init__(*args, **kwargs)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "config", "=", "{", "'mode'", ":", "[", "'view'", ",", "\"Critic mode to run in ('view', 'accept', or 'reject') - Default: view \"", "]", ",", "'raw_view'", ":", ...
https://github.com/facelessuser/pymdown-extensions/blob/7a9d548ed3aa921e77fbedd202947ba884cca04c/pymdownx/critic.py#L293-L301
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_core/xmlparser.py
python
CatalogedExpatParser.external_entity_ref
(self, context, base, sysid, pubid)
return 1
Add external entity reference to XML document.
Add external entity reference to XML document.
[ "Add", "external", "entity", "reference", "to", "XML", "document", "." ]
def external_entity_ref(self, context, base, sysid, pubid): """Add external entity reference to XML document.""" if not self._external_ges: return 1 source = self._ent_handler.resolveEntity(pubid, sysid) source = saxutils.prepare_input_source(source, self._source.getSystemId() or "") # If an entry does not exist in the xml cache, create it. filepath = os.path.join(XML_CACHE, base64.urlsafe_b64encode(pubid)) if not os.path.isfile(filepath): with open(filepath, 'w') as f: contents = source.getByteStream().read() source.setByteStream(StringIO(contents)) f.write(contents) self._entity_stack.append((self._parser, self._source)) self._parser = self._parser.ExternalEntityParserCreate(context) self._source = source try: xmlreader.IncrementalParser.parse(self, source) except: return 0 # FIXME: save error info here? (self._parser, self._source) = self._entity_stack[-1] del self._entity_stack[-1] return 1
[ "def", "external_entity_ref", "(", "self", ",", "context", ",", "base", ",", "sysid", ",", "pubid", ")", ":", "if", "not", "self", ".", "_external_ges", ":", "return", "1", "source", "=", "self", ".", "_ent_handler", ".", "resolveEntity", "(", "pubid", "...
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_core/xmlparser.py#L18-L47
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/ad_group_ad_label_service/client.py
python
AdGroupAdLabelServiceClient.parse_common_project_path
(path: str)
return m.groupdict() if m else {}
Parse a project path into its component segments.
Parse a project path into its component segments.
[ "Parse", "a", "project", "path", "into", "its", "component", "segments", "." ]
def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {}
[ "def", "parse_common_project_path", "(", "path", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "m", "=", "re", ".", "match", "(", "r\"^projects/(?P<project>.+?)$\"", ",", "path", ")", "return", "m", ".", "groupdict", "(", ")", "if", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/ad_group_ad_label_service/client.py#L254-L257
mbusb/multibootusb
fa89b28f27891a9ce8d6e2a5737baa2e6ee83dfd
scripts/osdriver.py
python
Windows.listbox_entry_to_device
(self, lb_entry)
[]
def listbox_entry_to_device(self, lb_entry): left = lb_entry.split(':', 1)[0] if left.isdigit(): return int(left) # see win_physicaldrive_to_listbox_entry() else: return lb_entry
[ "def", "listbox_entry_to_device", "(", "self", ",", "lb_entry", ")", ":", "left", "=", "lb_entry", ".", "split", "(", "':'", ",", "1", ")", "[", "0", "]", "if", "left", ".", "isdigit", "(", ")", ":", "return", "int", "(", "left", ")", "# see win_phys...
https://github.com/mbusb/multibootusb/blob/fa89b28f27891a9ce8d6e2a5737baa2e6ee83dfd/scripts/osdriver.py#L337-L342
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_histogram.py
python
Histogram.cumulative
(self)
return self["cumulative"]
The 'cumulative' property is an instance of Cumulative that may be specified as: - An instance of :class:`plotly.graph_objs.histogram.Cumulative` - A dict of string/value properties that will be passed to the Cumulative constructor Supported dict properties: currentbin Only applies if cumulative is enabled. Sets whether the current bin is included, excluded, or has half of its value included in the current cumulative value. "include" is the default for compatibility with various other tools, however it introduces a half-bin bias to the results. "exclude" makes the opposite half- bin bias, and "half" removes it. direction Only applies if cumulative is enabled. If "increasing" (default) we sum all prior bins, so the result increases from left to right. If "decreasing" we sum later bins so the result decreases from left to right. enabled If true, display the cumulative distribution by summing the binned values. Use the `direction` and `centralbin` attributes to tune the accumulation method. Note: in this mode, the "density" `histnorm` settings behave the same as their equivalents without "density": "" and "density" both rise to the number of data points, and "probability" and *probability density* both rise to the number of sample points. Returns ------- plotly.graph_objs.histogram.Cumulative
The 'cumulative' property is an instance of Cumulative that may be specified as: - An instance of :class:`plotly.graph_objs.histogram.Cumulative` - A dict of string/value properties that will be passed to the Cumulative constructor Supported dict properties: currentbin Only applies if cumulative is enabled. Sets whether the current bin is included, excluded, or has half of its value included in the current cumulative value. "include" is the default for compatibility with various other tools, however it introduces a half-bin bias to the results. "exclude" makes the opposite half- bin bias, and "half" removes it. direction Only applies if cumulative is enabled. If "increasing" (default) we sum all prior bins, so the result increases from left to right. If "decreasing" we sum later bins so the result decreases from left to right. enabled If true, display the cumulative distribution by summing the binned values. Use the `direction` and `centralbin` attributes to tune the accumulation method. Note: in this mode, the "density" `histnorm` settings behave the same as their equivalents without "density": "" and "density" both rise to the number of data points, and "probability" and *probability density* both rise to the number of sample points.
[ "The", "cumulative", "property", "is", "an", "instance", "of", "Cumulative", "that", "may", "be", "specified", "as", ":", "-", "An", "instance", "of", ":", "class", ":", "plotly", ".", "graph_objs", ".", "histogram", ".", "Cumulative", "-", "A", "dict", ...
def cumulative(self): """ The 'cumulative' property is an instance of Cumulative that may be specified as: - An instance of :class:`plotly.graph_objs.histogram.Cumulative` - A dict of string/value properties that will be passed to the Cumulative constructor Supported dict properties: currentbin Only applies if cumulative is enabled. Sets whether the current bin is included, excluded, or has half of its value included in the current cumulative value. "include" is the default for compatibility with various other tools, however it introduces a half-bin bias to the results. "exclude" makes the opposite half- bin bias, and "half" removes it. direction Only applies if cumulative is enabled. If "increasing" (default) we sum all prior bins, so the result increases from left to right. If "decreasing" we sum later bins so the result decreases from left to right. enabled If true, display the cumulative distribution by summing the binned values. Use the `direction` and `centralbin` attributes to tune the accumulation method. Note: in this mode, the "density" `histnorm` settings behave the same as their equivalents without "density": "" and "density" both rise to the number of data points, and "probability" and *probability density* both rise to the number of sample points. Returns ------- plotly.graph_objs.histogram.Cumulative """ return self["cumulative"]
[ "def", "cumulative", "(", "self", ")", ":", "return", "self", "[", "\"cumulative\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_histogram.py#L222-L263
internetarchive/openlibrary
33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8
openlibrary/plugins/upstream/utils.py
python
list_recent_pages
(path, limit=100, offset=0)
return web.ctx.site.get_many(web.ctx.site.things(q))
Lists all pages with name path/* in the order of last_modified.
Lists all pages with name path/* in the order of last_modified.
[ "Lists", "all", "pages", "with", "name", "path", "/", "*", "in", "the", "order", "of", "last_modified", "." ]
def list_recent_pages(path, limit=100, offset=0): """Lists all pages with name path/* in the order of last_modified.""" q = {} q['key~'] = path + '/*' # don't show /type/delete and /type/redirect q['a:type!='] = '/type/delete' q['b:type!='] = '/type/redirect' q['sort'] = 'key' q['limit'] = limit q['offset'] = offset q['sort'] = '-last_modified' # queries are very slow with != conditions # q['type'] != '/type/delete' return web.ctx.site.get_many(web.ctx.site.things(q))
[ "def", "list_recent_pages", "(", "path", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "q", "=", "{", "}", "q", "[", "'key~'", "]", "=", "path", "+", "'/*'", "# don't show /type/delete and /type/redirect", "q", "[", "'a:type!='", "]", "=",...
https://github.com/internetarchive/openlibrary/blob/33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8/openlibrary/plugins/upstream/utils.py#L195-L210
davidbau/ganseeing
93cea2c8f391aef001ddf9dcb35c43990681a47c
seeing/proggan_ablation.py
python
Generator32.forward
(self, x)
return x
[]
def forward(self, x): x = self.features(x) x = self.output(x) return x
[ "def", "forward", "(", "self", ",", "x", ")", ":", "x", "=", "self", ".", "features", "(", "x", ")", "x", "=", "self", ".", "output", "(", "x", ")", "return", "x" ]
https://github.com/davidbau/ganseeing/blob/93cea2c8f391aef001ddf9dcb35c43990681a47c/seeing/proggan_ablation.py#L334-L337
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Shared/requests/hooks.py
python
dispatch_hook
(key, hooks, hook_data, **kwargs)
return hook_data
Dispatches a hook dictionary on a given piece of data.
Dispatches a hook dictionary on a given piece of data.
[ "Dispatches", "a", "hook", "dictionary", "on", "a", "given", "piece", "of", "data", "." ]
def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or dict() hooks = hooks.get(key) if hooks: if hasattr(hooks, '__call__'): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
[ "def", "dispatch_hook", "(", "key", ",", "hooks", ",", "hook_data", ",", "*", "*", "kwargs", ")", ":", "hooks", "=", "hooks", "or", "dict", "(", ")", "hooks", "=", "hooks", ".", "get", "(", "key", ")", "if", "hooks", ":", "if", "hasattr", "(", "h...
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Shared/requests/hooks.py#L23-L34
algorhythms/LintCode
2520762a1cfbd486081583136396a2b2cac6e4fb
Binary Representation.py
python
Solution.natural_num_to_bin
(n)
return "".join(map(str, reversed(sb)))
:type n: int :param n: :return: string representation
[]
def natural_num_to_bin(n): """ :type n: int :param n: :return: string representation """ sb = [] # string buffer while n > 0: sb.append(n&1) n >>= 1 return "".join(map(str, reversed(sb)))
[ "def", "natural_num_to_bin", "(", "n", ")", ":", "sb", "=", "[", "]", "# string buffer", "while", "n", ">", "0", ":", "sb", ".", "append", "(", "n", "&", "1", ")", "n", ">>=", "1", "return", "\"\"", ".", "join", "(", "map", "(", "str", ",", "re...
https://github.com/algorhythms/LintCode/blob/2520762a1cfbd486081583136396a2b2cac6e4fb/Binary Representation.py#L52-L64
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/enum.py
python
_is_descriptor
(obj)
return ( hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__'))
Returns True if obj is a descriptor, False otherwise.
Returns True if obj is a descriptor, False otherwise.
[ "Returns", "True", "if", "obj", "is", "a", "descriptor", "False", "otherwise", "." ]
def _is_descriptor(obj): """Returns True if obj is a descriptor, False otherwise.""" return ( hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__'))
[ "def", "_is_descriptor", "(", "obj", ")", ":", "return", "(", "hasattr", "(", "obj", ",", "'__get__'", ")", "or", "hasattr", "(", "obj", ",", "'__set__'", ")", "or", "hasattr", "(", "obj", ",", "'__delete__'", ")", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/enum.py#L18-L23
altair-viz/altair
fb9e82eb378f68bad7a10c639f95e9a3991ac18d
tools/schemapi/decorator.py
python
schemaclass
(*args, init_func=True, docstring=True, property_map=True)
A decorator to add boilerplate to a schema class This will read the _json_schema attribute of a SchemaBase class, and add one or all of three attributes/methods, based on the schema: - An __init__ function - a __doc__ docstring In all cases, if the attribute/method is explicitly defined in the class it will not be overwritten. A simple invocation adds all three attributes/methods: @schemaclass class MySchema(SchemaBase): __schema = {...} Optionally, you can invoke schemaclass with arguments to turn off some of the added behaviors: @schemaclass(init_func=True, docstring=False) class MySchema(SchemaBase): __schema = {...}
A decorator to add boilerplate to a schema class
[ "A", "decorator", "to", "add", "boilerplate", "to", "a", "schema", "class" ]
def schemaclass(*args, init_func=True, docstring=True, property_map=True): """A decorator to add boilerplate to a schema class This will read the _json_schema attribute of a SchemaBase class, and add one or all of three attributes/methods, based on the schema: - An __init__ function - a __doc__ docstring In all cases, if the attribute/method is explicitly defined in the class it will not be overwritten. A simple invocation adds all three attributes/methods: @schemaclass class MySchema(SchemaBase): __schema = {...} Optionally, you can invoke schemaclass with arguments to turn off some of the added behaviors: @schemaclass(init_func=True, docstring=False) class MySchema(SchemaBase): __schema = {...} """ def _decorator(cls, init_func=init_func, docstring=docstring): if not (isinstance(cls, type) and issubclass(cls, SchemaBase)): warnings.warn("class is not an instance of SchemaBase.") name = cls.__name__ gen = codegen.SchemaGenerator( name, schema=cls._schema, rootschema=cls._rootschema ) if init_func and "__init__" not in cls.__dict__: init_code = gen.init_code() globals_ = {name: cls, "Undefined": Undefined} locals_ = {} exec(init_code, globals_, locals_) setattr(cls, "__init__", locals_["__init__"]) if docstring and not cls.__doc__: setattr(cls, "__doc__", gen.docstring()) return cls if len(args) == 0: return _decorator elif len(args) == 1: return _decorator(args[0]) else: raise ValueError( "optional arguments to schemaclass must be " "passed by keyword" )
[ "def", "schemaclass", "(", "*", "args", ",", "init_func", "=", "True", ",", "docstring", "=", "True", ",", "property_map", "=", "True", ")", ":", "def", "_decorator", "(", "cls", ",", "init_func", "=", "init_func", ",", "docstring", "=", "docstring", ")"...
https://github.com/altair-viz/altair/blob/fb9e82eb378f68bad7a10c639f95e9a3991ac18d/tools/schemapi/decorator.py#L5-L58
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/html5lib/_utils.py
python
MethodDispatcher.__getitem__
(self, key)
return dict.get(self, key, self.default)
[]
def __getitem__(self, key): return dict.get(self, key, self.default)
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "return", "dict", ".", "get", "(", "self", ",", "key", ",", "self", ".", "default", ")" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/html5lib/_utils.py#L69-L70
google/trax
d6cae2067dedd0490b78d831033607357e975015
trax/tf_numpy/numpy_impl/array_ops.py
python
around
(a, decimals=0)
return utils.tensor_to_ndarray(a).astype(dtype)
[]
def around(a, decimals=0): # pylint: disable=missing-docstring a = asarray(a) dtype = a.dtype factor = math.pow(10, decimals) if np.issubdtype(dtype, np.inexact): factor = tf.cast(factor, dtype) else: # Use float as the working dtype when a.dtype is exact (e.g. integer), # because `decimals` can be negative. float_dtype = dtypes.default_float_type() a = a.astype(float_dtype).data factor = tf.cast(factor, float_dtype) a = tf.multiply(a, factor) a = tf.round(a) a = tf.math.divide(a, factor) return utils.tensor_to_ndarray(a).astype(dtype)
[ "def", "around", "(", "a", ",", "decimals", "=", "0", ")", ":", "# pylint: disable=missing-docstring", "a", "=", "asarray", "(", "a", ")", "dtype", "=", "a", ".", "dtype", "factor", "=", "math", ".", "pow", "(", "10", ",", "decimals", ")", "if", "np"...
https://github.com/google/trax/blob/d6cae2067dedd0490b78d831033607357e975015/trax/tf_numpy/numpy_impl/array_ops.py#L817-L832
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/sound/microphone.py
python
Microphone.streamStatus
(self)
Status of the audio stream (`AudioDeviceStatus` or `None`). See :class:`~psychopy.sound.AudioDeviceStatus` for a complete overview of available status fields. This property has a value of `None` if the stream is presently closed. Examples -------- Get the capture start time of the stream:: # assumes mic.start() was called captureStartTime = mic.status.captureStartTime Check if microphone recording is active:: isActive = mic.status.active Get the number of seconds recorded up to this point:: recordedSecs = mic.status.recordedSecs
Status of the audio stream (`AudioDeviceStatus` or `None`).
[ "Status", "of", "the", "audio", "stream", "(", "AudioDeviceStatus", "or", "None", ")", "." ]
def streamStatus(self): """Status of the audio stream (`AudioDeviceStatus` or `None`). See :class:`~psychopy.sound.AudioDeviceStatus` for a complete overview of available status fields. This property has a value of `None` if the stream is presently closed. Examples -------- Get the capture start time of the stream:: # assumes mic.start() was called captureStartTime = mic.status.captureStartTime Check if microphone recording is active:: isActive = mic.status.active Get the number of seconds recorded up to this point:: recordedSecs = mic.status.recordedSecs """ currentStatus = self._stream.status if currentStatus != -1: return AudioDeviceStatus.createFromPTBDesc(currentStatus)
[ "def", "streamStatus", "(", "self", ")", ":", "currentStatus", "=", "self", ".", "_stream", ".", "status", "if", "currentStatus", "!=", "-", "1", ":", "return", "AudioDeviceStatus", ".", "createFromPTBDesc", "(", "currentStatus", ")" ]
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/sound/microphone.py#L652-L677
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/client/ssh/wrapper/pillar.py
python
raw
(key=None)
return ret
Return the raw pillar data that is available in the module. This will show the pillar as it is loaded as the __pillar__ dict. CLI Example: .. code-block:: bash salt '*' pillar.raw With the optional key argument, you can select a subtree of the pillar raw data.:: salt '*' pillar.raw key='roles'
Return the raw pillar data that is available in the module. This will show the pillar as it is loaded as the __pillar__ dict.
[ "Return", "the", "raw", "pillar", "data", "that", "is", "available", "in", "the", "module", ".", "This", "will", "show", "the", "pillar", "as", "it", "is", "loaded", "as", "the", "__pillar__", "dict", "." ]
def raw(key=None): """ Return the raw pillar data that is available in the module. This will show the pillar as it is loaded as the __pillar__ dict. CLI Example: .. code-block:: bash salt '*' pillar.raw With the optional key argument, you can select a subtree of the pillar raw data.:: salt '*' pillar.raw key='roles' """ if key: ret = __pillar__.get(key, {}) else: ret = __pillar__.value() return ret
[ "def", "raw", "(", "key", "=", "None", ")", ":", "if", "key", ":", "ret", "=", "__pillar__", ".", "get", "(", "key", ",", "{", "}", ")", "else", ":", "ret", "=", "__pillar__", ".", "value", "(", ")", "return", "ret" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/client/ssh/wrapper/pillar.py#L89-L110
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/homekit_controller/cover.py
python
HomeKitWindowCover.async_set_cover_tilt_position
(self, **kwargs)
Move the cover tilt to a specific position.
Move the cover tilt to a specific position.
[ "Move", "the", "cover", "tilt", "to", "a", "specific", "position", "." ]
async def async_set_cover_tilt_position(self, **kwargs): """Move the cover tilt to a specific position.""" tilt_position = kwargs[ATTR_TILT_POSITION] if self.is_vertical_tilt: await self.async_put_characteristics( {CharacteristicsTypes.VERTICAL_TILT_TARGET: tilt_position} ) elif self.is_horizontal_tilt: await self.async_put_characteristics( {CharacteristicsTypes.HORIZONTAL_TILT_TARGET: tilt_position} )
[ "async", "def", "async_set_cover_tilt_position", "(", "self", ",", "*", "*", "kwargs", ")", ":", "tilt_position", "=", "kwargs", "[", "ATTR_TILT_POSITION", "]", "if", "self", ".", "is_vertical_tilt", ":", "await", "self", ".", "async_put_characteristics", "(", "...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/homekit_controller/cover.py#L230-L240
mushorg/conpot
1c2382ea290b611fdc6a0a5f9572c7504bcb616e
conpot/protocols/bacnet/bacnet_app.py
python
BACnetApp.get_objects_and_properties
(self, dom)
parse the bacnet template for objects and their properties
parse the bacnet template for objects and their properties
[ "parse", "the", "bacnet", "template", "for", "objects", "and", "their", "properties" ]
def get_objects_and_properties(self, dom): """ parse the bacnet template for objects and their properties """ self.deviceIdentifier = int(dom.xpath("//bacnet/device_info/*")[1].text) device_property_list = dom.xpath("//bacnet/device_info/*") for prop in device_property_list: prop_key = prop.tag.lower().title() prop_key = re.sub("['_','-']", "", prop_key) prop_key = prop_key[0].lower() + prop_key[1:] if ( prop_key not in self.localDevice.propertyList.value and prop_key not in ["deviceIdentifier", "deviceName"] ): self.add_property(prop_key, prop.text) object_list = dom.xpath("//bacnet/object_list/object/@name") for obj in object_list: property_list = dom.xpath( '//bacnet/object_list/object[@name="%s"]/properties/*' % obj ) for prop in property_list: if prop.tag == "object_type": object_type = re.sub("-", " ", prop.text).lower().title() object_type = re.sub(" ", "", object_type) + "Object" try: device_object = getattr(bacpypes.object, object_type)() device_object.propertyList = list() except NameError: logger.critical("Non-existent BACnet object type") sys.exit(3) for prop in property_list: prop_key = prop.tag.lower().title() prop_key = re.sub("['_','-']", "", prop_key) prop_key = prop_key[0].lower() + prop_key[1:] if prop_key == "objectType": prop_val = prop.text.lower().title() prop_val = re.sub(" ", "", prop_val) prop_val = prop_val[0].lower() + prop_val[1:] prop_val = prop.text try: if prop_key == "objectIdentifier": device_object.objectIdentifier = int(prop_val) else: setattr(device_object, prop_key, prop_val) device_object.propertyList.append(prop_key) except bacpypes.object.PropertyError: logger.critical("Non-existent BACnet property type") sys.exit(3) self.add_object(device_object)
[ "def", "get_objects_and_properties", "(", "self", ",", "dom", ")", ":", "self", ".", "deviceIdentifier", "=", "int", "(", "dom", ".", "xpath", "(", "\"//bacnet/device_info/*\"", ")", "[", "1", "]", ".", "text", ")", "device_property_list", "=", "dom", ".", ...
https://github.com/mushorg/conpot/blob/1c2382ea290b611fdc6a0a5f9572c7504bcb616e/conpot/protocols/bacnet/bacnet_app.py#L69-L118
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/set_partition.py
python
SetPartition.standardization
(self)
return SetPartitions(len(r))([[r[e] for e in b] for b in self])
r""" Return the standardization of ``self``. Given a set partition `A = \{A_1, \ldots, A_n\}` of an ordered set `S`, the standardization of `A` is the set partition of `\{1, 2, \ldots, |S|\}` obtained by replacing the elements of the parts of `A` by the integers `1, 2, \ldots, |S|` in such a way that their relative order is preserved (i. e., the smallest element in the whole set partition is replaced by `1`, the next-smallest by `2`, and so on). EXAMPLES:: sage: SetPartition([[4], [1, 3]]).standardization() {{1, 2}, {3}} sage: SetPartition([[4], [6, 3]]).standardization() {{1, 3}, {2}} sage: SetPartition([]).standardization() {} sage: SetPartition([('c','b'),('d','f'),('e','a')]).standardization() {{1, 5}, {2, 3}, {4, 6}}
r""" Return the standardization of ``self``.
[ "r", "Return", "the", "standardization", "of", "self", "." ]
def standardization(self): r""" Return the standardization of ``self``. Given a set partition `A = \{A_1, \ldots, A_n\}` of an ordered set `S`, the standardization of `A` is the set partition of `\{1, 2, \ldots, |S|\}` obtained by replacing the elements of the parts of `A` by the integers `1, 2, \ldots, |S|` in such a way that their relative order is preserved (i. e., the smallest element in the whole set partition is replaced by `1`, the next-smallest by `2`, and so on). EXAMPLES:: sage: SetPartition([[4], [1, 3]]).standardization() {{1, 2}, {3}} sage: SetPartition([[4], [6, 3]]).standardization() {{1, 3}, {2}} sage: SetPartition([]).standardization() {} sage: SetPartition([('c','b'),('d','f'),('e','a')]).standardization() {{1, 5}, {2, 3}, {4, 6}} """ r = {e: i for i,e in enumerate(sorted(self.base_set()), 1)} return SetPartitions(len(r))([[r[e] for e in b] for b in self])
[ "def", "standardization", "(", "self", ")", ":", "r", "=", "{", "e", ":", "i", "for", "i", ",", "e", "in", "enumerate", "(", "sorted", "(", "self", ".", "base_set", "(", ")", ")", ",", "1", ")", "}", "return", "SetPartitions", "(", "len", "(", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/set_partition.py#L1661-L1685
zulip/zulip
19f891968de50d43920af63526c823bdd233cdee
zerver/migrations/0079_remove_old_scheduled_jobs.py
python
delete_old_scheduled_jobs
(apps: StateApps, schema_editor: DatabaseSchemaEditor)
Delete any old scheduled jobs, to handle changes in the format of that table. Ideally, we'd translate the jobs, but it's not really worth the development effort to save a few invitation reminders and day2 followup emails.
Delete any old scheduled jobs, to handle changes in the format of that table. Ideally, we'd translate the jobs, but it's not really worth the development effort to save a few invitation reminders and day2 followup emails.
[ "Delete", "any", "old", "scheduled", "jobs", "to", "handle", "changes", "in", "the", "format", "of", "that", "table", ".", "Ideally", "we", "d", "translate", "the", "jobs", "but", "it", "s", "not", "really", "worth", "the", "development", "effort", "to", ...
def delete_old_scheduled_jobs(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: """Delete any old scheduled jobs, to handle changes in the format of that table. Ideally, we'd translate the jobs, but it's not really worth the development effort to save a few invitation reminders and day2 followup emails. """ ScheduledJob = apps.get_model("zerver", "ScheduledJob") ScheduledJob.objects.all().delete()
[ "def", "delete_old_scheduled_jobs", "(", "apps", ":", "StateApps", ",", "schema_editor", ":", "DatabaseSchemaEditor", ")", "->", "None", ":", "ScheduledJob", "=", "apps", ".", "get_model", "(", "\"zerver\"", ",", "\"ScheduledJob\"", ")", "ScheduledJob", ".", "obje...
https://github.com/zulip/zulip/blob/19f891968de50d43920af63526c823bdd233cdee/zerver/migrations/0079_remove_old_scheduled_jobs.py#L7-L14
pythonanywhere/dirigible-spreadsheet
c771e9a391708f3b219248bf9974e05b1582fdd0
dirigible/sheet/parser/grammar.py
python
p_fplist
(p)
fplist : fpdef | fpdef COMMA | fpdef _comma_fpdefs | fpdef _comma_fpdefs COMMA
fplist : fpdef | fpdef COMMA | fpdef _comma_fpdefs | fpdef _comma_fpdefs COMMA
[ "fplist", ":", "fpdef", "|", "fpdef", "COMMA", "|", "fpdef", "_comma_fpdefs", "|", "fpdef", "_comma_fpdefs", "COMMA" ]
def p_fplist(p): """fplist : fpdef | fpdef COMMA | fpdef _comma_fpdefs | fpdef _comma_fpdefs COMMA""" if len(p) == 2: p[0] = FPList([p[1]]) elif len(p) == 3: if str(p[2]).rstrip() == ",": p[0] = FPList([p[1], p[2]]) else: p[0] = FPList([p[1]] + p[2]) else: p[0] = FPList([[p[1]] + p[2] + [p[3]]])
[ "def", "p_fplist", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "FPList", "(", "[", "p", "[", "1", "]", "]", ")", "elif", "len", "(", "p", ")", "==", "3", ":", "if", "str", "(", "p", "[", "2...
https://github.com/pythonanywhere/dirigible-spreadsheet/blob/c771e9a391708f3b219248bf9974e05b1582fdd0/dirigible/sheet/parser/grammar.py#L136-L149
log2timeline/dfvfs
4ca7bf06b15cdc000297a7122a065f0ca71de544
dfvfs/vfs/apfs_container_file_system.py
python
APFSContainerFileSystem.GetAPFSContainer
(self)
return self._fsapfs_container
Retrieves the APFS container. Returns: pyfsapfs.container: the APFS container.
Retrieves the APFS container.
[ "Retrieves", "the", "APFS", "container", "." ]
def GetAPFSContainer(self): """Retrieves the APFS container. Returns: pyfsapfs.container: the APFS container. """ return self._fsapfs_container
[ "def", "GetAPFSContainer", "(", "self", ")", ":", "return", "self", ".", "_fsapfs_container" ]
https://github.com/log2timeline/dfvfs/blob/4ca7bf06b15cdc000297a7122a065f0ca71de544/dfvfs/vfs/apfs_container_file_system.py#L86-L92
bokeh/bokeh
a00e59da76beb7b9f83613533cfd3aced1df5f06
bokeh/embed/elements.py
python
html_page_for_render_items
(bundle: Bundle | Tuple[str, str], docs_json: Dict[ID, DocJson], render_items: List[RenderItem], title: str, template: Template | str | None = None, template_variables: Dict[str, Any] = {})
return html
Render an HTML page from a template and Bokeh render items. Args: bundle (tuple): a tuple containing (bokehjs, bokehcss) docs_json (JSON-like): Serialized Bokeh Document render_items (RenderItems) Specific items to render from the document and where title (str or None) A title for the HTML page. If None, DEFAULT_TITLE is used template (str or Template or None, optional) : A Template to be used for the HTML page. If None, FILE is used. template_variables (dict, optional): Any Additional variables to pass to the template Returns: str
Render an HTML page from a template and Bokeh render items.
[ "Render", "an", "HTML", "page", "from", "a", "template", "and", "Bokeh", "render", "items", "." ]
def html_page_for_render_items(bundle: Bundle | Tuple[str, str], docs_json: Dict[ID, DocJson], render_items: List[RenderItem], title: str, template: Template | str | None = None, template_variables: Dict[str, Any] = {}) -> str: ''' Render an HTML page from a template and Bokeh render items. Args: bundle (tuple): a tuple containing (bokehjs, bokehcss) docs_json (JSON-like): Serialized Bokeh Document render_items (RenderItems) Specific items to render from the document and where title (str or None) A title for the HTML page. If None, DEFAULT_TITLE is used template (str or Template or None, optional) : A Template to be used for the HTML page. If None, FILE is used. template_variables (dict, optional): Any Additional variables to pass to the template Returns: str ''' if title is None: title = DEFAULT_TITLE bokeh_js, bokeh_css = bundle json_id = make_id() json = escape(serialize_json(docs_json), quote=False) json = wrap_in_script_tag(json, "application/json", json_id) script = wrap_in_script_tag(script_for_render_items(json_id, render_items)) context = template_variables.copy() context.update(dict( title = title, bokeh_js = bokeh_js, bokeh_css = bokeh_css, plot_script = json + script, docs = render_items, base = FILE, macros = MACROS, )) if len(render_items) == 1: context["doc"] = context["docs"][0] context["roots"] = context["doc"].roots # XXX: backwards compatibility, remove for 1.0 context["plot_div"] = "\n".join(div_for_render_item(item) for item in render_items) if template is None: template = FILE elif isinstance(template, str): template = get_env().from_string("{% extends base %}\n" + template) html = template.render(context) return html
[ "def", "html_page_for_render_items", "(", "bundle", ":", "Bundle", "|", "Tuple", "[", "str", ",", "str", "]", ",", "docs_json", ":", "Dict", "[", "ID", ",", "DocJson", "]", ",", "render_items", ":", "List", "[", "RenderItem", "]", ",", "title", ":", "s...
https://github.com/bokeh/bokeh/blob/a00e59da76beb7b9f83613533cfd3aced1df5f06/bokeh/embed/elements.py#L88-L152
tanghaibao/jcvi
5e720870c0928996f8b77a38208106ff0447ccb6
jcvi/variation/str.py
python
batchlobstr
(args)
%prog batchlobstr samples.csv Run lobSTR sequentially on list of samples. Each line contains: sample-name,s3-location
%prog batchlobstr samples.csv
[ "%prog", "batchlobstr", "samples", ".", "csv" ]
def batchlobstr(args): """ %prog batchlobstr samples.csv Run lobSTR sequentially on list of samples. Each line contains: sample-name,s3-location """ p = OptionParser(batchlobstr.__doc__) p.add_option("--sep", default=",", help="Separator for building commandline") p.set_home("lobstr", default="s3://hli-mv-data-science/htang/str-build/lobSTR/") p.set_aws_opts(store="hli-mv-data-science/htang/str-data") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) (samplesfile,) = args store = opts.output_path computed = ls_s3(store) fp = open(samplesfile) skipped = total = 0 for row in fp: total += 1 sample, s3file = row.strip().split(",")[:2] exec_id, sample_id = sample.split("_") bamfile = s3file.replace(".gz", "").replace(".vcf", ".bam") gzfile = sample + ".{0}.vcf.gz".format("hg38") if gzfile in computed: skipped += 1 continue print( opts.sep.join( "python -m jcvi.variation.str lobstr".split() + [ "hg38", "--input_bam_path", bamfile, "--output_path", store, "--sample_id", sample_id, "--workflow_execution_id", exec_id, "--lobstr_home", opts.lobstr_home, "--workdir", opts.workdir, ] ) ) fp.close() logging.debug("Total skipped: {0}".format(percentage(skipped, total)))
[ "def", "batchlobstr", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "batchlobstr", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--sep\"", ",", "default", "=", "\",\"", ",", "help", "=", "\"Separator for building commandline\"", ")", "p", ".",...
https://github.com/tanghaibao/jcvi/blob/5e720870c0928996f8b77a38208106ff0447ccb6/jcvi/variation/str.py#L1266-L1319
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/distribute/pkg_resources.py
python
Distribution.requires
(self,extras=())
return deps
List of Requirements needed for this distro if `extras` are used
List of Requirements needed for this distro if `extras` are used
[ "List", "of", "Requirements", "needed", "for", "this", "distro", "if", "extras", "are", "used" ]
def requires(self,extras=()): """List of Requirements needed for this distro if `extras` are used""" dm = self._dep_map deps = [] deps.extend(dm.get(None,())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra( "%s has no such extra feature %r" % (self, ext) ) return deps
[ "def", "requires", "(", "self", ",", "extras", "=", "(", ")", ")", ":", "dm", "=", "self", ".", "_dep_map", "deps", "=", "[", "]", "deps", ".", "extend", "(", "dm", ".", "get", "(", "None", ",", "(", ")", ")", ")", "for", "ext", "in", "extras...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/distribute/pkg_resources.py#L2205-L2217
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
deep-learning/NLP/Seq2Seq-PyTorch/evaluate.py
python
evaluate_model
( model, src, src_test, trg, trg_test, config, src_valid=None, trg_valid=None, verbose=True, metric='bleu' )
return get_bleu(preds, ground_truths)
Evaluate model.
Evaluate model.
[ "Evaluate", "model", "." ]
def evaluate_model( model, src, src_test, trg, trg_test, config, src_valid=None, trg_valid=None, verbose=True, metric='bleu' ): """Evaluate model.""" preds = [] ground_truths = [] for j in xrange(0, len(src_test['data']), config['data']['batch_size']): # Get source minibatch input_lines_src, output_lines_src, lens_src, mask_src = get_minibatch( src_test['data'], src['word2id'], j, config['data']['batch_size'], config['data']['max_src_length'], add_start=True, add_end=True ) # Get target minibatch input_lines_trg_gold, output_lines_trg_gold, lens_src, mask_src = ( get_minibatch( trg_test['data'], trg['word2id'], j, config['data']['batch_size'], config['data']['max_trg_length'], add_start=True, add_end=True ) ) # Initialize target with <s> for every sentence input_lines_trg = Variable(torch.LongTensor( [ [trg['word2id']['<s>']] for i in xrange(input_lines_src.size(0)) ] )).cuda() # Decode a minibatch greedily __TODO__ add beam search decoding input_lines_trg = decode_minibatch( config, model, input_lines_src, input_lines_trg, output_lines_trg_gold ) # Copy minibatch outputs to cpu and convert ids to words input_lines_trg = input_lines_trg.data.cpu().numpy() input_lines_trg = [ [trg['id2word'][x] for x in line] for line in input_lines_trg ] # Do the same for gold sentences output_lines_trg_gold = output_lines_trg_gold.data.cpu().numpy() output_lines_trg_gold = [ [trg['id2word'][x] for x in line] for line in output_lines_trg_gold ] # Process outputs for sentence_pred, sentence_real, sentence_real_src in zip( input_lines_trg, output_lines_trg_gold, output_lines_src ): if '</s>' in sentence_pred: index = sentence_pred.index('</s>') else: index = len(sentence_pred) preds.append(['<s>'] + sentence_pred[:index + 1]) if verbose: print ' '.join(['<s>'] + sentence_pred[:index + 1]) if '</s>' in sentence_real: index = sentence_real.index('</s>') else: index = len(sentence_real) if verbose: print ' '.join(['<s>'] + sentence_real[:index + 1]) if verbose: print '--------------------------------------' ground_truths.append(['<s>'] + sentence_real[:index + 1]) return get_bleu(preds, ground_truths)
[ "def", "evaluate_model", "(", "model", ",", "src", ",", "src_test", ",", "trg", ",", "trg_test", ",", "config", ",", "src_valid", "=", "None", ",", "trg_valid", "=", "None", ",", "verbose", "=", "True", ",", "metric", "=", "'bleu'", ")", ":", "preds", ...
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/deep-learning/NLP/Seq2Seq-PyTorch/evaluate.py#L140-L218
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/docutils/writers/docutils_xml.py
python
XMLTranslator.default_visit
(self, node)
Default node visit method.
Default node visit method.
[ "Default", "node", "visit", "method", "." ]
def default_visit(self, node): """Default node visit method.""" if not self.in_simple: self.output.append(self.indent*self.level) self.output.append(node.starttag(xml.sax.saxutils.quoteattr)) self.level += 1 if isinstance(node, nodes.TextElement): self.in_simple += 1 if not self.in_simple: self.output.append(self.newline)
[ "def", "default_visit", "(", "self", ",", "node", ")", ":", "if", "not", "self", ".", "in_simple", ":", "self", ".", "output", ".", "append", "(", "self", ".", "indent", "*", "self", ".", "level", ")", "self", ".", "output", ".", "append", "(", "no...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/docutils/writers/docutils_xml.py#L128-L137
gtaylor/python-colormath
4a076831fd5136f685aa7143db81eba27b2cd19a
colormath/color_objects.py
python
BaseRGBColor.clamped_rgb_g
(self)
return self._clamp_rgb_coordinate(self.rgb_g)
The clamped (0.0-1.0) G value.
The clamped (0.0-1.0) G value.
[ "The", "clamped", "(", "0", ".", "0", "-", "1", ".", "0", ")", "G", "value", "." ]
def clamped_rgb_g(self): """ The clamped (0.0-1.0) G value. """ return self._clamp_rgb_coordinate(self.rgb_g)
[ "def", "clamped_rgb_g", "(", "self", ")", ":", "return", "self", ".", "_clamp_rgb_coordinate", "(", "self", ".", "rgb_g", ")" ]
https://github.com/gtaylor/python-colormath/blob/4a076831fd5136f685aa7143db81eba27b2cd19a/colormath/color_objects.py#L644-L648
GoogleCloudPlatform/professional-services
0c707aa97437f3d154035ef8548109b7882f71da
tools/dns-sync/dns_sync/main.py
python
ComputeEngineActivityPush.handle_create_activity
(self, project, resource_type, resource_id, message_payload)
Process a resource created event. Args: project: Name of project owning the resource. resource_type: Type of the resource like "instance" or "forwardingRule". resource_id: unique id of the resource. message_payload: pubsub message payload.
Process a resource created event.
[ "Process", "a", "resource", "created", "event", "." ]
def handle_create_activity(self, project, resource_type, resource_id, message_payload): """Process a resource created event. Args: project: Name of project owning the resource. resource_type: Type of the resource like "instance" or "forwardingRule". resource_id: unique id of the resource. message_payload: pubsub message payload. """ state = None if audit_log.AuditLogLoop.is_audit_log_test_event(message_payload): state = audit_log.AuditLogLoop.get_state_entity() state.record_event(message_payload) # If this is an insert operation lookup the resource to find via the # operation. operation_reference = message_payload['operation'] operation_name = operation_reference['name'] operation = None try: if 'global' in operation_reference: operation = api.CLIENTS.compute.globalOperations().get( operation=operation_name, project=project).execute() elif 'region' in operation_reference: operation = api.CLIENTS.compute.regionOperations().get( operation=operation_name, project=project, region=operation_reference['region']).execute() elif 'zone' in operation_reference: operation = api.CLIENTS.compute.zoneOperations().get( operation=operation_name, project=project, zone=operation_reference['zone']).execute() except errors.HttpError as e: if e.resp.status == 404: # Don't raise exception on 404, some operations like GAE # Flexible operations can't be retrieved. logging.debug('unable to retreive operation %s/%s', project, operation_name) return else: raise # Lookup the resource the operation was performed on # as we need external IP and perhaps subnet. resource_url = operation['targetLink'] response, content = api.CLIENTS.compute._http.request(resource_url) if (response.status < 200) or (response.status >= 300): logging.error('unable %s to get resource from url %s: %s', response.status, resource_url, content) return resource = json.loads(content) # Save the resource in the datastore so we can retrieve it upon # resource deletion. as we won't be able to lookup the resource again # when we get the delete operation notification. stored_resource_id = '{}:{}:{}'.format(project, resource_type, resource_id) logging.debug('adding stored resource with id %s', stored_resource_id) resource_name = message_payload['resource']['name'] stored_resource = CreatedDnsResource( entity_id=stored_resource_id, project_id=project, resource_name=resource_name, resource_string=content, event=message_payload) stored_resource.put() create_dns_a_records_for_resource(resource, project) if state is not None: state.handle_create_event() state.put()
[ "def", "handle_create_activity", "(", "self", ",", "project", ",", "resource_type", ",", "resource_id", ",", "message_payload", ")", ":", "state", "=", "None", "if", "audit_log", ".", "AuditLogLoop", ".", "is_audit_log_test_event", "(", "message_payload", ")", ":"...
https://github.com/GoogleCloudPlatform/professional-services/blob/0c707aa97437f3d154035ef8548109b7882f71da/tools/dns-sync/dns_sync/main.py#L677-L753
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/scipy/special/basic.py
python
pro_cv_seq
(m, n, c)
return specfun.segv(m, n, c, 1)[1][:maxL]
Characteristic values for prolate spheroidal wave functions. Compute a sequence of characteristic values for the prolate spheroidal wave functions for mode m and n'=m..n and spheroidal parameter c. References ---------- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special Functions", John Wiley and Sons, 1996. http://jin.ece.illinois.edu/specfunc.html
Characteristic values for prolate spheroidal wave functions.
[ "Characteristic", "values", "for", "prolate", "spheroidal", "wave", "functions", "." ]
def pro_cv_seq(m, n, c): """Characteristic values for prolate spheroidal wave functions. Compute a sequence of characteristic values for the prolate spheroidal wave functions for mode m and n'=m..n and spheroidal parameter c. References ---------- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special Functions", John Wiley and Sons, 1996. http://jin.ece.illinois.edu/specfunc.html """ if not (isscalar(m) and isscalar(n) and isscalar(c)): raise ValueError("Arguments must be scalars.") if (n != floor(n)) or (m != floor(m)): raise ValueError("Modes must be integers.") if (n-m > 199): raise ValueError("Difference between n and m is too large.") maxL = n-m+1 return specfun.segv(m, n, c, 1)[1][:maxL]
[ "def", "pro_cv_seq", "(", "m", ",", "n", ",", "c", ")", ":", "if", "not", "(", "isscalar", "(", "m", ")", "and", "isscalar", "(", "n", ")", "and", "isscalar", "(", "c", ")", ")", ":", "raise", "ValueError", "(", "\"Arguments must be scalars.\"", ")",...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/scipy/special/basic.py#L2015-L2036
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/metadata/primitives.py
python
Contributor.names
(self)
return msg
r''' Returns all names in a list. >>> td = metadata.Contributor( ... role='composer', ... names=['Chopin, Fryderyk', 'Chopin, Frederick'], ... ) >>> td.names ['Chopin, Fryderyk', 'Chopin, Frederick'] >>> td.names = ['Czerny', 'Spohr'] >>> td.names ['Czerny', 'Spohr']
r''' Returns all names in a list.
[ "r", "Returns", "all", "names", "in", "a", "list", "." ]
def names(self): r''' Returns all names in a list. >>> td = metadata.Contributor( ... role='composer', ... names=['Chopin, Fryderyk', 'Chopin, Frederick'], ... ) >>> td.names ['Chopin, Fryderyk', 'Chopin, Frederick'] >>> td.names = ['Czerny', 'Spohr'] >>> td.names ['Czerny', 'Spohr'] ''' # return first name msg = [] for n in self._names: msg.append(str(n)) return msg
[ "def", "names", "(", "self", ")", ":", "# return first name", "msg", "=", "[", "]", "for", "n", "in", "self", ".", "_names", ":", "msg", ".", "append", "(", "str", "(", "n", ")", ")", "return", "msg" ]
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/metadata/primitives.py#L988-L1007
genforce/interfacegan
acec139909fb9aad41fbdbbbde651dfc0b7b3a17
models/pggan_tf_official/metrics/frechet_inception_distance.py
python
calculate_frechet_distance
(mu1, sigma1, mu2, sigma2)
return np.real(dist)
Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Params: -- mu1 : Numpy array containing the activations of the pool_3 layer of the inception net ( like returned by the function 'get_predictions') -- mu2 : The sample mean over activations of the pool_3 layer, precalcualted on an representive data set. -- sigma2: The covariance matrix over activations of the pool_3 layer, precalcualted on an representive data set. Returns: -- dist : The Frechet Distance. Raises: -- InvalidFIDException if nan occures.
Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
[ "Numpy", "implementation", "of", "the", "Frechet", "Distance", ".", "The", "Frechet", "distance", "between", "two", "multivariate", "Gaussians", "X_1", "~", "N", "(", "mu_1", "C_1", ")", "and", "X_2", "~", "N", "(", "mu_2", "C_2", ")", "is", "d^2", "=", ...
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Params: -- mu1 : Numpy array containing the activations of the pool_3 layer of the inception net ( like returned by the function 'get_predictions') -- mu2 : The sample mean over activations of the pool_3 layer, precalcualted on an representive data set. -- sigma2: The covariance matrix over activations of the pool_3 layer, precalcualted on an representive data set. Returns: -- dist : The Frechet Distance. Raises: -- InvalidFIDException if nan occures. """ m = np.square(mu1 - mu2).sum() #s = sp.linalg.sqrtm(np.dot(sigma1, sigma2)) # EDIT: commented out s, _ = sp.linalg.sqrtm(np.dot(sigma1, sigma2), disp=False) # EDIT: added dist = m + np.trace(sigma1+sigma2 - 2*s) #if np.isnan(dist): # EDIT: commented out # raise InvalidFIDException("nan occured in distance calculation.") # EDIT: commented out #return dist # EDIT: commented out return np.real(dist)
[ "def", "calculate_frechet_distance", "(", "mu1", ",", "sigma1", ",", "mu2", ",", "sigma2", ")", ":", "m", "=", "np", ".", "square", "(", "mu1", "-", "mu2", ")", ".", "sum", "(", ")", "#s = sp.linalg.sqrtm(np.dot(sigma1, sigma2)) # EDIT: commented out", "s", ",...
https://github.com/genforce/interfacegan/blob/acec139909fb9aad41fbdbbbde651dfc0b7b3a17/models/pggan_tf_official/metrics/frechet_inception_distance.py#L125-L152
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/jinja2/ext.py
python
extract_from_ast
(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True)
Extract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as `None`. This allows Babel to figure out what you really meant if you are using gettext functions that allow keyword arguments for placeholder expansion. If you don't want that behavior set the `babel_style` parameter to `False` which causes only strings to be returned and parameters are always stored in tuples. As a consequence invalid gettext calls (calls without a single string parameter or string parameters after non-string parameters) are skipped. This example explains the behavior: >>> from jinja2 import Environment >>> env = Environment() >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}') >>> list(extract_from_ast(node)) [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))] >>> list(extract_from_ast(node, babel_style=False)) [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))] For every string found this function yields a ``(lineno, function, message)`` tuple, where: * ``lineno`` is the number of the line on which the string was found, * ``function`` is the name of the ``gettext`` function used (if the string was extracted from embedded Python code), and * ``message`` is the string itself (a ``unicode`` object, or a tuple of ``unicode`` objects for functions with multiple string arguments). This extraction function operates on the AST and is because of that unable to extract any comments. For comment support you have to use the babel extraction interface or extract comments yourself.
Extract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as `None`. This allows Babel to figure out what you really meant if you are using gettext functions that allow keyword arguments for placeholder expansion. If you don't want that behavior set the `babel_style` parameter to `False` which causes only strings to be returned and parameters are always stored in tuples. As a consequence invalid gettext calls (calls without a single string parameter or string parameters after non-string parameters) are skipped.
[ "Extract", "localizable", "strings", "from", "the", "given", "template", "node", ".", "Per", "default", "this", "function", "returns", "matches", "in", "babel", "style", "that", "means", "non", "string", "parameters", "as", "well", "as", "keyword", "arguments", ...
def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True): """Extract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as `None`. This allows Babel to figure out what you really meant if you are using gettext functions that allow keyword arguments for placeholder expansion. If you don't want that behavior set the `babel_style` parameter to `False` which causes only strings to be returned and parameters are always stored in tuples. As a consequence invalid gettext calls (calls without a single string parameter or string parameters after non-string parameters) are skipped. This example explains the behavior: >>> from jinja2 import Environment >>> env = Environment() >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}') >>> list(extract_from_ast(node)) [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))] >>> list(extract_from_ast(node, babel_style=False)) [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))] For every string found this function yields a ``(lineno, function, message)`` tuple, where: * ``lineno`` is the number of the line on which the string was found, * ``function`` is the name of the ``gettext`` function used (if the string was extracted from embedded Python code), and * ``message`` is the string itself (a ``unicode`` object, or a tuple of ``unicode`` objects for functions with multiple string arguments). This extraction function operates on the AST and is because of that unable to extract any comments. For comment support you have to use the babel extraction interface or extract comments yourself. """ for node in node.find_all(nodes.Call): if not isinstance(node.node, nodes.Name) or \ node.node.name not in gettext_functions: continue strings = [] for arg in node.args: if isinstance(arg, nodes.Const) and \ isinstance(arg.value, string_types): strings.append(arg.value) else: strings.append(None) for arg in node.kwargs: strings.append(None) if node.dyn_args is not None: strings.append(None) if node.dyn_kwargs is not None: strings.append(None) if not babel_style: strings = tuple(x for x in strings if x is not None) if not strings: continue else: if len(strings) == 1: strings = strings[0] else: strings = tuple(strings) yield node.lineno, node.node.name, strings
[ "def", "extract_from_ast", "(", "node", ",", "gettext_functions", "=", "GETTEXT_FUNCTIONS", ",", "babel_style", "=", "True", ")", ":", "for", "node", "in", "node", ".", "find_all", "(", "nodes", ".", "Call", ")", ":", "if", "not", "isinstance", "(", "node"...
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/jinja2/ext.py#L448-L513
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/protocols/policies.py
python
TimeoutMixin.timeoutConnection
(self)
Called when the connection times out. Override to define behavior other than dropping the connection.
Called when the connection times out.
[ "Called", "when", "the", "connection", "times", "out", "." ]
def timeoutConnection(self): """ Called when the connection times out. Override to define behavior other than dropping the connection. """ self.transport.loseConnection()
[ "def", "timeoutConnection", "(", "self", ")", ":", "self", ".", "transport", ".", "loseConnection", "(", ")" ]
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/protocols/policies.py#L719-L725
Sujit-O/pykg2vec
492807b627574f95b0db9e7cb9f090c3c45a030a
pykg2vec/models/pointwise.py
python
SimplE.embed
(self, h, r, t)
return emb_h1, emb_h2, emb_r1, emb_r2, emb_t1, emb_t2
Function to get the embedding value. Args: h (Tensor): Head entities ids. r (Tensor): Relation ids of the triple. t (Tensor): Tail entity ids of the triple. Returns: Tensors: Returns head, relation and tail embedding Tensors.
Function to get the embedding value.
[ "Function", "to", "get", "the", "embedding", "value", "." ]
def embed(self, h, r, t): """Function to get the embedding value. Args: h (Tensor): Head entities ids. r (Tensor): Relation ids of the triple. t (Tensor): Tail entity ids of the triple. Returns: Tensors: Returns head, relation and tail embedding Tensors. """ emb_h1 = self.ent_head_embeddings(h) emb_h2 = self.ent_head_embeddings(t) emb_r1 = self.rel_embeddings(r) emb_r2 = self.rel_inv_embeddings(r) emb_t1 = self.ent_tail_embeddings(t) emb_t2 = self.ent_tail_embeddings(h) return emb_h1, emb_h2, emb_r1, emb_r2, emb_t1, emb_t2
[ "def", "embed", "(", "self", ",", "h", ",", "r", ",", "t", ")", ":", "emb_h1", "=", "self", ".", "ent_head_embeddings", "(", "h", ")", "emb_h2", "=", "self", ".", "ent_head_embeddings", "(", "t", ")", "emb_r1", "=", "self", ".", "rel_embeddings", "("...
https://github.com/Sujit-O/pykg2vec/blob/492807b627574f95b0db9e7cb9f090c3c45a030a/pykg2vec/models/pointwise.py#L503-L520
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/_vendor/packaging/tags.py
python
_normalize_string
(string: str)
return string.replace(".", "_").replace("-", "_")
[]
def _normalize_string(string: str) -> str: return string.replace(".", "_").replace("-", "_")
[ "def", "_normalize_string", "(", "string", ":", "str", ")", "->", "str", ":", "return", "string", ".", "replace", "(", "\".\"", ",", "\"_\"", ")", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")" ]
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_vendor/packaging/tags.py#L121-L122
ethereum/trinity
6383280c5044feb06695ac2f7bc1100b7bcf4fe0
trinity/sync/common/headers.py
python
HeaderMeatSyncer.schedule_segment
( self, parent_header: BlockHeaderAPI, gap_length: int, skeleton_peer: TChainPeer)
:param parent_header: the parent of the gap to fill :param gap_length: how long is the header gap :param skeleton_peer: the peer that provided the parent_header - will not use to fill gaps
:param parent_header: the parent of the gap to fill :param gap_length: how long is the header gap :param skeleton_peer: the peer that provided the parent_header - will not use to fill gaps
[ ":", "param", "parent_header", ":", "the", "parent", "of", "the", "gap", "to", "fill", ":", "param", "gap_length", ":", "how", "long", "is", "the", "header", "gap", ":", "param", "skeleton_peer", ":", "the", "peer", "that", "provided", "the", "parent_heade...
async def schedule_segment( self, parent_header: BlockHeaderAPI, gap_length: int, skeleton_peer: TChainPeer) -> None: """ :param parent_header: the parent of the gap to fill :param gap_length: how long is the header gap :param skeleton_peer: the peer that provided the parent_header - will not use to fill gaps """ try: await self._filler_header_tasks.add(( (parent_header, gap_length, skeleton_peer), )) except ValidationError as exc: self.logger.debug( "Tried to re-add a duplicate list of headers to the download queue: %s", exc, )
[ "async", "def", "schedule_segment", "(", "self", ",", "parent_header", ":", "BlockHeaderAPI", ",", "gap_length", ":", "int", ",", "skeleton_peer", ":", "TChainPeer", ")", "->", "None", ":", "try", ":", "await", "self", ".", "_filler_header_tasks", ".", "add", ...
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/trinity/sync/common/headers.py#L637-L655
hasgeek/hasjob
38098e8034ee749704dea65394b366e8adc5c71f
migrations/versions/17869f3e044c_event_sessions.py
python
downgrade
()
[]
def downgrade(): op.drop_table('user_event') op.drop_index(op.f('ix_event_session_user_id'), table_name='event_session') op.drop_index(op.f('ix_event_session_anon_user_id'), table_name='event_session') op.drop_table('event_session') op.drop_index(op.f('ix_anon_user_user_id'), table_name='anon_user') op.drop_table('anon_user')
[ "def", "downgrade", "(", ")", ":", "op", ".", "drop_table", "(", "'user_event'", ")", "op", ".", "drop_index", "(", "op", ".", "f", "(", "'ix_event_session_user_id'", ")", ",", "table_name", "=", "'event_session'", ")", "op", ".", "drop_index", "(", "op", ...
https://github.com/hasgeek/hasjob/blob/38098e8034ee749704dea65394b366e8adc5c71f/migrations/versions/17869f3e044c_event_sessions.py#L83-L89
XiaoMi/minos
164454a0804fb7eb7e14052327bdd4d5572c2697
supervisor/supervisor/supervisorctl.py
python
Controller.onecmd
(self, line)
Override the onecmd method to: - catch and print all exceptions - allow for composite commands in interactive mode (foo; bar) - call 'do_foo' on plugins rather than ourself
Override the onecmd method to: - catch and print all exceptions - allow for composite commands in interactive mode (foo; bar) - call 'do_foo' on plugins rather than ourself
[ "Override", "the", "onecmd", "method", "to", ":", "-", "catch", "and", "print", "all", "exceptions", "-", "allow", "for", "composite", "commands", "in", "interactive", "mode", "(", "foo", ";", "bar", ")", "-", "call", "do_foo", "on", "plugins", "rather", ...
def onecmd(self, line): """ Override the onecmd method to: - catch and print all exceptions - allow for composite commands in interactive mode (foo; bar) - call 'do_foo' on plugins rather than ourself """ origline = line lines = line.split(';') # don't filter(None, line.split), as we pop line = lines.pop(0) # stuffing the remainder into cmdqueue will cause cmdloop to # call us again for each command. self.cmdqueue.extend(lines) cmd, arg, line = self.parseline(line) if not line: return self.emptyline() if cmd is None: return self.default(line) self.lastcmd = line if cmd == '': return self.default(line) else: do_func = self._get_do_func(cmd) if do_func is None: return self.default(line) try: try: return do_func(arg) except xmlrpclib.ProtocolError, e: if e.errcode == 401: if self.options.interactive: self.output('Server requires authentication') username = raw_input('Username:') password = getpass.getpass(prompt='Password:') self.output('') self.options.username = username self.options.password = password return self.onecmd(origline) else: self.options.usage('Server requires authentication') else: raise do_func(arg) except SystemExit: raise except Exception, e: (file, fun, line), t, v, tbinfo = asyncore.compact_traceback() error = 'error: %s, %s: file: %s line: %s' % (t, v, file, line) self.output(error) if not self.options.interactive: sys.exit(2)
[ "def", "onecmd", "(", "self", ",", "line", ")", ":", "origline", "=", "line", "lines", "=", "line", ".", "split", "(", "';'", ")", "# don't filter(None, line.split), as we pop", "line", "=", "lines", ".", "pop", "(", "0", ")", "# stuffing the remainder into cm...
https://github.com/XiaoMi/minos/blob/164454a0804fb7eb7e14052327bdd4d5572c2697/supervisor/supervisor/supervisorctl.py#L118-L167
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/objects/admin.py
python
ObjectDBAdmin.get_form
(self, request, obj=None, **kwargs)
return super().get_form(request, obj, **defaults)
Use special form during creation. Args: request (Request): Incoming request. obj (Object, optional): Database object.
Use special form during creation.
[ "Use", "special", "form", "during", "creation", "." ]
def get_form(self, request, obj=None, **kwargs): """ Use special form during creation. Args: request (Request): Incoming request. obj (Object, optional): Database object. """ defaults = {} if obj is None: defaults.update( {"form": self.add_form, "fields": flatten_fieldsets(self.add_fieldsets)} ) defaults.update(kwargs) return super().get_form(request, obj, **defaults)
[ "def", "get_form", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "{", "}", "if", "obj", "is", "None", ":", "defaults", ".", "update", "(", "{", "\"form\"", ":", "self", ".", "add_form", ...
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/objects/admin.py#L152-L167
zenodo/zenodo
3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5
zenodo/modules/records/serializers/bibtex.py
python
Bibtex._get_entry_subtype
(self)
return 'default'
Return entry subtype.
Return entry subtype.
[ "Return", "entry", "subtype", "." ]
def _get_entry_subtype(self): """Return entry subtype.""" if 'resource_type' in self.record: if 'subtype' in self.record['resource_type']: return self.record['resource_type']['subtype'] return 'default'
[ "def", "_get_entry_subtype", "(", "self", ")", ":", "if", "'resource_type'", "in", "self", ".", "record", ":", "if", "'subtype'", "in", "self", ".", "record", "[", "'resource_type'", "]", ":", "return", "self", ".", "record", "[", "'resource_type'", "]", "...
https://github.com/zenodo/zenodo/blob/3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5/zenodo/modules/records/serializers/bibtex.py#L371-L376
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/arrays/base.py
python
ExtensionArray.shape
(self)
return (len(self),)
Return a tuple of the array dimensions.
Return a tuple of the array dimensions.
[ "Return", "a", "tuple", "of", "the", "array", "dimensions", "." ]
def shape(self): # type: () -> Tuple[int, ...] """ Return a tuple of the array dimensions. """ return (len(self),)
[ "def", "shape", "(", "self", ")", ":", "# type: () -> Tuple[int, ...]", "return", "(", "len", "(", "self", ")", ",", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/arrays/base.py#L296-L301
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/cards/properties/shell.py
python
CompositeShellProperty.get_mass_per_area_structure
(self, rhos: List[float])
return ksym * mass_per_area
r""" Gets the Mass/Area for the property structure only (doesn't consider nsm). .. math:: \frac{m}{A} = \sum(\rho t) Parameters ---------- rhos : List[float] the densities of each ply
r""" Gets the Mass/Area for the property structure only (doesn't consider nsm).
[ "r", "Gets", "the", "Mass", "/", "Area", "for", "the", "property", "structure", "only", "(", "doesn", "t", "consider", "nsm", ")", "." ]
def get_mass_per_area_structure(self, rhos: List[float]) -> float: r""" Gets the Mass/Area for the property structure only (doesn't consider nsm). .. math:: \frac{m}{A} = \sum(\rho t) Parameters ---------- rhos : List[float] the densities of each ply """ nplies = len(self.thicknesses) mass_per_area = 0. for iply in range(nplies): rho = rhos[iply] t = self.thicknesses[iply] mass_per_area += rho * t ksym = 2. if self.is_symmetrical else 1. return ksym * mass_per_area
[ "def", "get_mass_per_area_structure", "(", "self", ",", "rhos", ":", "List", "[", "float", "]", ")", "->", "float", ":", "nplies", "=", "len", "(", "self", ".", "thicknesses", ")", "mass_per_area", "=", "0.", "for", "iply", "in", "range", "(", "nplies", ...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/properties/shell.py#L618-L639
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/utils/scope.py
python
RecursiveAttribute.to_dict
(self)
return d
Get an equivalent dict representation.
Get an equivalent dict representation.
[ "Get", "an", "equivalent", "dict", "representation", "." ]
def to_dict(self): """Get an equivalent dict representation.""" d = {} for k, v in self.__dict__["data"].items(): if isinstance(v, RecursiveAttribute): d[k] = v.to_dict() else: d[k] = v return d
[ "def", "to_dict", "(", "self", ")", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "__dict__", "[", "\"data\"", "]", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "RecursiveAttribute", ")", ":", "d", "[", "k...
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/utils/scope.py#L106-L114
MouseLand/suite2p
12dc119ac0c7c4355e9cd3e07bebc447755623e4
suite2p/gui/masks.py
python
init_masks
(parent)
creates RGB masks using stat and puts them in M0 or M1 depending on whether or not iscell is True for a given ROI args: ops: mean_image, Vcorr stat: xpix,ypix,xext,yext iscell: vector with True if ROI is cell ops_plot: plotROI, view, color, randcols outputs: M0: ROIs that are True in iscell M1: ROIs that are False in iscell
creates RGB masks using stat and puts them in M0 or M1 depending on whether or not iscell is True for a given ROI args: ops: mean_image, Vcorr stat: xpix,ypix,xext,yext iscell: vector with True if ROI is cell ops_plot: plotROI, view, color, randcols outputs: M0: ROIs that are True in iscell M1: ROIs that are False in iscell
[ "creates", "RGB", "masks", "using", "stat", "and", "puts", "them", "in", "M0", "or", "M1", "depending", "on", "whether", "or", "not", "iscell", "is", "True", "for", "a", "given", "ROI", "args", ":", "ops", ":", "mean_image", "Vcorr", "stat", ":", "xpix...
def init_masks(parent): """ creates RGB masks using stat and puts them in M0 or M1 depending on whether or not iscell is True for a given ROI args: ops: mean_image, Vcorr stat: xpix,ypix,xext,yext iscell: vector with True if ROI is cell ops_plot: plotROI, view, color, randcols outputs: M0: ROIs that are True in iscell M1: ROIs that are False in iscell """ stat = parent.stat iscell = parent.iscell cols = parent.colors['cols'] ncells = len(stat) Ly = parent.Ly Lx = parent.Lx parent.rois['Sroi'] = np.zeros((2,Ly,Lx), 'bool') LamAll = np.zeros((Ly,Lx), np.float32) # these have 3 layers parent.rois['Lam'] = np.zeros((2,3,Ly,Lx), np.float32) parent.rois['iROI'] = -1 * np.ones((2,3,Ly,Lx), np.int32) for n in range(len(parent.roi_text_labels)): parent.checkBoxN.setChecked(False) try: parent.p1.removeItem(parent.roi_text_labels[n]) except: pass try: parent.p2.removeItem(parent.roi_text_labels[n]) except: pass # ignore merged cells iignore = np.zeros(ncells, 'bool') parent.roi_text_labels = [] for n in np.arange(ncells-1,-1,-1,int): ypix = stat[n]['ypix'] if ypix is not None and not iignore[n]: if 'imerge' in stat[n]: for k in stat[n]['imerge']: iignore[k] = True print(k) xpix = stat[n]['xpix'] lam = stat[n]['lam'] lam = lam / lam.sum() i = int(1-iscell[n]) # add cell on top parent.rois['iROI'][i,2,ypix,xpix] = parent.rois['iROI'][i,1,ypix,xpix] parent.rois['iROI'][i,1,ypix,xpix] = parent.rois['iROI'][i,0,ypix,xpix] parent.rois['iROI'][i,0,ypix,xpix] = n # add weighting to all layers parent.rois['Lam'][i,2,ypix,xpix] = parent.rois['Lam'][i,1,ypix,xpix] parent.rois['Lam'][i,1,ypix,xpix] = parent.rois['Lam'][i,0,ypix,xpix] parent.rois['Lam'][i,0,ypix,xpix] = lam parent.rois['Sroi'][i,ypix,xpix] = 1 LamAll[ypix,xpix] = lam med = stat[n]['med'] cell_str = str(n) else: cell_str = '' med = (0,0) txt = pg.TextItem(cell_str, color=(180,180,180), anchor=(0.5,0.5)) txt.setPos(med[1], med[0]) txt.setFont(QtGui.QFont("Times", 8, weight=QtGui.QFont.Bold)) parent.roi_text_labels.append(txt) parent.roi_text_labels = parent.roi_text_labels[::-1] parent.rois['LamMean'] = LamAll[LamAll>1e-10].mean() parent.rois['LamNorm'] = np.maximum(0, np.minimum(1, 0.75*parent.rois['Lam'][:,0]/parent.rois['LamMean'])) parent.colors['RGB'] = np.zeros((2,cols.shape[0],Ly,Lx,4), np.uint8) for c in range(0, cols.shape[0]): rgb_masks(parent, cols[c], c)
[ "def", "init_masks", "(", "parent", ")", ":", "stat", "=", "parent", ".", "stat", "iscell", "=", "parent", ".", "iscell", "cols", "=", "parent", ".", "colors", "[", "'cols'", "]", "ncells", "=", "len", "(", "stat", ")", "Ly", "=", "parent", ".", "L...
https://github.com/MouseLand/suite2p/blob/12dc119ac0c7c4355e9cd3e07bebc447755623e4/suite2p/gui/masks.py#L207-L286
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/multiprocessing/process.py
python
BaseProcess.daemon
(self)
return self._config.get('daemon', False)
Return whether process is a daemon
Return whether process is a daemon
[ "Return", "whether", "process", "is", "a", "daemon" ]
def daemon(self): ''' Return whether process is a daemon ''' return self._config.get('daemon', False)
[ "def", "daemon", "(", "self", ")", ":", "return", "self", ".", "_config", ".", "get", "(", "'daemon'", ",", "False", ")" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/multiprocessing/process.py#L147-L151
aio-libs/aioredis-py
56d6b325ee246a3eb0fc8bb6803247c86bb2f494
aioredis/client.py
python
Redis.acl_load
(self)
return self.execute_command("ACL LOAD")
Load ACL rules from the configured ``aclfile``. Note that the server must be configured with the ``aclfile`` directive to be able to load ACL rules from an aclfile.
Load ACL rules from the configured ``aclfile``.
[ "Load", "ACL", "rules", "from", "the", "configured", "aclfile", "." ]
def acl_load(self) -> Awaitable: """ Load ACL rules from the configured ``aclfile``. Note that the server must be configured with the ``aclfile`` directive to be able to load ACL rules from an aclfile. """ return self.execute_command("ACL LOAD")
[ "def", "acl_load", "(", "self", ")", "->", "Awaitable", ":", "return", "self", ".", "execute_command", "(", "\"ACL LOAD\"", ")" ]
https://github.com/aio-libs/aioredis-py/blob/56d6b325ee246a3eb0fc8bb6803247c86bb2f494/aioredis/client.py#L1169-L1176
AndrewAnnex/SpiceyPy
9f8b626338f119bacd39ef2ba94a6f71bd6341c0
src/spiceypy/spiceypy.py
python
b1900
()
return libspice.b1900_c()
Return the Julian Date corresponding to Besselian Date 1900.0. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/b1900_c.html :return: The Julian Date corresponding to Besselian Date 1900.0.
Return the Julian Date corresponding to Besselian Date 1900.0.
[ "Return", "the", "Julian", "Date", "corresponding", "to", "Besselian", "Date", "1900", ".", "0", "." ]
def b1900() -> float: """ Return the Julian Date corresponding to Besselian Date 1900.0. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/b1900_c.html :return: The Julian Date corresponding to Besselian Date 1900.0. """ return libspice.b1900_c()
[ "def", "b1900", "(", ")", "->", "float", ":", "return", "libspice", ".", "b1900_c", "(", ")" ]
https://github.com/AndrewAnnex/SpiceyPy/blob/9f8b626338f119bacd39ef2ba94a6f71bd6341c0/src/spiceypy/spiceypy.py#L363-L371
HazyResearch/fonduer
c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd
src/fonduer/utils/utils_visual.py
python
bbox_vert_aligned
(box1: Bbox, box2: Bbox)
return not (box1_left > box2_right or box2_left > box1_right)
Check two bounding boxes are vertical aligned. Return true if the horizontal center point of either span is within the horizontal range of the other
Check two bounding boxes are vertical aligned.
[ "Check", "two", "bounding", "boxes", "are", "vertical", "aligned", "." ]
def bbox_vert_aligned(box1: Bbox, box2: Bbox) -> bool: """Check two bounding boxes are vertical aligned. Return true if the horizontal center point of either span is within the horizontal range of the other """ if not (box1 and box2): return False # NEW: any overlap counts # return box1.left <= box2.right and box2.left <= box1.right box1_left = box1.left + 1.5 box2_left = box2.left + 1.5 box1_right = box1.right - 1.5 box2_right = box2.right - 1.5 return not (box1_left > box2_right or box2_left > box1_right)
[ "def", "bbox_vert_aligned", "(", "box1", ":", "Bbox", ",", "box2", ":", "Bbox", ")", "->", "bool", ":", "if", "not", "(", "box1", "and", "box2", ")", ":", "return", "False", "# NEW: any overlap counts", "# return box1.left <= box2.right and box2.left <= box1.righ...
https://github.com/HazyResearch/fonduer/blob/c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd/src/fonduer/utils/utils_visual.py#L89-L103
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
consul/datadog_checks/consul/config_models/defaults.py
python
instance_timeout
(field, value)
return 10
[]
def instance_timeout(field, value): return 10
[ "def", "instance_timeout", "(", "field", ",", "value", ")", ":", "return", "10" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/consul/datadog_checks/consul/config_models/defaults.py#L189-L190
bulik/ldsc
aa33296abac9569a6422ee6ba7eb4b902422cc74
ldscore/sumstats.py
python
_merge_and_log
(ld, sumstats, noun, log)
return sumstats
Wrap smart merge with log messages about # of SNPs.
Wrap smart merge with log messages about # of SNPs.
[ "Wrap", "smart", "merge", "with", "log", "messages", "about", "#", "of", "SNPs", "." ]
def _merge_and_log(ld, sumstats, noun, log): '''Wrap smart merge with log messages about # of SNPs.''' sumstats = smart_merge(ld, sumstats) msg = 'After merging with {F}, {N} SNPs remain.' if len(sumstats) == 0: raise ValueError(msg.format(N=len(sumstats), F=noun)) else: log.log(msg.format(N=len(sumstats), F=noun)) return sumstats
[ "def", "_merge_and_log", "(", "ld", ",", "sumstats", ",", "noun", ",", "log", ")", ":", "sumstats", "=", "smart_merge", "(", "ld", ",", "sumstats", ")", "msg", "=", "'After merging with {F}, {N} SNPs remain.'", "if", "len", "(", "sumstats", ")", "==", "0", ...
https://github.com/bulik/ldsc/blob/aa33296abac9569a6422ee6ba7eb4b902422cc74/ldscore/sumstats.py#L229-L238
Cimbali/pympress
d376c92ede603a305738bd38f0c50b2f68c58fcf
pympress/media_overlays/base.py
python
VideoOverlay.handle_embed
(self, mapped_widget)
return False
Handler to embed the video player in the window, connected to the :attr:`~.Gtk.Widget.signals.map` signal.
Handler to embed the video player in the window, connected to the :attr:`~.Gtk.Widget.signals.map` signal.
[ "Handler", "to", "embed", "the", "video", "player", "in", "the", "window", "connected", "to", "the", ":", "attr", ":", "~", ".", "Gtk", ".", "Widget", ".", "signals", ".", "map", "signal", "." ]
def handle_embed(self, mapped_widget): """ Handler to embed the video player in the window, connected to the :attr:`~.Gtk.Widget.signals.map` signal. """ return False
[ "def", "handle_embed", "(", "self", ",", "mapped_widget", ")", ":", "return", "False" ]
https://github.com/Cimbali/pympress/blob/d376c92ede603a305738bd38f0c50b2f68c58fcf/pympress/media_overlays/base.py#L102-L105
isce-framework/isce2
0e5114a8bede3caf1d533d98e44dfe4b983e3f48
setup/setup.py
python
ISCEDeps.download
(self)
Download the dependencies specified in self.toDownload
Download the dependencies specified in self.toDownload
[ "Download", "the", "dependencies", "specified", "in", "self", ".", "toDownload" ]
def download(self): """ Download the dependencies specified in self.toDownload """ global WORKING for dep in self.toDownload: item = self.urlitems[dep] for url in item.urls: urlpath, fname = os.path.split(url) print2log("Downloading %s from %s to %s" % (fname, urlpath, self.paths.src)) WORKING = barthread.BarThread() response = downloadfile(url, item.destfile, repeat=2) if response: if os.path.exists(item.destfile): self.dependency_log["downloaded"].append(item.name) WORKING.stop() WORKING = None break else: continue if not os.path.exists(item.destfile): msg = "Cannot download %s. Please check your internet connection and make sure that the download url for %s in %s.py is correct.\n" msg += "You might also consider installing the package manually: see tutorial." % (fname, item.name, SETUP_CONFIG) print2log(msg) sys.exit(1)
[ "def", "download", "(", "self", ")", ":", "global", "WORKING", "for", "dep", "in", "self", ".", "toDownload", ":", "item", "=", "self", ".", "urlitems", "[", "dep", "]", "for", "url", "in", "item", ".", "urls", ":", "urlpath", ",", "fname", "=", "o...
https://github.com/isce-framework/isce2/blob/0e5114a8bede3caf1d533d98e44dfe4b983e3f48/setup/setup.py#L564-L588
kbandla/dpkt
7a91ae53bb20563607f32e6781ef40d2efe6520d
dpkt/radius.py
python
parse_attrs
(buf)
return attrs
Parse attributes buffer into a list of (type, data) tuples.
Parse attributes buffer into a list of (type, data) tuples.
[ "Parse", "attributes", "buffer", "into", "a", "list", "of", "(", "type", "data", ")", "tuples", "." ]
def parse_attrs(buf): """Parse attributes buffer into a list of (type, data) tuples.""" attrs = [] while buf: t = compat_ord(buf[0]) l_ = compat_ord(buf[1]) if l_ < 2: break d, buf = buf[2:l_], buf[l_:] attrs.append((t, d)) return attrs
[ "def", "parse_attrs", "(", "buf", ")", ":", "attrs", "=", "[", "]", "while", "buf", ":", "t", "=", "compat_ord", "(", "buf", "[", "0", "]", ")", "l_", "=", "compat_ord", "(", "buf", "[", "1", "]", ")", "if", "l_", "<", "2", ":", "break", "d",...
https://github.com/kbandla/dpkt/blob/7a91ae53bb20563607f32e6781ef40d2efe6520d/dpkt/radius.py#L37-L47
yaleimeng/Final_word_Similarity
e50bfe10d417db4b3097aecf1265faa29b8fa1bb
cilin/V1/ciLin.py
python
CilinSimilarity.sim2016_by_code
(self, c1, c2)
return cur_sim
根据编码计算相似度
根据编码计算相似度
[ "根据编码计算相似度" ]
def sim2016_by_code(self, c1, c2): """ 根据编码计算相似度 """ # 先把code的层级信息提取出来 clayer1 = self.code_layer(c1) clayer2 = self.code_layer(c2) common_str = self.get_common_str(c1, c2) # print('common_str: ', common_str) length = len(common_str) # 如果有一个编码以'@'结尾,那么表示自我封闭,这个编码中只有一个词,直接返回f if c1.endswith('@') or c2.endswith('@') or 0 == length: return self.f cur_sim = 0 if 7 <= length: # 如果前面七个字符相同,则第八个字符也相同,要么同为'=',要么同为'#'' if c1.endswith('=') and c2.endswith('='): cur_sim = 1 elif c1.endswith('#') and c2.endswith('#'): cur_sim = self.e else: # 从这里开始要改,这之前都一样 k = self.get_k(clayer1, clayer2) n = self.get_n(common_str) d = self.dist2016(common_str) e = math.sqrt(self.epow(-1 * k / (2 * n))) cur_sim = (1.05 0.05 * d) * e return cur_sim
[ "def", "sim2016_by_code", "(", "self", ",", "c1", ",", "c2", ")", ":", "# 先把code的层级信息提取出来", "clayer1", "=", "self", ".", "code_layer", "(", "c1", ")", "clayer2", "=", "self", ".", "code_layer", "(", "c2", ")", "common_str", "=", "self", ".", "get_common_...
https://github.com/yaleimeng/Final_word_Similarity/blob/e50bfe10d417db4b3097aecf1265faa29b8fa1bb/cilin/V1/ciLin.py#L147-L179
kristovatlas/osx-config-check
7ab816d52d818a770b712ad0652e7bd7457ffd15
const.py
python
_const.__setattr__
(self, name, value)
[]
def __setattr__(self, name, value): if self.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)" % name self.__dict__[name] = value
[ "def", "__setattr__", "(", "self", ",", "name", ",", "value", ")", ":", "if", "self", ".", "__dict__", ".", "has_key", "(", "name", ")", ":", "raise", "self", ".", "ConstError", ",", "\"Can't rebind const(%s)\"", "%", "name", "self", ".", "__dict__", "["...
https://github.com/kristovatlas/osx-config-check/blob/7ab816d52d818a770b712ad0652e7bd7457ffd15/const.py#L11-L14
prody/ProDy
b24bbf58aa8fffe463c8548ae50e3955910e5b7f
prody/atomic/atomgroup.py
python
AtomGroup.numBytes
(self, all=False)
return sum(getbase(arr).nbytes for arr in arrays.values())
Returns number of bytes used by atomic data arrays, such as coordinate, flag, and attribute arrays. If *all* is **True**, internal arrays for indexing hierarchical views, bonds, and fragments will also be included. Note that memory usage of Python objects is not taken into account and that this may change in the future.
Returns number of bytes used by atomic data arrays, such as coordinate, flag, and attribute arrays. If *all* is **True**, internal arrays for indexing hierarchical views, bonds, and fragments will also be included. Note that memory usage of Python objects is not taken into account and that this may change in the future.
[ "Returns", "number", "of", "bytes", "used", "by", "atomic", "data", "arrays", "such", "as", "coordinate", "flag", "and", "attribute", "arrays", ".", "If", "*", "all", "*", "is", "**", "True", "**", "internal", "arrays", "for", "indexing", "hierarchical", "...
def numBytes(self, all=False): """Returns number of bytes used by atomic data arrays, such as coordinate, flag, and attribute arrays. If *all* is **True**, internal arrays for indexing hierarchical views, bonds, and fragments will also be included. Note that memory usage of Python objects is not taken into account and that this may change in the future.""" arrays = {} getbase = lambda arr: arr if arr.base is None else getbase(arr.base) getpair = lambda arr: (id(arr), arr) getboth = lambda arr: getpair(getbase(arr)) if self._coords is not None: arrays[id(self._coords)] = self._coords arrays.update(getboth(val) for key, val in self._data.items() if val is not None) if self._bonds is not None: arrays[id(self._bonds)] = self._bonds if self._angles is not None: arrays[id(self._angles)] = self._angles if self._dihedrals is not None: arrays[id(self._dihedrals)] = self._dihedrals if self._impropers is not None: arrays[id(self._impropers)] = self._impropers if self._flags: arrays.update(getboth(val) for key, val in self._flags.items() if val is not None) if all: if self._subsets: arrays.update(getboth(val) for key, val in self._subsets.items() if val is not None) if self._fragments: for val in self._fragments: val = getbase(val) arrays[id(val)] = val if self._bmap is not None: arrays[id(self._bonds)] = self._bmap if self._hv is not None: arrays.update(getboth(val) if hasattr(val, 'base') else getboth(val._indices) for val in self._hv._residues) arrays.update(getboth(val) if hasattr(val, 'base') else getboth(val._indices) for val in self._hv._chains) arrays.update(getboth(val) if hasattr(val, 'base') else getboth(val._indices) for val in self._hv._segments) return sum(getbase(arr).nbytes for arr in arrays.values())
[ "def", "numBytes", "(", "self", ",", "all", "=", "False", ")", ":", "arrays", "=", "{", "}", "getbase", "=", "lambda", "arr", ":", "arr", "if", "arr", ".", "base", "is", "None", "else", "getbase", "(", "arr", ".", "base", ")", "getpair", "=", "la...
https://github.com/prody/ProDy/blob/b24bbf58aa8fffe463c8548ae50e3955910e5b7f/prody/atomic/atomgroup.py#L670-L716
shaneshixiang/rllabplusplus
4d55f96ec98e3fe025b7991945e3e6a54fd5449f
rllab/rllab_mujoco_py/glfw.py
python
set_gamma
(monitor, gamma)
Generates a gamma ramp and sets it for the specified monitor. Wrapper for: void glfwSetGamma(GLFWmonitor* monitor, float gamma);
Generates a gamma ramp and sets it for the specified monitor.
[ "Generates", "a", "gamma", "ramp", "and", "sets", "it", "for", "the", "specified", "monitor", "." ]
def set_gamma(monitor, gamma): ''' Generates a gamma ramp and sets it for the specified monitor. Wrapper for: void glfwSetGamma(GLFWmonitor* monitor, float gamma); ''' _glfw.glfwSetGamma(monitor, gamma)
[ "def", "set_gamma", "(", "monitor", ",", "gamma", ")", ":", "_glfw", ".", "glfwSetGamma", "(", "monitor", ",", "gamma", ")" ]
https://github.com/shaneshixiang/rllabplusplus/blob/4d55f96ec98e3fe025b7991945e3e6a54fd5449f/rllab/rllab_mujoco_py/glfw.py#L720-L727
hyperledger/sawtooth-core
704cd5837c21f53642c06ffc97ba7978a77940b0
validator/sawtooth_validator/journal/block_store.py
python
BlockStore.get_batch
(self, batch_id)
return batch
Check to see if the requested batch_id is in the current chain. If so, find the batch with the batch_id and return it. This is done by finding the block and searching for the batch. :param batch_id (string): The id of the batch requested. :return: The batch with the batch_id.
Check to see if the requested batch_id is in the current chain. If so, find the batch with the batch_id and return it. This is done by finding the block and searching for the batch.
[ "Check", "to", "see", "if", "the", "requested", "batch_id", "is", "in", "the", "current", "chain", ".", "If", "so", "find", "the", "batch", "with", "the", "batch_id", "and", "return", "it", ".", "This", "is", "done", "by", "finding", "the", "block", "a...
def get_batch(self, batch_id): """ Check to see if the requested batch_id is in the current chain. If so, find the batch with the batch_id and return it. This is done by finding the block and searching for the batch. :param batch_id (string): The id of the batch requested. :return: The batch with the batch_id. """ payload = self._get_data_by_id(batch_id, 'commit_store_get_batch') batch = Batch() batch.ParseFromString(payload) return batch
[ "def", "get_batch", "(", "self", ",", "batch_id", ")", ":", "payload", "=", "self", ".", "_get_data_by_id", "(", "batch_id", ",", "'commit_store_get_batch'", ")", "batch", "=", "Batch", "(", ")", "batch", ".", "ParseFromString", "(", "payload", ")", "return"...
https://github.com/hyperledger/sawtooth-core/blob/704cd5837c21f53642c06ffc97ba7978a77940b0/validator/sawtooth_validator/journal/block_store.py#L368-L384
mariostoev/finviz
1c421ac17f1c8932b00bde17d1065aecb635347e
finviz/helper_functions/request_functions.py
python
Connector.__http_request__async
( self, url: str, session: aiohttp.ClientSession, )
Sends asynchronous http request to URL address and scrapes the webpage.
Sends asynchronous http request to URL address and scrapes the webpage.
[ "Sends", "asynchronous", "http", "request", "to", "URL", "address", "and", "scrapes", "the", "webpage", "." ]
async def __http_request__async( self, url: str, session: aiohttp.ClientSession, ): """ Sends asynchronous http request to URL address and scrapes the webpage. """ try: async with session.get( url, headers={"User-Agent": self.user_agent} ) as response: page_html = await response.read() if page_html.decode("utf-8") == "Too many requests.": raise Exception("Too many requests.") if self.css_select: return self.scrape_function( html.fromstring(page_html), *self.arguments ) return self.scrape_function(page_html, *self.arguments) except (asyncio.TimeoutError, requests.exceptions.Timeout): raise ConnectionTimeout(url)
[ "async", "def", "__http_request__async", "(", "self", ",", "url", ":", "str", ",", "session", ":", "aiohttp", ".", "ClientSession", ",", ")", ":", "try", ":", "async", "with", "session", ".", "get", "(", "url", ",", "headers", "=", "{", "\"User-Agent\"",...
https://github.com/mariostoev/finviz/blob/1c421ac17f1c8932b00bde17d1065aecb635347e/finviz/helper_functions/request_functions.py#L95-L117
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/email/mime/application.py
python
MIMEApplication.__init__
(self, _data, _subtype='octet-stream', _encoder=encoders.encode_base64, *, policy=None, **_params)
Create an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.
Create an application/* type MIME document.
[ "Create", "an", "application", "/", "*", "type", "MIME", "document", "." ]
def __init__(self, _data, _subtype='octet-stream', _encoder=encoders.encode_base64, *, policy=None, **_params): """Create an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: raise TypeError('Invalid application MIME subtype') MIMENonMultipart.__init__(self, 'application', _subtype, policy=policy, **_params) self.set_payload(_data) _encoder(self)
[ "def", "__init__", "(", "self", ",", "_data", ",", "_subtype", "=", "'octet-stream'", ",", "_encoder", "=", "encoders", ".", "encode_base64", ",", "*", ",", "policy", "=", "None", ",", "*", "*", "_params", ")", ":", "if", "_subtype", "is", "None", ":",...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/email/mime/application.py#L16-L37
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/devops_sdk/v6_0/build/build_client.py
python
BuildClient.get_build_timeline
(self, project, build_id, timeline_id=None, change_id=None, plan_id=None)
return self._deserialize('Timeline', response)
GetBuildTimeline. [Preview API] Gets details for a build :param str project: Project ID or project name :param int build_id: :param str timeline_id: :param int change_id: :param str plan_id: :rtype: :class:`<Timeline> <azure.devops.v6_0.build.models.Timeline>`
GetBuildTimeline. [Preview API] Gets details for a build :param str project: Project ID or project name :param int build_id: :param str timeline_id: :param int change_id: :param str plan_id: :rtype: :class:`<Timeline> <azure.devops.v6_0.build.models.Timeline>`
[ "GetBuildTimeline", ".", "[", "Preview", "API", "]", "Gets", "details", "for", "a", "build", ":", "param", "str", "project", ":", "Project", "ID", "or", "project", "name", ":", "param", "int", "build_id", ":", ":", "param", "str", "timeline_id", ":", ":"...
def get_build_timeline(self, project, build_id, timeline_id=None, change_id=None, plan_id=None): """GetBuildTimeline. [Preview API] Gets details for a build :param str project: Project ID or project name :param int build_id: :param str timeline_id: :param int change_id: :param str plan_id: :rtype: :class:`<Timeline> <azure.devops.v6_0.build.models.Timeline>` """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') if build_id is not None: route_values['buildId'] = self._serialize.url('build_id', build_id, 'int') if timeline_id is not None: route_values['timelineId'] = self._serialize.url('timeline_id', timeline_id, 'str') query_parameters = {} if change_id is not None: query_parameters['changeId'] = self._serialize.query('change_id', change_id, 'int') if plan_id is not None: query_parameters['planId'] = self._serialize.query('plan_id', plan_id, 'str') response = self._send(http_method='GET', location_id='8baac422-4c6e-4de5-8532-db96d92acffa', version='6.0-preview.2', route_values=route_values, query_parameters=query_parameters) return self._deserialize('Timeline', response)
[ "def", "get_build_timeline", "(", "self", ",", "project", ",", "build_id", ",", "timeline_id", "=", "None", ",", "change_id", "=", "None", ",", "plan_id", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", ...
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v6_0/build/build_client.py#L2026-L2053
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/colors.py
python
LightSource.shade_normals
(self, normals, fraction=1.)
return intensity
Calculate the illumination intensity for the normal vectors of a surface using the defined azimuth and elevation for the light source. Imagine an artificial sun placed at infinity in some azimuth and elevation position illuminating our surface. The parts of the surface that slope toward the sun should brighten while those sides facing away should become darker. Parameters ---------- fraction : number, optional Increases or decreases the contrast of the hillshade. Values greater than one will cause intermediate values to move closer to full illumination or shadow (and clipping any values that move beyond 0 or 1). Note that this is not visually or mathematically the same as vertical exaggeration. Returns ------- ndarray A 2D array of illumination values between 0-1, where 0 is completely in shadow and 1 is completely illuminated.
Calculate the illumination intensity for the normal vectors of a surface using the defined azimuth and elevation for the light source.
[ "Calculate", "the", "illumination", "intensity", "for", "the", "normal", "vectors", "of", "a", "surface", "using", "the", "defined", "azimuth", "and", "elevation", "for", "the", "light", "source", "." ]
def shade_normals(self, normals, fraction=1.): """ Calculate the illumination intensity for the normal vectors of a surface using the defined azimuth and elevation for the light source. Imagine an artificial sun placed at infinity in some azimuth and elevation position illuminating our surface. The parts of the surface that slope toward the sun should brighten while those sides facing away should become darker. Parameters ---------- fraction : number, optional Increases or decreases the contrast of the hillshade. Values greater than one will cause intermediate values to move closer to full illumination or shadow (and clipping any values that move beyond 0 or 1). Note that this is not visually or mathematically the same as vertical exaggeration. Returns ------- ndarray A 2D array of illumination values between 0-1, where 0 is completely in shadow and 1 is completely illuminated. """ intensity = normals.dot(self.direction) # Apply contrast stretch imin, imax = intensity.min(), intensity.max() intensity *= fraction # Rescale to 0-1, keeping range before contrast stretch # If constant slope, keep relative scaling (i.e. flat should be 0.5, # fully occluded 0, etc.) if (imax - imin) > 1e-6: # Strictly speaking, this is incorrect. Negative values should be # clipped to 0 because they're fully occluded. However, rescaling # in this manner is consistent with the previous implementation and # visually appears better than a "hard" clip. intensity -= imin intensity /= (imax - imin) intensity = np.clip(intensity, 0, 1) return intensity
[ "def", "shade_normals", "(", "self", ",", "normals", ",", "fraction", "=", "1.", ")", ":", "intensity", "=", "normals", ".", "dot", "(", "self", ".", "direction", ")", "# Apply contrast stretch", "imin", ",", "imax", "=", "intensity", ".", "min", "(", ")...
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/colors.py#L2126-L2170
prody/ProDy
b24bbf58aa8fffe463c8548ae50e3955910e5b7f
prody/database/goa.py
python
GOADictList.__iter__
(self)
Yield go_term instances.
Yield go_term instances.
[ "Yield", "go_term", "instances", "." ]
def __iter__(self): """Yield go_term instances.""" for item in self._list: yield item
[ "def", "__iter__", "(", "self", ")", ":", "for", "item", "in", "self", ".", "_list", ":", "yield", "item" ]
https://github.com/prody/ProDy/blob/b24bbf58aa8fffe463c8548ae50e3955910e5b7f/prody/database/goa.py#L79-L82
Tencent/bk-sops
2a6bd1573b7b42812cb8a5b00929e98ab916b18d
gcloud/taskflow3/apis/django/api.py
python
node_callback
(request, token)
return JsonResponse(callback_result)
old callback view, handle pipeline callback, will not longer use after 3.6.X+ version
old callback view, handle pipeline callback, will not longer use after 3.6.X+ version
[ "old", "callback", "view", "handle", "pipeline", "callback", "will", "not", "longer", "use", "after", "3", ".", "6", ".", "X", "+", "version" ]
def node_callback(request, token): """ old callback view, handle pipeline callback, will not longer use after 3.6.X+ version """ logger.info("[old_node_callback]callback body for token({}): {}".format(token, request.body)) try: f = Fernet(settings.CALLBACK_KEY) node_id = f.decrypt(bytes(token, encoding="utf8")).decode() except Exception: logger.warning("invalid token %s" % token) return JsonResponse({"result": False, "message": "invalid token"}, status=400) try: callback_data = json.loads(request.body) except Exception: logger.warning("node callback error: %s" % traceback.format_exc()) return JsonResponse({"result": False, "message": "invalid request body"}, status=400) # 老的回调接口,一定是老引擎的接口 dispatcher = NodeCommandDispatcher(engine_ver=EngineConfig.ENGINE_VER_V1, node_id=node_id) # 由于回调方不一定会进行多次回调,这里为了在业务层防止出现不可抗力(网络,DB 问题等)导致失败 # 增加失败重试机制 callback_result = None for __ in range(env.NODE_CALLBACK_RETRY_TIMES): callback_result = dispatcher.dispatch(command="callback", operator="", data=callback_data) logger.info("result of callback call({}): {}".format(token, callback_result)) if callback_result["result"]: break # 考虑callback时Process状态还没及时修改为sleep的情况 time.sleep(0.5) return JsonResponse(callback_result)
[ "def", "node_callback", "(", "request", ",", "token", ")", ":", "logger", ".", "info", "(", "\"[old_node_callback]callback body for token({}): {}\"", ".", "format", "(", "token", ",", "request", ".", "body", ")", ")", "try", ":", "f", "=", "Fernet", "(", "se...
https://github.com/Tencent/bk-sops/blob/2a6bd1573b7b42812cb8a5b00929e98ab916b18d/gcloud/taskflow3/apis/django/api.py#L467-L500
microsoft/NeuronBlocks
e30ed2384d6f7aad394069e79d08b3b69b6fd803
block_zoo/op/Combination.py
python
Combination.forward
(self, *args)
return torch.cat(result, last_dim), args[1]
process inputs Args: args (list): [string, string_len, string2, string2_len, ...] e.g. string (Variable): [batch_size, dim], string_len (ndarray): [batch_size] Returns: Variable: [batch_size, output_dim], None
process inputs
[ "process", "inputs" ]
def forward(self, *args): """ process inputs Args: args (list): [string, string_len, string2, string2_len, ...] e.g. string (Variable): [batch_size, dim], string_len (ndarray): [batch_size] Returns: Variable: [batch_size, output_dim], None """ result = [] if "origin" in self.layer_conf.operations: for idx, input in enumerate(args): if idx % 2 == 0: result.append(input) if "difference" in self.layer_conf.operations: result.append(torch.abs(args[0] - args[2])) if "dot_multiply" in self.layer_conf.operations: result_multiply = None for idx, input in enumerate(args): if idx % 2 == 0: if result_multiply is None: result_multiply = input else: result_multiply = result_multiply * input result.append(result_multiply) last_dim = len(args[0].size()) - 1 return torch.cat(result, last_dim), args[1]
[ "def", "forward", "(", "self", ",", "*", "args", ")", ":", "result", "=", "[", "]", "if", "\"origin\"", "in", "self", ".", "layer_conf", ".", "operations", ":", "for", "idx", ",", "input", "in", "enumerate", "(", "args", ")", ":", "if", "idx", "%",...
https://github.com/microsoft/NeuronBlocks/blob/e30ed2384d6f7aad394069e79d08b3b69b6fd803/block_zoo/op/Combination.py#L91-L122
chainer/chainerrl
7eed375614b46a986f0adfedcc8c61b5063e1d3e
chainerrl/agents/td3.py
python
TD3.update_q_func
(self, batch)
Compute loss for a given Q-function.
Compute loss for a given Q-function.
[ "Compute", "loss", "for", "a", "given", "Q", "-", "function", "." ]
def update_q_func(self, batch): """Compute loss for a given Q-function.""" batch_next_state = batch['next_state'] batch_rewards = batch['reward'] batch_terminal = batch['is_state_terminal'] batch_state = batch['state'] batch_actions = batch['action'] batch_discount = batch['discount'] with chainer.no_backprop_mode(), chainer.using_config('train', False): next_actions = self.target_policy_smoothing_func( self.target_policy(batch_next_state).sample().array) next_q1 = self.target_q_func1(batch_next_state, next_actions) next_q2 = self.target_q_func2(batch_next_state, next_actions) next_q = F.minimum(next_q1, next_q2) target_q = batch_rewards + batch_discount * \ (1.0 - batch_terminal) * F.flatten(next_q) predict_q1 = F.flatten(self.q_func1(batch_state, batch_actions)) predict_q2 = F.flatten(self.q_func2(batch_state, batch_actions)) loss1 = F.mean_squared_error(target_q, predict_q1) loss2 = F.mean_squared_error(target_q, predict_q2) # Update stats self.q1_record.extend(cuda.to_cpu(predict_q1.array)) self.q2_record.extend(cuda.to_cpu(predict_q2.array)) self.q_func1_loss_record.append(float(loss1.array)) self.q_func2_loss_record.append(float(loss2.array)) self.q_func1_optimizer.update(lambda: loss1) self.q_func2_optimizer.update(lambda: loss2)
[ "def", "update_q_func", "(", "self", ",", "batch", ")", ":", "batch_next_state", "=", "batch", "[", "'next_state'", "]", "batch_rewards", "=", "batch", "[", "'reward'", "]", "batch_terminal", "=", "batch", "[", "'is_state_terminal'", "]", "batch_state", "=", "...
https://github.com/chainer/chainerrl/blob/7eed375614b46a986f0adfedcc8c61b5063e1d3e/chainerrl/agents/td3.py#L180-L213
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/pstats.py
python
count_calls
(callers)
return nc
Sum the caller statistics to get total number of calls received.
Sum the caller statistics to get total number of calls received.
[ "Sum", "the", "caller", "statistics", "to", "get", "total", "number", "of", "calls", "received", "." ]
def count_calls(callers): """Sum the caller statistics to get total number of calls received.""" nc = 0 for calls in callers.values(): nc += calls return nc
[ "def", "count_calls", "(", "callers", ")", ":", "nc", "=", "0", "for", "calls", "in", "callers", ".", "values", "(", ")", ":", "nc", "+=", "calls", "return", "nc" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/pstats.py#L541-L546
YaoZeyuan/ZhihuHelp_archived
a0e4a7acd4512452022ce088fff2adc6f8d30195
src/lib/requests/packages/urllib3/poolmanager.py
python
_default_key_normalizer
(key_class, request_context)
return key_class(**context)
Create a pool key of type ``key_class`` for a request. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_scheme``. :param key_class: The class to use when constructing the key. This should be a namedtuple with the ``scheme`` and ``host`` keys at a minimum. :param request_context: A dictionary-like object that contain the context for a request. It should contain a key for each field in the :class:`HTTPPoolKey`
Create a pool key of type ``key_class`` for a request.
[ "Create", "a", "pool", "key", "of", "type", "key_class", "for", "a", "request", "." ]
def _default_key_normalizer(key_class, request_context): """ Create a pool key of type ``key_class`` for a request. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_scheme``. :param key_class: The class to use when constructing the key. This should be a namedtuple with the ``scheme`` and ``host`` keys at a minimum. :param request_context: A dictionary-like object that contain the context for a request. It should contain a key for each field in the :class:`HTTPPoolKey` """ context = {} for key in key_class._fields: context[key] = request_context.get(key) context['scheme'] = context['scheme'].lower() context['host'] = context['host'].lower() return key_class(**context)
[ "def", "_default_key_normalizer", "(", "key_class", ",", "request_context", ")", ":", "context", "=", "{", "}", "for", "key", "in", "key_class", ".", "_fields", ":", "context", "[", "key", "]", "=", "request_context", ".", "get", "(", "key", ")", "context"...
https://github.com/YaoZeyuan/ZhihuHelp_archived/blob/a0e4a7acd4512452022ce088fff2adc6f8d30195/src/lib/requests/packages/urllib3/poolmanager.py#L47-L69
blampe/IbPy
cba912d2ecc669b0bf2980357ea7942e49c0825e
ib/ext/EClientSocket.py
python
EClientSocket.replaceFA
(self, faDataType, xml)
generated source for method replaceFA
generated source for method replaceFA
[ "generated", "source", "for", "method", "replaceFA" ]
def replaceFA(self, faDataType, xml): """ generated source for method replaceFA """ # not connected? if not self.m_connected: self.notConnected() return # This feature is only available for versions of TWS >= 13 if self.m_serverVersion < 13: self.error(EClientErrors.NO_VALID_ID, EClientErrors.UPDATE_TWS.code(), EClientErrors.UPDATE_TWS.msg()) return VERSION = 1 try: self.send(self.REPLACE_FA) self.send(VERSION) self.send(faDataType) self.send(xml) except Exception as e: self.error(faDataType, EClientErrors.FAIL_SEND_FA_REPLACE, str(e)) self.close()
[ "def", "replaceFA", "(", "self", ",", "faDataType", ",", "xml", ")", ":", "# not connected?", "if", "not", "self", ".", "m_connected", ":", "self", ".", "notConnected", "(", ")", "return", "# This feature is only available for versions of TWS >= 13", "if", "self",...
https://github.com/blampe/IbPy/blob/cba912d2ecc669b0bf2980357ea7942e49c0825e/ib/ext/EClientSocket.py#L1374-L1392
mraardvark/pyupdi
4aa013e9ec4437af14af26189585ad594ab05164
updi/application.py
python
UpdiApplication.reset
(self, apply_reset)
Applies or releases an UPDI reset condition
Applies or releases an UPDI reset condition
[ "Applies", "or", "releases", "an", "UPDI", "reset", "condition" ]
def reset(self, apply_reset): """ Applies or releases an UPDI reset condition """ if apply_reset: self.logger.info("Apply reset") self.datalink.stcs(constants.UPDI_ASI_RESET_REQ, constants.UPDI_RESET_REQ_VALUE) self.logger.info("Check reset") sys_status = self.datalink.ldcs(constants.UPDI_ASI_SYS_STATUS) if not sys_status & (1 << constants.UPDI_ASI_SYS_STATUS_RSTSYS): raise("Error applying reset") else: self.logger.info("Release reset") self.datalink.stcs(constants.UPDI_ASI_RESET_REQ, 0x00) while True: # TODO - add timeout self.logger.info("Wait for !reset") sys_status = self.datalink.ldcs(constants.UPDI_ASI_SYS_STATUS) if not sys_status & (1 << constants.UPDI_ASI_SYS_STATUS_RSTSYS): break
[ "def", "reset", "(", "self", ",", "apply_reset", ")", ":", "if", "apply_reset", ":", "self", ".", "logger", ".", "info", "(", "\"Apply reset\"", ")", "self", ".", "datalink", ".", "stcs", "(", "constants", ".", "UPDI_ASI_RESET_REQ", ",", "constants", ".", ...
https://github.com/mraardvark/pyupdi/blob/4aa013e9ec4437af14af26189585ad594ab05164/updi/application.py#L180-L199
Yelp/pyleus
8ab87e2d18b8b6a7e0471ceefdbb3ff23a576cce
pyleus/configuration.py
python
update_configuration
(config, update_dict)
return Configuration(**tmp)
Update configuration with new values passed as dictionary. :return: new configuration ``namedtuple``
Update configuration with new values passed as dictionary.
[ "Update", "configuration", "with", "new", "values", "passed", "as", "dictionary", "." ]
def update_configuration(config, update_dict): """Update configuration with new values passed as dictionary. :return: new configuration ``namedtuple`` """ tmp = config._asdict() tmp.update(update_dict) return Configuration(**tmp)
[ "def", "update_configuration", "(", "config", ",", "update_dict", ")", ":", "tmp", "=", "config", ".", "_asdict", "(", ")", "tmp", ".", "update", "(", "update_dict", ")", "return", "Configuration", "(", "*", "*", "tmp", ")" ]
https://github.com/Yelp/pyleus/blob/8ab87e2d18b8b6a7e0471ceefdbb3ff23a576cce/pyleus/configuration.py#L107-L114
trailofbits/manticore
b050fdf0939f6c63f503cdf87ec0ab159dd41159
manticore/native/cpu/aarch64.py
python
Aarch64Cpu.CSINV
(cpu, res_op, reg_op1, reg_op2, cond=None)
CSINV. :param res_op: destination register. :param reg_op1: source register. :param reg_op2: source register.
CSINV.
[ "CSINV", "." ]
def CSINV(cpu, res_op, reg_op1, reg_op2, cond=None): """ CSINV. :param res_op: destination register. :param reg_op1: source register. :param reg_op2: source register. """ assert res_op.type is cs.arm64.ARM64_OP_REG assert reg_op1.type is cs.arm64.ARM64_OP_REG assert reg_op2.type is cs.arm64.ARM64_OP_REG insn_rx = "[01]" # sf insn_rx += "1" # op insn_rx += "0" insn_rx += "11010100" insn_rx += "[01]{5}" # Rm insn_rx += "[01]{4}" # cond insn_rx += "0" insn_rx += "0" # o2 insn_rx += "[01]{5}" # Rn insn_rx += "[01]{5}" # Rd assert re.match(insn_rx, cpu.insn_bit_str) reg1 = reg_op1.read() reg2 = reg_op2.read() cond = cond if cond else cpu.instruction.cc result = Operators.ITEBV(res_op.size, cpu.cond_holds(cond), reg1, ~reg2) res_op.write(UInt(result, res_op.size))
[ "def", "CSINV", "(", "cpu", ",", "res_op", ",", "reg_op1", ",", "reg_op2", ",", "cond", "=", "None", ")", ":", "assert", "res_op", ".", "type", "is", "cs", ".", "arm64", ".", "ARM64_OP_REG", "assert", "reg_op1", ".", "type", "is", "cs", ".", "arm64",...
https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/native/cpu/aarch64.py#L2794-L2825
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/setuptools/_vendor/packaging/markers.py
python
Marker.__init__
(self, marker)
[]
def __init__(self, marker): try: self._markers = _coerce_parse_result(MARKER.parseString(marker)) except ParseException as e: err_str = "Invalid marker: {0!r}, parse error at {1!r}".format( marker, marker[e.loc:e.loc + 8]) raise InvalidMarker(err_str)
[ "def", "__init__", "(", "self", ",", "marker", ")", ":", "try", ":", "self", ".", "_markers", "=", "_coerce_parse_result", "(", "MARKER", ".", "parseString", "(", "marker", ")", ")", "except", "ParseException", "as", "e", ":", "err_str", "=", "\"Invalid ma...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/setuptools/_vendor/packaging/markers.py#L274-L280
accel-brain/accel-brain-code
86f489dc9be001a3bae6d053f48d6b57c0bedb95
Accel-Brain-Base/accelbrainbase/observabledata/_mxnet/neuralnetworks/auto_encoder.py
python
AutoEncoder.set_init_deferred_flag
(self, value)
setter for `bool` that means initialization in this class will be deferred or not.
setter for `bool` that means initialization in this class will be deferred or not.
[ "setter", "for", "bool", "that", "means", "initialization", "in", "this", "class", "will", "be", "deferred", "or", "not", "." ]
def set_init_deferred_flag(self, value): ''' setter for `bool` that means initialization in this class will be deferred or not.''' self.__init_deferred_flag = value
[ "def", "set_init_deferred_flag", "(", "self", ",", "value", ")", ":", "self", ".", "__init_deferred_flag", "=", "value" ]
https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Accel-Brain-Base/accelbrainbase/observabledata/_mxnet/neuralnetworks/auto_encoder.py#L284-L286
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/Django-1.11.29/django/contrib/messages/api.py
python
get_level
(request)
return storage.level
Returns the minimum level of messages to be recorded. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, the ``INFO`` level is used.
Returns the minimum level of messages to be recorded.
[ "Returns", "the", "minimum", "level", "of", "messages", "to", "be", "recorded", "." ]
def get_level(request): """ Returns the minimum level of messages to be recorded. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, the ``INFO`` level is used. """ storage = getattr(request, '_messages', default_storage(request)) return storage.level
[ "def", "get_level", "(", "request", ")", ":", "storage", "=", "getattr", "(", "request", ",", "'_messages'", ",", "default_storage", "(", "request", ")", ")", "return", "storage", ".", "level" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/contrib/messages/api.py#L45-L53
psolin/cleanco
806bf5f2439b96d8b5b5e21af824d5c870aba168
cleanco/classify.py
python
countrysources
()
return sorted(countries, key=lambda part: len(part[1]), reverse=True)
business countries / type abbreviations sorted by length of type abbreviations
business countries / type abbreviations sorted by length of type abbreviations
[ "business", "countries", "/", "type", "abbreviations", "sorted", "by", "length", "of", "type", "abbreviations" ]
def countrysources(): "business countries / type abbreviations sorted by length of type abbreviations" countries = [] for country in terms_by_country: for item in terms_by_country[country]: countries.append((country, item)) return sorted(countries, key=lambda part: len(part[1]), reverse=True)
[ "def", "countrysources", "(", ")", ":", "countries", "=", "[", "]", "for", "country", "in", "terms_by_country", ":", "for", "item", "in", "terms_by_country", "[", "country", "]", ":", "countries", ".", "append", "(", "(", "country", ",", "item", ")", ")"...
https://github.com/psolin/cleanco/blob/806bf5f2439b96d8b5b5e21af824d5c870aba168/cleanco/classify.py#L34-L41
Kozea/WeasyPrint
6cce2978165134e37683cb5b3d156cac6a11a7f9
weasyprint/css/validation/__init__.py
python
preprocess_declarations
(base_url, declarations)
Expand shorthand properties, filter unsupported properties and values. Log a warning for every ignored declaration. Return a iterable of ``(name, value, important)`` tuples.
Expand shorthand properties, filter unsupported properties and values.
[ "Expand", "shorthand", "properties", "filter", "unsupported", "properties", "and", "values", "." ]
def preprocess_declarations(base_url, declarations): """Expand shorthand properties, filter unsupported properties and values. Log a warning for every ignored declaration. Return a iterable of ``(name, value, important)`` tuples. """ for declaration in declarations: if declaration.type == 'error': LOGGER.warning( 'Error: %s at %d:%d.', declaration.message, declaration.source_line, declaration.source_column) if declaration.type != 'declaration': continue name = declaration.name if not name.startswith('--'): name = declaration.lower_name def validation_error(level, reason): getattr(LOGGER, level)( 'Ignored `%s:%s` at %d:%d, %s.', declaration.name, serialize(declaration.value), declaration.source_line, declaration.source_column, reason) if name in NOT_PRINT_MEDIA: validation_error( 'debug', 'the property does not apply for the print media') continue if name.startswith(PREFIX): unprefixed_name = name[len(PREFIX):] if unprefixed_name in PROPRIETARY: name = unprefixed_name elif unprefixed_name in UNSTABLE: LOGGER.warning( 'Deprecated `%s:%s` at %d:%d, ' 'prefixes on unstable attributes are deprecated, ' 'use %r instead.', declaration.name, serialize(declaration.value), declaration.source_line, declaration.source_column, unprefixed_name) name = unprefixed_name else: LOGGER.warning( 'Ignored `%s:%s` at %d:%d, ' 'prefix on this attribute is not supported, ' 'use %r instead.', declaration.name, serialize(declaration.value), declaration.source_line, declaration.source_column, unprefixed_name) continue if name.startswith('-') and not name.startswith('--'): validation_error('debug', 'prefixed selectors are ignored') continue expander_ = EXPANDERS.get(name, validate_non_shorthand) tokens = remove_whitespace(declaration.value) try: # Use list() to consume generators now and catch any error. result = list(expander_(base_url, name, tokens)) except InvalidValues as exc: validation_error( 'warning', exc.args[0] if exc.args and exc.args[0] else 'invalid value') continue important = declaration.important for long_name, value in result: yield long_name.replace('-', '_'), value, important
[ "def", "preprocess_declarations", "(", "base_url", ",", "declarations", ")", ":", "for", "declaration", "in", "declarations", ":", "if", "declaration", ".", "type", "==", "'error'", ":", "LOGGER", ".", "warning", "(", "'Error: %s at %d:%d.'", ",", "declaration", ...
https://github.com/Kozea/WeasyPrint/blob/6cce2978165134e37683cb5b3d156cac6a11a7f9/weasyprint/css/validation/__init__.py#L60-L133
zhanlaoban/Transformers_for_Text_Classification
5e12b21616b29e445e11fe307948e5c55084bb0e
transformers/tokenization_t5.py
python
T5Tokenizer._convert_id_to_token
(self, index, return_unicode=True)
return token
Converts an index (integer) in a token (string/unicode) using the vocab.
Converts an index (integer) in a token (string/unicode) using the vocab.
[ "Converts", "an", "index", "(", "integer", ")", "in", "a", "token", "(", "string", "/", "unicode", ")", "using", "the", "vocab", "." ]
def _convert_id_to_token(self, index, return_unicode=True): """Converts an index (integer) in a token (string/unicode) using the vocab.""" if index < self.sp_model.get_piece_size(): token = self.sp_model.IdToPiece(index) else: token = u"<extra_id_{}>".format(self.vocab_size - 1 - index) if six.PY2 and return_unicode and isinstance(token, str): token = token.decode('utf-8') return token
[ "def", "_convert_id_to_token", "(", "self", ",", "index", ",", "return_unicode", "=", "True", ")", ":", "if", "index", "<", "self", ".", "sp_model", ".", "get_piece_size", "(", ")", ":", "token", "=", "self", ".", "sp_model", ".", "IdToPiece", "(", "inde...
https://github.com/zhanlaoban/Transformers_for_Text_Classification/blob/5e12b21616b29e445e11fe307948e5c55084bb0e/transformers/tokenization_t5.py#L149-L157
happinesslz/TANet
2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f
pointpillars_with_TANet/second/data/preprocess.py
python
_read_and_prep_v9
(info, root_path, num_point_features, prep_func)
return example
read data from KITTI-format infos, then call prep function.
read data from KITTI-format infos, then call prep function.
[ "read", "data", "from", "KITTI", "-", "format", "infos", "then", "call", "prep", "function", "." ]
def _read_and_prep_v9(info, root_path, num_point_features, prep_func): """read data from KITTI-format infos, then call prep function. """ # velodyne_path = str(pathlib.Path(root_path) / info['velodyne_path']) # velodyne_path += '_reduced' v_path = pathlib.Path(root_path) / info['velodyne_path'] v_path = v_path.parent.parent / ( v_path.parent.stem + "_reduced") / v_path.name points = np.fromfile( str(v_path), dtype=np.float32, count=-1).reshape([-1, num_point_features]) image_idx = info['image_idx'] rect = info['calib/R0_rect'].astype(np.float32) Trv2c = info['calib/Tr_velo_to_cam'].astype(np.float32) P2 = info['calib/P2'].astype(np.float32) input_dict = { 'points': points, 'rect': rect, 'Trv2c': Trv2c, 'P2': P2, 'image_shape': np.array(info["img_shape"], dtype=np.int32), 'image_idx': image_idx, 'image_path': info['img_path'], # 'pointcloud_num_features': num_point_features, } if 'annos' in info: annos = info['annos'] # we need other objects to avoid collision when sample annos = kitti.remove_dontcare(annos) loc = annos["location"] dims = annos["dimensions"] rots = annos["rotation_y"] gt_names = annos["name"] # print(gt_names, len(loc)) gt_boxes = np.concatenate( [loc, dims, rots[..., np.newaxis]], axis=1).astype(np.float32) # gt_boxes = box_np_ops.box_camera_to_lidar(gt_boxes, rect, Trv2c) difficulty = annos["difficulty"] input_dict.update({ 'gt_boxes': gt_boxes, 'gt_names': gt_names, 'difficulty': difficulty, }) if 'group_ids' in annos: input_dict['group_ids'] = annos["group_ids"] example = prep_func(input_dict=input_dict) example["image_idx"] = image_idx example["image_shape"] = input_dict["image_shape"] if "anchors_mask" in example: example["anchors_mask"] = example["anchors_mask"].astype(np.uint8) return example
[ "def", "_read_and_prep_v9", "(", "info", ",", "root_path", ",", "num_point_features", ",", "prep_func", ")", ":", "# velodyne_path = str(pathlib.Path(root_path) / info['velodyne_path'])", "# velodyne_path += '_reduced'", "v_path", "=", "pathlib", ".", "Path", "(", "root_path"...
https://github.com/happinesslz/TANet/blob/2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f/pointpillars_with_TANet/second/data/preprocess.py#L306-L359
mcfletch/pyopengl
02d11dad9ff18e50db10e975c4756e17bf198464
OpenGL/GL/images.py
python
CompressedImageConverter.finalise
( self, wrapper )
Get our pixel index from the wrapper
Get our pixel index from the wrapper
[ "Get", "our", "pixel", "index", "from", "the", "wrapper" ]
def finalise( self, wrapper ): """Get our pixel index from the wrapper""" self.dataIndex = wrapper.pyArgIndex( 'data' )
[ "def", "finalise", "(", "self", ",", "wrapper", ")", ":", "self", ".", "dataIndex", "=", "wrapper", ".", "pyArgIndex", "(", "'data'", ")" ]
https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GL/images.py#L493-L495
zatosource/zato
2a9d273f06f9d776fbfeb53e73855af6e40fa208
code/zato-common/src/zato/common/ext/configobj_.py
python
ConfigObj._handle_bom
(self, infile)
Handle any BOM, and decode if necessary. If an encoding is specified, that *must* be used - but the BOM should still be removed (and the BOM attribute set). (If the encoding is wrongly specified, then a BOM for an alternative encoding won't be discovered or removed.) If an encoding is not specified, UTF8 or UTF16 BOM will be detected and removed. The BOM attribute will be set. UTF16 will be decoded to unicode. NOTE: This method must not be called with an empty ``infile``. Specifying the *wrong* encoding is likely to cause a ``UnicodeDecodeError``. ``infile`` must always be returned as a list of lines, but may be passed in as a single string.
Handle any BOM, and decode if necessary.
[ "Handle", "any", "BOM", "and", "decode", "if", "necessary", "." ]
def _handle_bom(self, infile): """ Handle any BOM, and decode if necessary. If an encoding is specified, that *must* be used - but the BOM should still be removed (and the BOM attribute set). (If the encoding is wrongly specified, then a BOM for an alternative encoding won't be discovered or removed.) If an encoding is not specified, UTF8 or UTF16 BOM will be detected and removed. The BOM attribute will be set. UTF16 will be decoded to unicode. NOTE: This method must not be called with an empty ``infile``. Specifying the *wrong* encoding is likely to cause a ``UnicodeDecodeError``. ``infile`` must always be returned as a list of lines, but may be passed in as a single string. """ if ((self.encoding is not None) and (self.encoding.lower() not in BOM_LIST)): # No need to check for a BOM # the encoding specified doesn't have one # just decode return self._decode(infile, self.encoding) if isinstance(infile, (list, tuple)): line = infile[0] else: line = infile if isinstance(line, six.text_type): # it's already decoded and there's no need to do anything # else, just use the _decode utility method to handle # listifying appropriately return self._decode(infile, self.encoding) if self.encoding is not None: # encoding explicitly supplied # And it could have an associated BOM # TODO: if encoding is just UTF16 - we ought to check for both # TODO: big endian and little endian versions. enc = BOM_LIST[self.encoding.lower()] if enc == 'utf_16': # For UTF16 we try big endian and little endian for BOM, (encoding, final_encoding) in list(BOMS.items()): if not final_encoding: # skip UTF8 continue if infile.startswith(BOM): ### BOM discovered ##self.BOM = True # Don't need to remove BOM return self._decode(infile, encoding) # If we get this far, will *probably* raise a DecodeError # As it doesn't appear to start with a BOM return self._decode(infile, self.encoding) # Must be UTF8 BOM = BOM_SET[enc] if not line.startswith(BOM): return self._decode(infile, self.encoding) newline = line[len(BOM):] # BOM removed if isinstance(infile, (list, tuple)): infile[0] = newline else: infile = newline self.BOM = True return self._decode(infile, self.encoding) # No encoding specified - so we need to check for UTF8/UTF16 for BOM, (encoding, final_encoding) in list(BOMS.items()): if not isinstance(line, six.binary_type) or not line.startswith(BOM): # didn't specify a BOM, or it's not a bytestring continue else: # BOM discovered self.encoding = final_encoding if not final_encoding: self.BOM = True # UTF8 # remove BOM newline = line[len(BOM):] if isinstance(infile, (list, tuple)): infile[0] = newline else: infile = newline # UTF-8 if isinstance(infile, six.text_type): return infile.splitlines(True) elif isinstance(infile, six.binary_type): return infile.decode('utf-8').splitlines(True) else: return self._decode(infile, 'utf-8') # UTF16 - have to decode return self._decode(infile, encoding) if six.PY2 and isinstance(line, str): # don't actually do any decoding, since we're on python 2 and # returning a bytestring is fine return self._decode(infile, None) # No BOM discovered and no encoding specified, default to UTF-8 if isinstance(infile, six.binary_type): return infile.decode('utf-8').splitlines(True) else: return self._decode(infile, 'utf-8')
[ "def", "_handle_bom", "(", "self", ",", "infile", ")", ":", "if", "(", "(", "self", ".", "encoding", "is", "not", "None", ")", "and", "(", "self", ".", "encoding", ".", "lower", "(", ")", "not", "in", "BOM_LIST", ")", ")", ":", "# No need to check fo...
https://github.com/zatosource/zato/blob/2a9d273f06f9d776fbfeb53e73855af6e40fa208/code/zato-common/src/zato/common/ext/configobj_.py#L1409-L1523
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
pytorch/pytorchcv/models/dla.py
python
dla102x2
(**kwargs)
return get_dla(levels=[1, 3, 4, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneckX64, residual_root=True, model_name="dla102x2", **kwargs)
DLA-X2-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for keeping the model parameters.
DLA-X2-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
[ "DLA", "-", "X2", "-", "102", "model", "from", "Deep", "Layer", "Aggregation", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1707", ".", "06484", "." ]
def dla102x2(**kwargs): """ DLA-X2-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for keeping the model parameters. """ class DLABottleneckX64(DLABottleneckX): def __init__(self, in_channels, out_channels, stride): super(DLABottleneckX64, self).__init__(in_channels, out_channels, stride, cardinality=64) return get_dla(levels=[1, 3, 4, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneckX64, residual_root=True, model_name="dla102x2", **kwargs)
[ "def", "dla102x2", "(", "*", "*", "kwargs", ")", ":", "class", "DLABottleneckX64", "(", "DLABottleneckX", ")", ":", "def", "__init__", "(", "self", ",", "in_channels", ",", "out_channels", ",", "stride", ")", ":", "super", "(", "DLABottleneckX64", ",", "se...
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/pytorch/pytorchcv/models/dla.py#L559-L575
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/codec/base.py
python
MultiPerDocumentReader.min_field_length
(self)
return min(r.min_field_length() for r in self._readers)
[]
def min_field_length(self): return min(r.min_field_length() for r in self._readers)
[ "def", "min_field_length", "(", "self", ")", ":", "return", "min", "(", "r", ".", "min_field_length", "(", ")", "for", "r", "in", "self", ".", "_readers", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/codec/base.py#L789-L790
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/cuda/cudadrv/nvvm.py
python
NVVM.is_nvvm70
(self)
return (self._majorIR, self._minorIR) >= (1, 6)
[]
def is_nvvm70(self): # NVVM70 uses NVVM IR version 1.6. See the documentation for # nvvmAddModuleToProgram in # https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html return (self._majorIR, self._minorIR) >= (1, 6)
[ "def", "is_nvvm70", "(", "self", ")", ":", "# NVVM70 uses NVVM IR version 1.6. See the documentation for", "# nvvmAddModuleToProgram in", "# https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html", "return", "(", "self", ".", "_majorIR", ",", "self", ".", "_minorIR", ")...
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cuda/cudadrv/nvvm.py#L162-L166
geekan/scrapy-examples
edb1cb116bd6def65a6ef01f953b58eb43e54305
tutorial/tutorial/pipelines.py
python
XmlExportPipeline.__init__
(self)
[]
def __init__(self): self.files = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "files", "=", "{", "}" ]
https://github.com/geekan/scrapy-examples/blob/edb1cb116bd6def65a6ef01f953b58eb43e54305/tutorial/tutorial/pipelines.py#L19-L20
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/scapy/modules/p0f.py
python
p0f_selectdb
(flags)
[]
def p0f_selectdb(flags): # tested flags: S, R, A if flags & 0x16 == 0x2: # SYN return p0f_kdb elif flags & 0x16 == 0x12: # SYN/ACK return p0fa_kdb elif flags & 0x16 in [ 0x4, 0x14 ]: # RST RST/ACK return p0fr_kdb elif flags & 0x16 == 0x10: # ACK return p0fo_kdb else: return None
[ "def", "p0f_selectdb", "(", "flags", ")", ":", "# tested flags: S, R, A", "if", "flags", "&", "0x16", "==", "0x2", ":", "# SYN", "return", "p0f_kdb", "elif", "flags", "&", "0x16", "==", "0x12", ":", "# SYN/ACK", "return", "p0fa_kdb", "elif", "flags", "&", ...
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/modules/p0f.py#L73-L88
JDAI-CV/fast-reid
31d99b793fe0937461b9c9bc8a8a11f88bf5642c
fastreid/data/samplers/triplet_sampler.py
python
NaiveIdentitySampler.__init__
(self, data_source: str, mini_batch_size: int, num_instances: int, seed: Optional[int] = None)
[]
def __init__(self, data_source: str, mini_batch_size: int, num_instances: int, seed: Optional[int] = None): self.data_source = data_source self.num_instances = num_instances self.num_pids_per_batch = mini_batch_size // self.num_instances self._rank = comm.get_rank() self._world_size = comm.get_world_size() self.batch_size = mini_batch_size * self._world_size self.pid_index = defaultdict(list) for index, info in enumerate(data_source): pid = info[1] self.pid_index[pid].append(index) self.pids = sorted(list(self.pid_index.keys())) self.num_identities = len(self.pids) if seed is None: seed = comm.shared_random_seed() self._seed = int(seed)
[ "def", "__init__", "(", "self", ",", "data_source", ":", "str", ",", "mini_batch_size", ":", "int", ",", "num_instances", ":", "int", ",", "seed", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "self", ".", "data_source", "=", "data_source", ...
https://github.com/JDAI-CV/fast-reid/blob/31d99b793fe0937461b9c9bc8a8a11f88bf5642c/fastreid/data/samplers/triplet_sampler.py#L208-L228
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/PIL/McIdasImagePlugin.py
python
McIdasImageFile._open
(self)
[]
def _open(self): # parse area file directory s = self.fp.read(256) if not _accept(s) or len(s) != 256: raise SyntaxError("not an McIdas area file") self.area_descriptor_raw = s self.area_descriptor = w = [0] + list(struct.unpack("!64i", s)) # get mode if w[11] == 1: mode = rawmode = "L" elif w[11] == 2: # FIXME: add memory map support mode = "I" rawmode = "I;16B" elif w[11] == 4: # FIXME: add memory map support mode = "I" rawmode = "I;32B" else: raise SyntaxError("unsupported McIdas format") self.mode = mode self.size = w[10], w[9] offset = w[34] + w[15] stride = w[15] + w[10]*w[11]*w[14] self.tile = [("raw", (0, 0) + self.size, offset, (rawmode, stride, 1))]
[ "def", "_open", "(", "self", ")", ":", "# parse area file directory", "s", "=", "self", ".", "fp", ".", "read", "(", "256", ")", "if", "not", "_accept", "(", "s", ")", "or", "len", "(", "s", ")", "!=", "256", ":", "raise", "SyntaxError", "(", "\"no...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/PIL/McIdasImagePlugin.py#L37-L67
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/tools/dev_appserver_import_hook.py
python
HardenedModulesHook.FindAndLoadModule
(self, submodule, submodule_fullname, search_path)
return module
Finds and loads a module, loads it, and adds it to the module dictionary. Args: submodule: Name of the module to import (e.g., baz). submodule_fullname: Full name of the module to import (e.g., foo.bar.baz). search_path: Path to use for searching for this submodule. For top-level modules this should be None; otherwise it should be the __path__ attribute from the parent package. Returns: A new module instance that has been inserted into the module dictionary supplied to __init__. Raises: ImportError exception if the module could not be loaded for whatever reason (e.g., missing, not allowed).
Finds and loads a module, loads it, and adds it to the module dictionary.
[ "Finds", "and", "loads", "a", "module", "loads", "it", "and", "adds", "it", "to", "the", "module", "dictionary", "." ]
def FindAndLoadModule(self, submodule, submodule_fullname, search_path): """Finds and loads a module, loads it, and adds it to the module dictionary. Args: submodule: Name of the module to import (e.g., baz). submodule_fullname: Full name of the module to import (e.g., foo.bar.baz). search_path: Path to use for searching for this submodule. For top-level modules this should be None; otherwise it should be the __path__ attribute from the parent package. Returns: A new module instance that has been inserted into the module dictionary supplied to __init__. Raises: ImportError exception if the module could not be loaded for whatever reason (e.g., missing, not allowed). """ module = self._imp.new_module(submodule_fullname) if submodule_fullname == 'thread': module.__dict__.update(self._dummy_thread.__dict__) module.__name__ = 'thread' elif submodule_fullname == 'cPickle': module.__dict__.update(self._pickle.__dict__) module.__name__ = 'cPickle' elif submodule_fullname == 'os': module.__dict__.update(self._os.__dict__) elif submodule_fullname == 'ssl': pass elif self.StubModuleExists(submodule_fullname): module = self.ImportStubModule(submodule_fullname) else: source_file, pathname, description = self.FindModuleRestricted(submodule, submodule_fullname, search_path) module = self.LoadModuleRestricted(submodule_fullname, source_file, pathname, description) if (getattr(module, '__path__', None) is not None and search_path != self._app_code_path): try: app_search_path = os.path.join(self._app_code_path, *(submodule_fullname.split('.')[:-1])) source_file, pathname, description = self.FindModuleRestricted(submodule, submodule_fullname, [app_search_path]) module.__path__.append(pathname) except ImportError, e: pass module.__loader__ = self self.FixModule(module) if submodule_fullname not in self._module_dict: self._module_dict[submodule_fullname] = module if submodule_fullname != submodule: parent_module = self._module_dict.get( submodule_fullname[:-len(submodule) - 1]) if parent_module and not hasattr(parent_module, submodule): setattr(parent_module, submodule, module) if submodule_fullname == 'os': os_path_name = module.path.__name__ os_path = self.FindAndLoadModule(os_path_name, os_path_name, search_path) self._module_dict['os.path'] = os_path module.__dict__['path'] = os_path return module
[ "def", "FindAndLoadModule", "(", "self", ",", "submodule", ",", "submodule_fullname", ",", "search_path", ")", ":", "module", "=", "self", ".", "_imp", ".", "new_module", "(", "submodule_fullname", ")", "if", "submodule_fullname", "==", "'thread'", ":", "module"...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/tools/dev_appserver_import_hook.py#L1585-L1675
ahmetcemturan/SFACT
7576e29ba72b33e5058049b77b7b558875542747
skeinforge_application/skeinforge_plugins/craft_plugins/coil.py
python
CoilSkein.parseBoundaries
(self)
Parse the boundaries and add them to the boundary layers.
Parse the boundaries and add them to the boundary layers.
[ "Parse", "the", "boundaries", "and", "add", "them", "to", "the", "boundary", "layers", "." ]
def parseBoundaries(self): "Parse the boundaries and add them to the boundary layers." boundaryLoop = None boundaryLayer = None for line in self.lines[self.lineIndex :]: splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) if len( self.shutdownLines ) > 0: self.shutdownLines.append(line) if firstWord == '(</boundaryPerimeter>)': boundaryLoop = None elif firstWord == '(<boundaryPoint>': location = gcodec.getLocationFromSplitLine(None, splitLine) if boundaryLoop == None: boundaryLoop = [] boundaryLayer.loops.append(boundaryLoop) boundaryLoop.append(location.dropAxis()) elif firstWord == '(<layer>': boundaryLayer = euclidean.LoopLayer(float(splitLine[1])) self.boundaryLayers.append(boundaryLayer) elif firstWord == '(</crafting>)': self.shutdownLines = [ line ] for boundaryLayer in self.boundaryLayers: if not euclidean.isWiddershins( boundaryLayer.loops[0] ): boundaryLayer.loops[0].reverse() self.boundaryReverseLayers = self.boundaryLayers[:] self.boundaryReverseLayers.reverse()
[ "def", "parseBoundaries", "(", "self", ")", ":", "boundaryLoop", "=", "None", "boundaryLayer", "=", "None", "for", "line", "in", "self", ".", "lines", "[", "self", ".", "lineIndex", ":", "]", ":", "splitLine", "=", "gcodec", ".", "getSplitLineBeforeBracketSe...
https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/skeinforge_application/skeinforge_plugins/craft_plugins/coil.py#L187-L213
mutpy/mutpy
5c8b3ca0d365083a4da8333f7fce8783114371fa
mutpy/operators/base.py
python
copy_node
(mutate)
return f
[]
def copy_node(mutate): def f(self, node): copied_node = copy.deepcopy(node, memo={ id(node.parent): node.parent, }) return mutate(self, copied_node) return f
[ "def", "copy_node", "(", "mutate", ")", ":", "def", "f", "(", "self", ",", "node", ")", ":", "copied_node", "=", "copy", ".", "deepcopy", "(", "node", ",", "memo", "=", "{", "id", "(", "node", ".", "parent", ")", ":", "node", ".", "parent", ",", ...
https://github.com/mutpy/mutpy/blob/5c8b3ca0d365083a4da8333f7fce8783114371fa/mutpy/operators/base.py#L19-L26
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/lib2to3/fixes/fix_import.py
python
traverse_imports
(names)
Walks over all the names imported in a dotted_as_names node.
Walks over all the names imported in a dotted_as_names node.
[ "Walks", "over", "all", "the", "names", "imported", "in", "a", "dotted_as_names", "node", "." ]
def traverse_imports(names): """ Walks over all the names imported in a dotted_as_names node. """ pending = [names] while pending: node = pending.pop() if node.type == token.NAME: yield node.value elif node.type == syms.dotted_name: yield "".join([ch.value for ch in node.children]) elif node.type == syms.dotted_as_name: pending.append(node.children[0]) elif node.type == syms.dotted_as_names: pending.extend(node.children[::-2]) else: raise AssertionError("unkown node type")
[ "def", "traverse_imports", "(", "names", ")", ":", "pending", "=", "[", "names", "]", "while", "pending", ":", "node", "=", "pending", ".", "pop", "(", ")", "if", "node", ".", "type", "==", "token", ".", "NAME", ":", "yield", "node", ".", "value", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/lib2to3/fixes/fix_import.py#L19-L35
XuShaohua/bcloud
4b54e0fdccf2b3013285fef05c97354cfa31697b
bcloud/UploadPage.py
python
UploadPage.pause_tasks
(self)
暂停所有上传任务
暂停所有上传任务
[ "暂停所有上传任务" ]
def pause_tasks(self): '''暂停所有上传任务''' if self.first_run: return for row in self.liststore: self.pause_task(row, scan=False)
[ "def", "pause_tasks", "(", "self", ")", ":", "if", "self", ".", "first_run", ":", "return", "for", "row", "in", "self", ".", "liststore", ":", "self", ".", "pause_task", "(", "row", ",", "scan", "=", "False", ")" ]
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/UploadPage.py#L538-L543
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/core/grr_response_core/lib/utils.py
python
ProcessIdString
()
return "%s@%s:%d" % (psutil.Process().name(), socket.gethostname(), os.getpid())
[]
def ProcessIdString(): return "%s@%s:%d" % (psutil.Process().name(), socket.gethostname(), os.getpid())
[ "def", "ProcessIdString", "(", ")", ":", "return", "\"%s@%s:%d\"", "%", "(", "psutil", ".", "Process", "(", ")", ".", "name", "(", ")", ",", "socket", ".", "gethostname", "(", ")", ",", "os", ".", "getpid", "(", ")", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/core/grr_response_core/lib/utils.py#L1306-L1308
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
Extensions/BottomWidgets/BookmarkWidget.py
python
BookmarkWidget.startLoadTimer
(self)
[]
def startLoadTimer(self): self.loadTimer.start(1000)
[ "def", "startLoadTimer", "(", "self", ")", ":", "self", ".", "loadTimer", ".", "start", "(", "1000", ")" ]
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/Extensions/BottomWidgets/BookmarkWidget.py#L28-L29
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/core/classes/dataset.py
python
Dataset.collate_fn
(self, batch)
return self._collate_fn(batch)
This is the method that user pass as functor to DataLoader. The method optionally performs neural type checking and add types to the outputs. Please note, subclasses of Dataset should not implement `input_types`. # Usage: dataloader = torch.utils.data.DataLoader( ...., collate_fn=dataset.collate_fn, .... ) Returns: Collated batch, with or without types.
This is the method that user pass as functor to DataLoader. The method optionally performs neural type checking and add types to the outputs.
[ "This", "is", "the", "method", "that", "user", "pass", "as", "functor", "to", "DataLoader", ".", "The", "method", "optionally", "performs", "neural", "type", "checking", "and", "add", "types", "to", "the", "outputs", "." ]
def collate_fn(self, batch): """ This is the method that user pass as functor to DataLoader. The method optionally performs neural type checking and add types to the outputs. Please note, subclasses of Dataset should not implement `input_types`. # Usage: dataloader = torch.utils.data.DataLoader( ...., collate_fn=dataset.collate_fn, .... ) Returns: Collated batch, with or without types. """ if self.input_types is not None: raise TypeError("Datasets should not implement `input_types` as they are not checked") # Simply forward the inner `_collate_fn` return self._collate_fn(batch)
[ "def", "collate_fn", "(", "self", ",", "batch", ")", ":", "if", "self", ".", "input_types", "is", "not", "None", ":", "raise", "TypeError", "(", "\"Datasets should not implement `input_types` as they are not checked\"", ")", "# Simply forward the inner `_collate_fn`", "re...
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/core/classes/dataset.py#L38-L59
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar.get
(self, name, default=None, domain=None, path=None)
Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1).
Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains.
[ "Dict", "-", "like", "get", "()", "that", "also", "supports", "optional", "domain", "and", "path", "args", "in", "order", "to", "resolve", "naming", "collisions", "from", "using", "one", "cookie", "jar", "over", "multiple", "domains", "." ]
def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). """ try: return self._find_no_duplicates(name, domain, path) except KeyError: return default
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "None", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_find_no_duplicates", "(", "name", ",", "domain", ",", "path", ")", "except", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/requests/cookies.py#L190-L200
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/analysis/hash_tagging.py
python
HashAnalyzer._GetHashesFromQueue
(self, maximum_number_of_hashes)
return hashes
Retrieves hashes from the queue. Args: maximum_number_of_hashes (int): maximum number of hashes to retrieve from the queue. Returns: list[str]: hashes.
Retrieves hashes from the queue.
[ "Retrieves", "hashes", "from", "the", "queue", "." ]
def _GetHashesFromQueue(self, maximum_number_of_hashes): """Retrieves hashes from the queue. Args: maximum_number_of_hashes (int): maximum number of hashes to retrieve from the queue. Returns: list[str]: hashes. """ hashes = [] for _ in range(maximum_number_of_hashes): try: item = self._hash_queue.get_nowait() hashes.append(item) except queue.Empty: continue return hashes
[ "def", "_GetHashesFromQueue", "(", "self", ",", "maximum_number_of_hashes", ")", ":", "hashes", "=", "[", "]", "for", "_", "in", "range", "(", "maximum_number_of_hashes", ")", ":", "try", ":", "item", "=", "self", ".", "_hash_queue", ".", "get_nowait", "(", ...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/analysis/hash_tagging.py#L83-L101
DataDog/dd-trace-py
13f9c6c1a8b4820365b299ab204f2bb5189d2a49
ddtrace/vendor/debtcollector/removals.py
python
removed_module
(module, replacement=None, message=None, version=None, removal_version=None, stacklevel=3, category=None)
Helper to be called inside a module to emit a deprecation warning :param str replacment: A location (or information about) of any potential replacement for the removed module (if applicable) :param str message: A message to include in the deprecation warning :param str version: Specify what version the removed module is present in :param str removal_version: What version the module will be removed. If '?' is used this implies an undefined future version :param int stacklevel: How many entries deep in the call stack before ignoring :param type category: warnings message category (this defaults to ``DeprecationWarning`` when none is provided)
Helper to be called inside a module to emit a deprecation warning
[ "Helper", "to", "be", "called", "inside", "a", "module", "to", "emit", "a", "deprecation", "warning" ]
def removed_module(module, replacement=None, message=None, version=None, removal_version=None, stacklevel=3, category=None): """Helper to be called inside a module to emit a deprecation warning :param str replacment: A location (or information about) of any potential replacement for the removed module (if applicable) :param str message: A message to include in the deprecation warning :param str version: Specify what version the removed module is present in :param str removal_version: What version the module will be removed. If '?' is used this implies an undefined future version :param int stacklevel: How many entries deep in the call stack before ignoring :param type category: warnings message category (this defaults to ``DeprecationWarning`` when none is provided) """ if inspect.ismodule(module): module_name = _get_qualified_name(module) elif isinstance(module, six.string_types): module_name = module else: _qual, type_name = _utils.get_qualified_name(type(module)) raise TypeError("Unexpected module type '%s' (expected string or" " module type only)" % type_name) prefix = "The '%s' module usage is deprecated" % module_name if replacement: postfix = ", please use %s instead" % replacement else: postfix = None out_message = _utils.generate_message(prefix, postfix=postfix, message=message, version=version, removal_version=removal_version) _utils.deprecation(out_message, stacklevel=stacklevel, category=category)
[ "def", "removed_module", "(", "module", ",", "replacement", "=", "None", ",", "message", "=", "None", ",", "version", "=", "None", ",", "removal_version", "=", "None", ",", "stacklevel", "=", "3", ",", "category", "=", "None", ")", ":", "if", "inspect", ...
https://github.com/DataDog/dd-trace-py/blob/13f9c6c1a8b4820365b299ab204f2bb5189d2a49/ddtrace/vendor/debtcollector/removals.py#L299-L334
piwheels/piwheels
ff0b306fc7b6754fe8d73f1ddfae884e54ce6c8a
piwheels/master/db.py
python
Database.log_build
(self, build)
Log a build attempt in the database, including build output and wheel info if successful.
Log a build attempt in the database, including build output and wheel info if successful.
[ "Log", "a", "build", "attempt", "in", "the", "database", "including", "build", "output", "and", "wheel", "info", "if", "successful", "." ]
def log_build(self, build): """ Log a build attempt in the database, including build output and wheel info if successful. """ with self._conn.begin(): if build.status: build_id = self._conn.execute( "VALUES (log_build_success(%s, %s, %s, %s, %s, %s, " "CAST(%s AS files ARRAY), CAST(%s AS dependencies ARRAY)" "))", ( build.package, build.version, build.slave_id, build.duration, build.abi_tag, sanitize(build.output), [( file.filename, None, file.filesize, file.filehash, file.package_tag, file.package_version_tag, file.py_version_tag, file.abi_tag, file.platform_tag, file.requires_python, ) for file in build.files.values()], [( file.filename, tool, dependency, ) for file in build.files.values() for tool, dependencies in file.dependencies.items() for dependency in dependencies] )).scalar() else: build_id = self._conn.execute( "VALUES (log_build_failure(%s, %s, %s, %s, %s, %s))", ( build.package, build.version, build.slave_id, build.duration, build.abi_tag, sanitize(build.output), )).scalar() build.logged(build_id)
[ "def", "log_build", "(", "self", ",", "build", ")", ":", "with", "self", ".", "_conn", ".", "begin", "(", ")", ":", "if", "build", ".", "status", ":", "build_id", "=", "self", ".", "_conn", ".", "execute", "(", "\"VALUES (log_build_success(%s, %s, %s, %s, ...
https://github.com/piwheels/piwheels/blob/ff0b306fc7b6754fe8d73f1ddfae884e54ce6c8a/piwheels/master/db.py#L394-L445