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
simetenn/uncertainpy
ffb2400289743066265b9a8561cdf3b72e478a28
src/uncertainpy/features/features.py
python
Features.validate
(self, feature_name, *feature_result)
Validate the results from ``calculate_feature``. This method ensures each returns `time`, `values`. Parameters ---------- model_results Any type of model results returned by ``run``. feature_name : str Name of the feature, to create better error messages. Raises ------ ValueError If the model result does not fit the requirements. TypeError If the model result does not fit the requirements. Notes ----- Tries to verify that at least, `time` and `values` are returned from ``run``. ``model_result`` should follow the format: ``return time, values, info_1, info_2, ...``. Where: * ``time_feature`` : ``{None, numpy.nan, array_like}`` Time values, or equivalent, of the feature, if no time values return None or numpy.nan. * ``values`` : ``{None, numpy.nan, array_like}`` The feature results, `values` must either be regular (have the same number of points for different paramaters) or be able to be interpolated. If there are no feature results return None or ``numpy.nan`` instead of `values` and that evaluation are disregarded.
Validate the results from ``calculate_feature``.
[ "Validate", "the", "results", "from", "calculate_feature", "." ]
def validate(self, feature_name, *feature_result): """ Validate the results from ``calculate_feature``. This method ensures each returns `time`, `values`. Parameters ---------- model_results Any type of model results returned by ``run``. feature_name : str Name of the feature, to create better error messages. Raises ------ ValueError If the model result does not fit the requirements. TypeError If the model result does not fit the requirements. Notes ----- Tries to verify that at least, `time` and `values` are returned from ``run``. ``model_result`` should follow the format: ``return time, values, info_1, info_2, ...``. Where: * ``time_feature`` : ``{None, numpy.nan, array_like}`` Time values, or equivalent, of the feature, if no time values return None or numpy.nan. * ``values`` : ``{None, numpy.nan, array_like}`` The feature results, `values` must either be regular (have the same number of points for different paramaters) or be able to be interpolated. If there are no feature results return None or ``numpy.nan`` instead of `values` and that evaluation are disregarded. """ if isinstance(feature_result, np.ndarray): raise ValueError("{} returns an numpy array. ".format(feature_name) + "This indicates only time or values is returned. " + "{} must return time and values".format(feature_name) + "(return time, values | return None, values)") if isinstance(feature_result, six.string_types): raise ValueError("{} returns a string. ".format(feature_name) + "This indicates only time or values is returned. " + "{} must return time and values".format(feature_name) + "(return time, values | return None, values)") # Check that time, and values is returned try: time_feature, values_feature = feature_result except (ValueError, TypeError) as error: msg = "feature {} must return time and values (return time, values | return None, values)".format(feature_name) if not error.args: error.args = ("",) error.args = error.args + (msg,) raise
[ "def", "validate", "(", "self", ",", "feature_name", ",", "*", "feature_result", ")", ":", "if", "isinstance", "(", "feature_result", ",", "np", ".", "ndarray", ")", ":", "raise", "ValueError", "(", "\"{} returns an numpy array. \"", ".", "format", "(", "featu...
https://github.com/simetenn/uncertainpy/blob/ffb2400289743066265b9a8561cdf3b72e478a28/src/uncertainpy/features/features.py#L384-L442
plaid/plaid-python
8c60fca608e426f3ff30da8857775946d29e122c
plaid/model/external_payment_schedule_base.py
python
ExternalPaymentScheduleBase.additional_properties_type
()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type,)
[ "def", "additional_properties_type", "(", ")", ":", "lazy_import", "(", ")", "return", "(", "bool", ",", "date", ",", "datetime", ",", "dict", ",", "float", ",", "int", ",", "list", ",", "str", ",", "none_type", ",", ")" ]
https://github.com/plaid/plaid-python/blob/8c60fca608e426f3ff30da8857775946d29e122c/plaid/model/external_payment_schedule_base.py#L63-L69
deepmind/bsuite
f305972cf05042f6ce23d638477ea9b33918ba17
bsuite/baselines/tf/actor_critic_rnn/agent.py
python
ActorCriticRNN.select_action
(self, timestep: dm_env.TimeStep)
return tf.random.categorical(logits, num_samples=1).numpy().squeeze()
Selects actions according to the latest softmax policy.
Selects actions according to the latest softmax policy.
[ "Selects", "actions", "according", "to", "the", "latest", "softmax", "policy", "." ]
def select_action(self, timestep: dm_env.TimeStep) -> base.Action: """Selects actions according to the latest softmax policy.""" if timestep.first(): self._state = self._network.initial_state(1) self._rollout_initial_state = self._network.initial_state(1) observation = tf.expand_dims(timestep.observation, axis=0) (logits, _), self._state = self._forward(observation, self._state) return tf.random.categorical(logits, num_samples=1).numpy().squeeze()
[ "def", "select_action", "(", "self", ",", "timestep", ":", "dm_env", ".", "TimeStep", ")", "->", "base", ".", "Action", ":", "if", "timestep", ".", "first", "(", ")", ":", "self", ".", "_state", "=", "self", ".", "_network", ".", "initial_state", "(", ...
https://github.com/deepmind/bsuite/blob/f305972cf05042f6ce23d638477ea9b33918ba17/bsuite/baselines/tf/actor_critic_rnn/agent.py#L116-L123
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/mimify.py
python
mime_encode
(line, header)
return newline + line
Code a single line as quoted-printable. If header is set, quote some extra characters.
Code a single line as quoted-printable. If header is set, quote some extra characters.
[ "Code", "a", "single", "line", "as", "quoted", "-", "printable", ".", "If", "header", "is", "set", "quote", "some", "extra", "characters", "." ]
def mime_encode(line, header): """Code a single line as quoted-printable. If header is set, quote some extra characters.""" if header: reg = mime_header_char else: reg = mime_char newline = '' pos = 0 if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = ('=%02x' % ord('F')).upper() pos = 1 while 1: res = reg.search(line, pos) if res is None: break newline = newline + line[pos:res.start(0)] + \ ('=%02x' % ord(res.group(0))).upper() pos = res.end(0) line = newline + line[pos:] newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
[ "def", "mime_encode", "(", "line", ",", "header", ")", ":", "if", "header", ":", "reg", "=", "mime_header_char", "else", ":", "reg", "=", "mime_char", "newline", "=", "''", "pos", "=", "0", "if", "len", "(", "line", ")", ">=", "5", "and", "line", "...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/mimify.py#L228-L258
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/pyparsing.py
python
Char.__init__
(self, charset, asKeyword=False, excludeChars=None)
[]
def __init__(self, charset, asKeyword=False, excludeChars=None): super(Char, self).__init__(charset, exact=1, asKeyword=asKeyword, excludeChars=excludeChars) self.reString = "[%s]" % _escapeRegexRangeChars(''.join(self.initChars)) if asKeyword: self.reString = r"\b%s\b" % self.reString self.re = re.compile(self.reString) self.re_match = self.re.match
[ "def", "__init__", "(", "self", ",", "charset", ",", "asKeyword", "=", "False", ",", "excludeChars", "=", "None", ")", ":", "super", "(", "Char", ",", "self", ")", ".", "__init__", "(", "charset", ",", "exact", "=", "1", ",", "asKeyword", "=", "asKey...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/pyparsing.py#L3261-L3267
paver/paver
a755508ea742a216284bd4b605f871994989d27d
bootstrap.py
python
make_relative_path
(source, dest, dest_is_directory=True)
return os.path.sep.join(full_parts)
Make a filename relative, where the filename is dest, and it is being referred to from the filename source. >>> make_relative_path('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Directory') '../another-place/src/Directory' >>> make_relative_path('/usr/share/something/a-file.pth', ... '/home/user/src/Directory') '../../../home/user/src/Directory' >>> make_relative_path('/usr/share/a-file.pth', '/usr/share/') './'
Make a filename relative, where the filename is dest, and it is being referred to from the filename source.
[ "Make", "a", "filename", "relative", "where", "the", "filename", "is", "dest", "and", "it", "is", "being", "referred", "to", "from", "the", "filename", "source", "." ]
def make_relative_path(source, dest, dest_is_directory=True): """ Make a filename relative, where the filename is dest, and it is being referred to from the filename source. >>> make_relative_path('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Directory') '../another-place/src/Directory' >>> make_relative_path('/usr/share/something/a-file.pth', ... '/home/user/src/Directory') '../../../home/user/src/Directory' >>> make_relative_path('/usr/share/a-file.pth', '/usr/share/') './' """ source = os.path.dirname(source) if not dest_is_directory: dest_filename = os.path.basename(dest) dest = os.path.dirname(dest) dest = os.path.normpath(os.path.abspath(dest)) source = os.path.normpath(os.path.abspath(source)) dest_parts = dest.strip(os.path.sep).split(os.path.sep) source_parts = source.strip(os.path.sep).split(os.path.sep) while dest_parts and source_parts and dest_parts[0] == source_parts[0]: dest_parts.pop(0) source_parts.pop(0) full_parts = ['..']*len(source_parts) + dest_parts if not dest_is_directory: full_parts.append(dest_filename) if not full_parts: # Special case for the current directory (otherwise it'd be '') return './' return os.path.sep.join(full_parts)
[ "def", "make_relative_path", "(", "source", ",", "dest", ",", "dest_is_directory", "=", "True", ")", ":", "source", "=", "os", ".", "path", ".", "dirname", "(", "source", ")", "if", "not", "dest_is_directory", ":", "dest_filename", "=", "os", ".", "path", ...
https://github.com/paver/paver/blob/a755508ea742a216284bd4b605f871994989d27d/bootstrap.py#L1722-L1753
Sandmann79/xbmc
42d276765701d43572219b94198dfba9971aba2a
script.module.mechanicalsoup/lib/mechanicalsoup/form.py
python
Form.check
(self, data)
For backwards compatibility, this method handles checkboxes and radio buttons in a single call. It will not uncheck any checkboxes unless explicitly specified by ``data``, in contrast with the default behavior of :func:`~Form.set_checkbox`.
For backwards compatibility, this method handles checkboxes and radio buttons in a single call. It will not uncheck any checkboxes unless explicitly specified by ``data``, in contrast with the default behavior of :func:`~Form.set_checkbox`.
[ "For", "backwards", "compatibility", "this", "method", "handles", "checkboxes", "and", "radio", "buttons", "in", "a", "single", "call", ".", "It", "will", "not", "uncheck", "any", "checkboxes", "unless", "explicitly", "specified", "by", "data", "in", "contrast",...
def check(self, data): """For backwards compatibility, this method handles checkboxes and radio buttons in a single call. It will not uncheck any checkboxes unless explicitly specified by ``data``, in contrast with the default behavior of :func:`~Form.set_checkbox`. """ for (name, value) in data.items(): try: self.set_checkbox({name: value}, uncheck_other_boxes=False) continue except InvalidFormMethod: pass try: self.set_radio({name: value}) continue except InvalidFormMethod: pass raise LinkNotFoundError("No input checkbox/radio named " + name)
[ "def", "check", "(", "self", ",", "data", ")", ":", "for", "(", "name", ",", "value", ")", "in", "data", ".", "items", "(", ")", ":", "try", ":", "self", ".", "set_checkbox", "(", "{", "name", ":", "value", "}", ",", "uncheck_other_boxes", "=", "...
https://github.com/Sandmann79/xbmc/blob/42d276765701d43572219b94198dfba9971aba2a/script.module.mechanicalsoup/lib/mechanicalsoup/form.py#L80-L97
kaidic/LDAM-DRW
2536330f2afdaa65618323cb5a5850efccce762a
models/resnet_cifar.py
python
resnet20
()
return ResNet_s(BasicBlock, [3, 3, 3])
[]
def resnet20(): return ResNet_s(BasicBlock, [3, 3, 3])
[ "def", "resnet20", "(", ")", ":", "return", "ResNet_s", "(", "BasicBlock", ",", "[", "3", ",", "3", ",", "3", "]", ")" ]
https://github.com/kaidic/LDAM-DRW/blob/2536330f2afdaa65618323cb5a5850efccce762a/models/resnet_cifar.py#L127-L128
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py
python
ClassManager.mapper
(self)
[]
def mapper(self): # raises unless self.mapper has been assigned raise exc.UnmappedClassError(self.class_)
[ "def", "mapper", "(", "self", ")", ":", "# raises unless self.mapper has been assigned", "raise", "exc", ".", "UnmappedClassError", "(", "self", ".", "class_", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py#L114-L116
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
dist/lib/python2.7/wsgiref/handlers.py
python
BaseHandler.get_stderr
(self)
Override in subclass to return suitable 'wsgi.errors
Override in subclass to return suitable 'wsgi.errors
[ "Override", "in", "subclass", "to", "return", "suitable", "wsgi", ".", "errors" ]
def get_stderr(self): """Override in subclass to return suitable 'wsgi.errors'""" raise NotImplementedError
[ "def", "get_stderr", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/wsgiref/handlers.py#L347-L349
coto/gae-boilerplate
470f2b61fcb0238c1ad02cc1f97e6017acbe9628
bp_includes/external/requests/packages/urllib3/connectionpool.py
python
HTTPConnectionPool._get_timeout
(self, timeout)
Helper that always returns a :class:`urllib3.util.Timeout`
Helper that always returns a :class:`urllib3.util.Timeout`
[ "Helper", "that", "always", "returns", "a", ":", "class", ":", "urllib3", ".", "util", ".", "Timeout" ]
def _get_timeout(self, timeout): """ Helper that always returns a :class:`urllib3.util.Timeout` """ if timeout is _Default: return self.timeout.clone() if isinstance(timeout, Timeout): return timeout.clone() else: # User passed us an int/float. This is for backwards compatibility, # can be removed later return Timeout.from_float(timeout)
[ "def", "_get_timeout", "(", "self", ",", "timeout", ")", ":", "if", "timeout", "is", "_Default", ":", "return", "self", ".", "timeout", ".", "clone", "(", ")", "if", "isinstance", "(", "timeout", ",", "Timeout", ")", ":", "return", "timeout", ".", "clo...
https://github.com/coto/gae-boilerplate/blob/470f2b61fcb0238c1ad02cc1f97e6017acbe9628/bp_includes/external/requests/packages/urllib3/connectionpool.py#L248-L258
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/modform_hecketriangle/graded_ring_element.py
python
FormsRingElement._repr_
(self)
return self._rat_repr()
r""" Return the string representation of ``self``. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.graded_ring import QuasiModularFormsRing sage: (x,y,z,d)=var("x,y,z,d") sage: QuasiModularFormsRing(n=5)(x^3*z-d*y) f_rho^3*E2 - f_i*d sage: QuasiModularFormsRing(n=infinity)(x) E4
r""" Return the string representation of ``self``.
[ "r", "Return", "the", "string", "representation", "of", "self", "." ]
def _repr_(self): r""" Return the string representation of ``self``. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.graded_ring import QuasiModularFormsRing sage: (x,y,z,d)=var("x,y,z,d") sage: QuasiModularFormsRing(n=5)(x^3*z-d*y) f_rho^3*E2 - f_i*d sage: QuasiModularFormsRing(n=infinity)(x) E4 """ return self._rat_repr()
[ "def", "_repr_", "(", "self", ")", ":", "return", "self", ".", "_rat_repr", "(", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/modform_hecketriangle/graded_ring_element.py#L171-L186
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/plugins/layout/widgets/dialog.py
python
test
()
Run layout test widget test
Run layout test widget test
[ "Run", "layout", "test", "widget", "test" ]
def test(): """Run layout test widget test""" from spyder.utils.qthelpers import qapplication app = qapplication() names = ['test', 'tester', '20', '30', '40'] ui_names = ['L1', 'L2', '20', '30', '40'] order = ['test', 'tester', '20', '30', '40'] read_only = ['test', 'tester'] active = ['test', 'tester'] widget_1 = LayoutSettingsDialog( None, names, ui_names, order, active, read_only) widget_2 = LayoutSaveDialog(None, order) widget_1.show() widget_2.show() sys.exit(app.exec_())
[ "def", "test", "(", ")", ":", "from", "spyder", ".", "utils", ".", "qthelpers", "import", "qapplication", "app", "=", "qapplication", "(", ")", "names", "=", "[", "'test'", ",", "'tester'", ",", "'20'", ",", "'30'", ",", "'40'", "]", "ui_names", "=", ...
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/layout/widgets/dialog.py#L377-L392
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/immlib/librecognition.py
python
FunctionRecognition.checkHeuristic
(self, address, reference, refFirstCall=[])
return perc
Check a given address with a precomputed hash of a function. Return a percentage of match (you can use a threasold to consider a real match) @type address: DWORD @param address: Address of the function to compare @type reference: STRING @param reference: base64 representation of the compressed information about the function @type refFirstCall: STRING @param refFirstCall: the same, but following the function pointed by the first call in the first BB. (OPTIONAL) @rtype: INTEGER @return: heuristic threasold to consider a real function match
Check a given address with a precomputed hash of a function. Return a percentage of match (you can use a threasold to consider a real match) @type address: DWORD @param address: Address of the function to compare @type reference: STRING @param reference: base64 representation of the compressed information about the function
[ "Check", "a", "given", "address", "with", "a", "precomputed", "hash", "of", "a", "function", ".", "Return", "a", "percentage", "of", "match", "(", "you", "can", "use", "a", "threasold", "to", "consider", "a", "real", "match", ")", "@type", "address", ":"...
def checkHeuristic(self, address, reference, refFirstCall=[]): """ Check a given address with a precomputed hash of a function. Return a percentage of match (you can use a threasold to consider a real match) @type address: DWORD @param address: Address of the function to compare @type reference: STRING @param reference: base64 representation of the compressed information about the function @type refFirstCall: STRING @param refFirstCall: the same, but following the function pointed by the first call in the first BB. (OPTIONAL) @rtype: INTEGER @return: heuristic threasold to consider a real function match """ #self.imm.Log("checking heuristically: %08X" % address) #do the hard work just one time if self.heuristicCache.has_key(address): cfg = self.heuristicCache[address] else: cfg = self.makeFunctionHashHeuristic(address) self.heuristicCache[address] = cfg #check reference against our cache sha1 = hashlib.sha1(reference+refFirstCall).digest() if self.heuristicReferencesCache.has_key(sha1): refcfg = self.heuristicReferencesCache[sha1] else: #This's the reference hash to compare with (uncompress just once and cache the results) #Decode each BB-hash refcfg = [] refcfg.append([]) refcfg.append([]) data = binascii.a2b_base64(reference) for o in range(0,len(data),12): (start, left, right) = struct.unpack("LLL",data[o:o+12]) refcfg[0].append([ start, left, right ]) if refFirstCall: data = binascii.a2b_base64(refFirstCall) for o in range(0,len(data),12): (start, left, right) = struct.unpack("LLL",data[o:o+12]) refcfg[1].append([ start, left, right ]) self.heuristicReferencesCache[sha1] = refcfg perc1 = self.compareHeuristic(cfg[0][:], refcfg[0][:]) if cfg[1] or refcfg[1]: perc2 = self.compareHeuristic(cfg[1][:], refcfg[1][:]) #use the average perc = (perc1 + perc2) / 2 else: perc = perc1 return perc
[ "def", "checkHeuristic", "(", "self", ",", "address", ",", "reference", ",", "refFirstCall", "=", "[", "]", ")", ":", "#self.imm.Log(\"checking heuristically: %08X\" % address)", "#do the hard work just one time", "if", "self", ".", "heuristicCache", ".", "has_key", "("...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/immlib/librecognition.py#L140-L197
anchore/anchore-engine
bb18b70e0cbcad58beb44cd439d00067d8f7ea8b
anchore_engine/utils.py
python
filter_record_keys
(record_list, whitelist_keys)
return filtered
Filter the list records to remove verbose entries and make it suitable for notification format :param record_dict: dict containing values to process :param whitelist_keys: keys to leave in the record dicts :return: a new list with dicts that only contain the whitelisted elements
Filter the list records to remove verbose entries and make it suitable for notification format :param record_dict: dict containing values to process :param whitelist_keys: keys to leave in the record dicts :return: a new list with dicts that only contain the whitelisted elements
[ "Filter", "the", "list", "records", "to", "remove", "verbose", "entries", "and", "make", "it", "suitable", "for", "notification", "format", ":", "param", "record_dict", ":", "dict", "containing", "values", "to", "process", ":", "param", "whitelist_keys", ":", ...
def filter_record_keys(record_list, whitelist_keys): """ Filter the list records to remove verbose entries and make it suitable for notification format :param record_dict: dict containing values to process :param whitelist_keys: keys to leave in the record dicts :return: a new list with dicts that only contain the whitelisted elements """ filtered = [ {k: v for k, v in [y for y in list(x.items()) if y[0] in whitelist_keys]} for x in record_list ] return filtered
[ "def", "filter_record_keys", "(", "record_list", ",", "whitelist_keys", ")", ":", "filtered", "=", "[", "{", "k", ":", "v", "for", "k", ",", "v", "in", "[", "y", "for", "y", "in", "list", "(", "x", ".", "items", "(", ")", ")", "if", "y", "[", "...
https://github.com/anchore/anchore-engine/blob/bb18b70e0cbcad58beb44cd439d00067d8f7ea8b/anchore_engine/utils.py#L193-L205
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/src/contacts/dispatch.py
python
im_service_compatible
(to_service, from_service)
return to_service in protocols[from_service].compatible
Returns True if a buddy on to_service can be IMed from a connection to from_service.
Returns True if a buddy on to_service can be IMed from a connection to from_service.
[ "Returns", "True", "if", "a", "buddy", "on", "to_service", "can", "be", "IMed", "from", "a", "connection", "to", "from_service", "." ]
def im_service_compatible(to_service, from_service): ''' Returns True if a buddy on to_service can be IMed from a connection to from_service. ''' return to_service in protocols[from_service].compatible
[ "def", "im_service_compatible", "(", "to_service", ",", "from_service", ")", ":", "return", "to_service", "in", "protocols", "[", "from_service", "]", ".", "compatible" ]
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/contacts/dispatch.py#L242-L247
python-xlib/python-xlib
1a3031544bb25464c4744edae39ac02b0e730f13
Xlib/ext/nvcontrol.py
python
Gpu.__init__
(self, ngpu=0)
Target a GPU
Target a GPU
[ "Target", "a", "GPU" ]
def __init__(self, ngpu=0): """Target a GPU""" super(self.__class__, self).__init__() self._id = ngpu self._type = NV_CTRL_TARGET_TYPE_GPU self._name = 'GPU'
[ "def", "__init__", "(", "self", ",", "ngpu", "=", "0", ")", ":", "super", "(", "self", ".", "__class__", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_id", "=", "ngpu", "self", ".", "_type", "=", "NV_CTRL_TARGET_TYPE_GPU", "self", ".", ...
https://github.com/python-xlib/python-xlib/blob/1a3031544bb25464c4744edae39ac02b0e730f13/Xlib/ext/nvcontrol.py#L5201-L5206
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/pkg_resources.py
python
ZipProvider.__init__
(self, module)
[]
def __init__(self, module): EggProvider.__init__(self,module) self.zipinfo = zipimport._zip_directory_cache[self.loader.archive] self.zip_pre = self.loader.archive+os.sep
[ "def", "__init__", "(", "self", ",", "module", ")", ":", "EggProvider", ".", "__init__", "(", "self", ",", "module", ")", "self", ".", "zipinfo", "=", "zipimport", ".", "_zip_directory_cache", "[", "self", ".", "loader", ".", "archive", "]", "self", ".",...
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/pkg_resources.py#L1305-L1308
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
nltk/parse/api.py
python
ParserI.iter_parse
(self, sent)
:return: An iterator that generates parse trees that represent possible structures for the given sentence. When possible, this list is sorted from most likely to least likely. :param sent: The sentence to be parsed :type sent: list(str) :rtype: iter(Tree)
:return: An iterator that generates parse trees that represent possible structures for the given sentence. When possible, this list is sorted from most likely to least likely.
[ ":", "return", ":", "An", "iterator", "that", "generates", "parse", "trees", "that", "represent", "possible", "structures", "for", "the", "given", "sentence", ".", "When", "possible", "this", "list", "is", "sorted", "from", "most", "likely", "to", "least", "...
def iter_parse(self, sent): """ :return: An iterator that generates parse trees that represent possible structures for the given sentence. When possible, this list is sorted from most likely to least likely. :param sent: The sentence to be parsed :type sent: list(str) :rtype: iter(Tree) """ if overridden(self.batch_iter_parse): return self.batch_iter_parse([sent])[0] elif overridden(self.nbest_parse) or overridden(self.batch_nbest_parse): return iter(self.nbest_parse(sent)) elif overridden(self.parse) or overridden(self.batch_parse): tree = self.parse(sent) if tree: return iter([tree]) else: return iter([]) else: raise NotImplementedError()
[ "def", "iter_parse", "(", "self", ",", "sent", ")", ":", "if", "overridden", "(", "self", ".", "batch_iter_parse", ")", ":", "return", "self", ".", "batch_iter_parse", "(", "[", "sent", "]", ")", "[", "0", "]", "elif", "overridden", "(", "self", ".", ...
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/parse/api.py#L77-L96
mysql/mysql-connector-python
c5460bcbb0dff8e4e48bf4af7a971c89bf486d85
lib/mysql/connector/conversion.py
python
MySQLConverter._DATETIME_to_python
(self, value, dsc=None)
return datetime_val
Converts DATETIME column value to python datetime.time value type. Converts the DATETIME column MySQL type passed as bytes to a python datetime.datetime type. Returns: datetime.datetime type.
Converts DATETIME column value to python datetime.time value type.
[ "Converts", "DATETIME", "column", "value", "to", "python", "datetime", ".", "time", "value", "type", "." ]
def _DATETIME_to_python(self, value, dsc=None): # pylint: disable=C0103 """"Converts DATETIME column value to python datetime.time value type. Converts the DATETIME column MySQL type passed as bytes to a python datetime.datetime type. Returns: datetime.datetime type. """ if isinstance(value, datetime.datetime): return value datetime_val = None try: (date_, time_) = value.split(b' ') if len(time_) > 8: (hms, mcs) = time_.split(b'.') mcs = int(mcs.ljust(6, b'0')) else: hms = time_ mcs = 0 dtval = [int(i) for i in date_.split(b'-')] + \ [int(i) for i in hms.split(b':')] + [mcs, ] if len(dtval) < 6: raise ValueError("invalid datetime format: {} len: {}" "".format(dtval, len(dtval))) else: # Note that by default MySQL accepts invalid timestamps # (this is also backward compatibility). # Traditionaly C/py returns None for this well formed but # invalid datetime for python like '0000-00-00 HH:MM:SS'. try: datetime_val = datetime.datetime(*dtval) except ValueError: return None except (IndexError, TypeError): raise ValueError(CONVERT_ERROR.format(value=value, pytype="datetime.timedelta")) return datetime_val
[ "def", "_DATETIME_to_python", "(", "self", ",", "value", ",", "dsc", "=", "None", ")", ":", "# pylint: disable=C0103", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", "datetime_val", "=", "None", "try", ":", ...
https://github.com/mysql/mysql-connector-python/blob/c5460bcbb0dff8e4e48bf4af7a971c89bf486d85/lib/mysql/connector/conversion.py#L513-L550
Map-A-Droid/MAD
81375b5c9ccc5ca3161eb487aa81469d40ded221
mapadroid/db/DbPogoProtoSubmit.py
python
DbPogoProtoSubmit.quest
(self, origin: str, quest_proto: dict, mitm_mapper, quest_gen: QuestGen)
return True
[]
def quest(self, origin: str, quest_proto: dict, mitm_mapper, quest_gen: QuestGen): origin_logger = get_origin_logger(logger, origin=origin) origin_logger.debug3("DbPogoProtoSubmit::quest called") fort_id = quest_proto.get("fort_id", None) if fort_id is None: return False if "challenge_quest" not in quest_proto: return False protoquest = quest_proto["challenge_quest"]["quest"] protoquest_display = quest_proto["challenge_quest"]["quest_display"] rewards = protoquest.get("quest_rewards", None) if rewards is None or not rewards: return False reward = rewards[0] item = reward['item'] encounter = reward['pokemon_encounter'] goal = protoquest['goal'] quest_type = protoquest.get("quest_type", None) quest_template = protoquest.get("template_id", None) quest_title_resource_id = protoquest_display.get("title", None) reward_type = reward.get("type", None) item_item = item.get("item", None) item_amount = item.get("amount", None) pokemon_id = encounter.get("pokemon_id", None) if reward_type == 4: item_amount = reward.get('candy', {}).get('amount', 0) pokemon_id = reward.get('candy', {}).get('pokemon_id', 0) elif reward_type == 12: item_amount = reward.get('mega_resource', {}).get('amount', 0) pokemon_id = reward.get('mega_resource', {}).get('pokemon_id', 0) stardust = reward.get("stardust", None) form_id = encounter.get("pokemon_display", {}).get("form_value", 0) costume_id = encounter.get("pokemon_display", {}).get("costume_value", 0) target = goal.get("target", None) condition = goal.get("condition", None) json_condition = json.dumps(condition) task = quest_gen.questtask(int(quest_type), json_condition, int(target), str(quest_template), quest_title_resource_id) mitm_mapper.collect_quest_stats(origin, fort_id) query_quests = ( "INSERT INTO trs_quest (GUID, quest_type, quest_timestamp, quest_stardust, quest_pokemon_id, " "quest_pokemon_form_id, quest_pokemon_costume_id, " "quest_reward_type, quest_item_id, quest_item_amount, quest_target, quest_condition, quest_reward, " "quest_task, quest_template, quest_title)" " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" "ON DUPLICATE KEY UPDATE quest_type=VALUES(quest_type), quest_timestamp=VALUES(quest_timestamp), " "quest_stardust=VALUES(quest_stardust), quest_pokemon_id=VALUES(quest_pokemon_id), " "quest_reward_type=VALUES(quest_reward_type), quest_item_id=VALUES(quest_item_id), " "quest_item_amount=VALUES(quest_item_amount), quest_target=VALUES(quest_target), " "quest_condition=VALUES(quest_condition), quest_reward=VALUES(quest_reward), " "quest_task=VALUES(quest_task), quest_template=VALUES(quest_template), " "quest_pokemon_form_id=VALUES(quest_pokemon_form_id), " "quest_pokemon_costume_id=VALUES(quest_pokemon_costume_id), " "quest_title=VALUES(quest_title)" ) insert_values = ( fort_id, quest_type, time.time(), stardust, pokemon_id, form_id, costume_id, reward_type, item_item, item_amount, target, json_condition, json.dumps(rewards), task, quest_template, quest_title_resource_id ) origin_logger.debug3("DbPogoProtoSubmit::quest submitted quest type {} at stop {}", quest_type, fort_id) self._db_exec.execute(query_quests, insert_values, commit=True) return True
[ "def", "quest", "(", "self", ",", "origin", ":", "str", ",", "quest_proto", ":", "dict", ",", "mitm_mapper", ",", "quest_gen", ":", "QuestGen", ")", ":", "origin_logger", "=", "get_origin_logger", "(", "logger", ",", "origin", "=", "origin", ")", "origin_l...
https://github.com/Map-A-Droid/MAD/blob/81375b5c9ccc5ca3161eb487aa81469d40ded221/mapadroid/db/DbPogoProtoSubmit.py#L659-L730
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/platform.py
python
_syscmd_file
(target, default='')
return output.decode('latin-1')
Interface to the system's file command. The function uses the -b option of the file command to have it omit the filename in its output. Follow the symlinks. It returns default in case the command should fail.
Interface to the system's file command.
[ "Interface", "to", "the", "system", "s", "file", "command", "." ]
def _syscmd_file(target, default=''): """ Interface to the system's file command. The function uses the -b option of the file command to have it omit the filename in its output. Follow the symlinks. It returns default in case the command should fail. """ if sys.platform in ('dos', 'win32', 'win16'): # XXX Others too ? return default import subprocess target = _follow_symlinks(target) # "file" output is locale dependent: force the usage of the C locale # to get deterministic behavior. env = dict(os.environ, LC_ALL='C') try: # -b: do not prepend filenames to output lines (brief mode) output = subprocess.check_output(['file', '-b', target], stderr=subprocess.DEVNULL, env=env) except (OSError, subprocess.CalledProcessError): return default if not output: return default # With the C locale, the output should be mostly ASCII-compatible. # Decode from Latin-1 to prevent Unicode decode error. return output.decode('latin-1')
[ "def", "_syscmd_file", "(", "target", ",", "default", "=", "''", ")", ":", "if", "sys", ".", "platform", "in", "(", "'dos'", ",", "'win32'", ",", "'win16'", ")", ":", "# XXX Others too ?", "return", "default", "import", "subprocess", "target", "=", "_follo...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/platform.py#L620-L649
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/ecobee/climate.py
python
Thermostat.target_temperature_step
(self)
return PRECISION_HALVES
Set target temperature step to halves.
Set target temperature step to halves.
[ "Set", "target", "temperature", "step", "to", "halves", "." ]
def target_temperature_step(self) -> float: """Set target temperature step to halves.""" return PRECISION_HALVES
[ "def", "target_temperature_step", "(", "self", ")", "->", "float", ":", "return", "PRECISION_HALVES" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/ecobee/climate.py#L424-L426
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/parfors/parfor.py
python
ParforDiagnostics.sort_pf_by_line
(self, pf_id, parfors_simple)
return line
pd_id - the parfors id parfors_simple - the simple parfors map
pd_id - the parfors id parfors_simple - the simple parfors map
[ "pd_id", "-", "the", "parfors", "id", "parfors_simple", "-", "the", "simple", "parfors", "map" ]
def sort_pf_by_line(self, pf_id, parfors_simple): """ pd_id - the parfors id parfors_simple - the simple parfors map """ # this sorts parfors by source line number pf = parfors_simple[pf_id][0] pattern = pf.patterns[0] line = max(0, pf.loc.line - 1) # why are these out by 1 ?! filename = self.func_ir.loc.filename nadj, nroots = self.compute_graph_info(self.nested_fusion_info) fadj, froots = self.compute_graph_info(self.fusion_info) graphs = [nadj, fadj] # If the parfor is internal, like internal prange, then the # default line number is from its location in the numba source # To get a more accurate line number, this first checks the # adjacency graph for fused parfors that might not be internal # and uses the minimum line number from there. If that fails # (case where there's just a single internal parfor) the IR # is walked backwards from the parfor location and the first non # parfor statement line number is used. if isinstance(pattern, tuple): if pattern[1] == 'internal': reported_loc = pattern[2][1] if reported_loc.filename == filename: return max(0, reported_loc.line - 1) else: # first recurse and check the adjacency list for # something that is not an in internal parfor tmp = [] for adj in graphs: if adj: # graph may be empty, e.g. no nesting for k in adj[pf_id]: tmp.append(self.sort_pf_by_line(k, parfors_simple)) if tmp: return max(0, min(tmp) - 1) # second run through the parfor block to see if there's # and reference to a line number in the user source for blk in pf.loop_body.values(): for stmt in blk.body: if stmt.loc.filename == filename: return max(0, stmt.loc.line - 1) # finally run through the func_ir and look for the # first non-parfor statement prior to this one and # grab the line from that for blk in self.func_ir.blocks.values(): try: idx = blk.body.index(pf) for i in range(idx - 1, 0, -1): stmt = blk.body[i] if not isinstance(stmt, Parfor): line = max(0, stmt.loc.line - 1) break except ValueError: pass return line
[ "def", "sort_pf_by_line", "(", "self", ",", "pf_id", ",", "parfors_simple", ")", ":", "# this sorts parfors by source line number", "pf", "=", "parfors_simple", "[", "pf_id", "]", "[", "0", "]", "pattern", "=", "pf", ".", "patterns", "[", "0", "]", "line", "...
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/parfors/parfor.py#L808-L864
allegroai/clearml
5953dc6eefadcdfcc2bdbb6a0da32be58823a5af
clearml/utilities/proxy_object.py
python
naive_nested_from_flat_dictionary
(flat_dict, sep='/')
return { sub_prefix: ( bucket[0][1] if (len(bucket) == 1 and sub_prefix == bucket[0][0]) else naive_nested_from_flat_dictionary( { k[len(sub_prefix) + 1:]: v for k, v in bucket if len(k) > len(sub_prefix) }, sep=sep ) ) for sub_prefix, bucket in ( (key, list(group)) for key, group in itertools.groupby( sorted(flat_dict.items()), key=lambda item: item[0].partition(sep)[0] ) ) }
A naive conversion of a flat dictionary with '/'-separated keys signifying nesting into a nested dictionary.
A naive conversion of a flat dictionary with '/'-separated keys signifying nesting into a nested dictionary.
[ "A", "naive", "conversion", "of", "a", "flat", "dictionary", "with", "/", "-", "separated", "keys", "signifying", "nesting", "into", "a", "nested", "dictionary", "." ]
def naive_nested_from_flat_dictionary(flat_dict, sep='/'): """ A naive conversion of a flat dictionary with '/'-separated keys signifying nesting into a nested dictionary. """ return { sub_prefix: ( bucket[0][1] if (len(bucket) == 1 and sub_prefix == bucket[0][0]) else naive_nested_from_flat_dictionary( { k[len(sub_prefix) + 1:]: v for k, v in bucket if len(k) > len(sub_prefix) }, sep=sep ) ) for sub_prefix, bucket in ( (key, list(group)) for key, group in itertools.groupby( sorted(flat_dict.items()), key=lambda item: item[0].partition(sep)[0] ) ) }
[ "def", "naive_nested_from_flat_dictionary", "(", "flat_dict", ",", "sep", "=", "'/'", ")", ":", "return", "{", "sub_prefix", ":", "(", "bucket", "[", "0", "]", "[", "1", "]", "if", "(", "len", "(", "bucket", ")", "==", "1", "and", "sub_prefix", "==", ...
https://github.com/allegroai/clearml/blob/5953dc6eefadcdfcc2bdbb6a0da32be58823a5af/clearml/utilities/proxy_object.py#L134-L156
svpcom/wifibroadcast
51251b8c484b8c4f548aa3bbb1633e0edbb605dc
telemetry/mavlink.py
python
MAVLink.log_request_end_encode
(self, target_system, target_component)
return MAVLink_log_request_end_message(target_system, target_component)
Stop log transfer and resume normal logging target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t)
Stop log transfer and resume normal logging
[ "Stop", "log", "transfer", "and", "resume", "normal", "logging" ]
def log_request_end_encode(self, target_system, target_component): ''' Stop log transfer and resume normal logging target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) ''' return MAVLink_log_request_end_message(target_system, target_component)
[ "def", "log_request_end_encode", "(", "self", ",", "target_system", ",", "target_component", ")", ":", "return", "MAVLink_log_request_end_message", "(", "target_system", ",", "target_component", ")" ]
https://github.com/svpcom/wifibroadcast/blob/51251b8c484b8c4f548aa3bbb1633e0edbb605dc/telemetry/mavlink.py#L25559-L25567
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/click/utils.py
python
echo
( message: t.Optional[t.Any] = None, file: t.Optional[t.IO] = None, nl: bool = True, err: bool = False, color: t.Optional[bool] = None, )
Print a message and newline to stdout or a file. This should be used instead of :func:`print` because it provides better support for different data, files, and environments. Compared to :func:`print`, this does the following: - Ensures that the output encoding is not misconfigured on Linux. - Supports Unicode in the Windows console. - Supports writing to binary outputs, and supports writing bytes to text outputs. - Supports colors and styles on Windows. - Removes ANSI color and style codes if the output does not look like an interactive terminal. - Always flushes the output. :param message: The string or bytes to output. Other objects are converted to strings. :param file: The file to write to. Defaults to ``stdout``. :param err: Write to ``stderr`` instead of ``stdout``. :param nl: Print a newline after the message. Enabled by default. :param color: Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal. .. versionchanged:: 6.0 Support Unicode output on the Windows console. Click does not modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` will still not support Unicode. .. versionchanged:: 4.0 Added the ``color`` parameter. .. versionadded:: 3.0 Added the ``err`` parameter. .. versionchanged:: 2.0 Support colors on Windows if colorama is installed.
Print a message and newline to stdout or a file. This should be used instead of :func:`print` because it provides better support for different data, files, and environments.
[ "Print", "a", "message", "and", "newline", "to", "stdout", "or", "a", "file", ".", "This", "should", "be", "used", "instead", "of", ":", "func", ":", "print", "because", "it", "provides", "better", "support", "for", "different", "data", "files", "and", "...
def echo( message: t.Optional[t.Any] = None, file: t.Optional[t.IO] = None, nl: bool = True, err: bool = False, color: t.Optional[bool] = None, ) -> None: """Print a message and newline to stdout or a file. This should be used instead of :func:`print` because it provides better support for different data, files, and environments. Compared to :func:`print`, this does the following: - Ensures that the output encoding is not misconfigured on Linux. - Supports Unicode in the Windows console. - Supports writing to binary outputs, and supports writing bytes to text outputs. - Supports colors and styles on Windows. - Removes ANSI color and style codes if the output does not look like an interactive terminal. - Always flushes the output. :param message: The string or bytes to output. Other objects are converted to strings. :param file: The file to write to. Defaults to ``stdout``. :param err: Write to ``stderr`` instead of ``stdout``. :param nl: Print a newline after the message. Enabled by default. :param color: Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal. .. versionchanged:: 6.0 Support Unicode output on the Windows console. Click does not modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` will still not support Unicode. .. versionchanged:: 4.0 Added the ``color`` parameter. .. versionadded:: 3.0 Added the ``err`` parameter. .. versionchanged:: 2.0 Support colors on Windows if colorama is installed. """ if file is None: if err: file = _default_text_stderr() else: file = _default_text_stdout() # Convert non bytes/text into the native string type. if message is not None and not isinstance(message, (str, bytes, bytearray)): out: t.Optional[t.Union[str, bytes]] = str(message) else: out = message if nl: out = out or "" if isinstance(out, str): out += "\n" else: out += b"\n" if not out: file.flush() return # If there is a message and the value looks like bytes, we manually # need to find the binary stream and write the message in there. # This is done separately so that most stream types will work as you # would expect. Eg: you can write to StringIO for other cases. if isinstance(out, (bytes, bytearray)): binary_file = _find_binary_writer(file) if binary_file is not None: file.flush() binary_file.write(out) binary_file.flush() return # ANSI style code support. For no message or bytes, nothing happens. # When outputting to a file instead of a terminal, strip codes. else: color = resolve_color_default(color) if should_strip_ansi(file, color): out = strip_ansi(out) elif WIN: if auto_wrap_for_ansi is not None: file = auto_wrap_for_ansi(file) # type: ignore elif not color: out = strip_ansi(out) file.write(out) # type: ignore file.flush()
[ "def", "echo", "(", "message", ":", "t", ".", "Optional", "[", "t", ".", "Any", "]", "=", "None", ",", "file", ":", "t", ".", "Optional", "[", "t", ".", "IO", "]", "=", "None", ",", "nl", ":", "bool", "=", "True", ",", "err", ":", "bool", "...
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/click/utils.py#L204-L299
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/wsgiref/validate.py
python
IteratorWrapper.__init__
(self, wsgi_iterator, check_start_response)
[]
def __init__(self, wsgi_iterator, check_start_response): self.original_iterator = wsgi_iterator self.iterator = iter(wsgi_iterator) self.closed = False self.check_start_response = check_start_response
[ "def", "__init__", "(", "self", ",", "wsgi_iterator", ",", "check_start_response", ")", ":", "self", ".", "original_iterator", "=", "wsgi_iterator", "self", ".", "iterator", "=", "iter", "(", "wsgi_iterator", ")", "self", ".", "closed", "=", "False", "self", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/wsgiref/validate.py#L265-L269
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/boto-2.46.1/boto/utils.py
python
find_matching_headers
(name, headers)
return [h for h in headers if h.lower() == name.lower()]
Takes a specific header name and a dict of headers {"name": "value"}. Returns a list of matching header names, case-insensitive.
Takes a specific header name and a dict of headers {"name": "value"}. Returns a list of matching header names, case-insensitive.
[ "Takes", "a", "specific", "header", "name", "and", "a", "dict", "of", "headers", "{", "name", ":", "value", "}", ".", "Returns", "a", "list", "of", "matching", "header", "names", "case", "-", "insensitive", "." ]
def find_matching_headers(name, headers): """ Takes a specific header name and a dict of headers {"name": "value"}. Returns a list of matching header names, case-insensitive. """ return [h for h in headers if h.lower() == name.lower()]
[ "def", "find_matching_headers", "(", "name", ",", "headers", ")", ":", "return", "[", "h", "for", "h", "in", "headers", "if", "h", ".", "lower", "(", ")", "==", "name", ".", "lower", "(", ")", "]" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/boto-2.46.1/boto/utils.py#L1025-L1031
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/volume/drivers/ibm/flashsystem_common.py
python
FlashSystemDriver._delete_vdisk
(self, name, force)
Deletes existing vdisks.
Deletes existing vdisks.
[ "Deletes", "existing", "vdisks", "." ]
def _delete_vdisk(self, name, force): """Deletes existing vdisks.""" LOG.debug('enter: _delete_vdisk: vdisk %s.', name) # Try to delete volume only if found on the storage vdisk_defined = self._is_vdisk_defined(name) if not vdisk_defined: LOG.warning('warning: Tried to delete vdisk %s but ' 'it does not exist.', name) return ssh_cmd = ['svctask', 'rmvdisk', '-force', name] if not force: ssh_cmd.remove('-force') out, err = self._ssh(ssh_cmd) # No output should be returned from rmvdisk self._assert_ssh_return( (not out.strip()), ('_delete_vdisk %(name)s') % {'name': name}, ssh_cmd, out, err) LOG.debug('leave: _delete_vdisk: vdisk %s.', name)
[ "def", "_delete_vdisk", "(", "self", ",", "name", ",", "force", ")", ":", "LOG", ".", "debug", "(", "'enter: _delete_vdisk: vdisk %s.'", ",", "name", ")", "# Try to delete volume only if found on the storage", "vdisk_defined", "=", "self", ".", "_is_vdisk_defined", "(...
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/ibm/flashsystem_common.py#L345-L367
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/django/db/backends/creation.py
python
BaseDatabaseCreation.sql_indexes_for_model
(self, model, style)
return output
Returns the CREATE INDEX SQL statements for a single model.
Returns the CREATE INDEX SQL statements for a single model.
[ "Returns", "the", "CREATE", "INDEX", "SQL", "statements", "for", "a", "single", "model", "." ]
def sql_indexes_for_model(self, model, style): """ Returns the CREATE INDEX SQL statements for a single model. """ if not model._meta.managed or model._meta.proxy or model._meta.swapped: return [] output = [] for f in model._meta.local_fields: output.extend(self.sql_indexes_for_field(model, f, style)) for fs in model._meta.index_together: fields = [model._meta.get_field_by_name(f)[0] for f in fs] output.extend(self.sql_indexes_for_fields(model, fields, style)) return output
[ "def", "sql_indexes_for_model", "(", "self", ",", "model", ",", "style", ")", ":", "if", "not", "model", ".", "_meta", ".", "managed", "or", "model", ".", "_meta", ".", "proxy", "or", "model", ".", "_meta", ".", "swapped", ":", "return", "[", "]", "o...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/django/db/backends/creation.py#L171-L183
mozilla/TTS
e9e07844b77a43fb0864354791fb4cf72ffded11
TTS/vocoder/layers/upsample.py
python
Stretch2d.forward
(self, x)
return F.interpolate( x, scale_factor=(self.y_scale, self.x_scale), mode=self.mode)
x (Tensor): Input tensor (B, C, F, T). Tensor: Interpolated tensor (B, C, F * y_scale, T * x_scale),
x (Tensor): Input tensor (B, C, F, T). Tensor: Interpolated tensor (B, C, F * y_scale, T * x_scale),
[ "x", "(", "Tensor", ")", ":", "Input", "tensor", "(", "B", "C", "F", "T", ")", ".", "Tensor", ":", "Interpolated", "tensor", "(", "B", "C", "F", "*", "y_scale", "T", "*", "x_scale", ")" ]
def forward(self, x): """ x (Tensor): Input tensor (B, C, F, T). Tensor: Interpolated tensor (B, C, F * y_scale, T * x_scale), """ return F.interpolate( x, scale_factor=(self.y_scale, self.x_scale), mode=self.mode)
[ "def", "forward", "(", "self", ",", "x", ")", ":", "return", "F", ".", "interpolate", "(", "x", ",", "scale_factor", "=", "(", "self", ".", "y_scale", ",", "self", ".", "x_scale", ")", ",", "mode", "=", "self", ".", "mode", ")" ]
https://github.com/mozilla/TTS/blob/e9e07844b77a43fb0864354791fb4cf72ffded11/TTS/vocoder/layers/upsample.py#L12-L18
clovaai/assembled-cnn
9cdc29761d828ecd3708ea13e5acc44c696ec30f
preprocessing/inception_preprocessing.py
python
preprocess_for_eval
(image, height, width, central_fraction=0.875, scope=None)
Prepare one image for evaluation. If height and width are specified it would output an image with that size by applying resize_bilinear. If central_fraction is specified it would crop the central fraction of the input image. Args: image: 3-D Tensor of image. If dtype is tf.float32 then the range should be [0, 1], otherwise it would converted to tf.float32 assuming that the range is [0, MAX], where MAX is largest positive representable number for int(8/16/32) data type (see `tf.image.convert_image_dtype` for details). height: integer width: integer central_fraction: Optional Float, fraction of the image to crop. scope: Optional scope for name_scope. Returns: 3-D float Tensor of prepared image.
Prepare one image for evaluation.
[ "Prepare", "one", "image", "for", "evaluation", "." ]
def preprocess_for_eval(image, height, width, central_fraction=0.875, scope=None): """Prepare one image for evaluation. If height and width are specified it would output an image with that size by applying resize_bilinear. If central_fraction is specified it would crop the central fraction of the input image. Args: image: 3-D Tensor of image. If dtype is tf.float32 then the range should be [0, 1], otherwise it would converted to tf.float32 assuming that the range is [0, MAX], where MAX is largest positive representable number for int(8/16/32) data type (see `tf.image.convert_image_dtype` for details). height: integer width: integer central_fraction: Optional Float, fraction of the image to crop. scope: Optional scope for name_scope. Returns: 3-D float Tensor of prepared image. """ with tf.name_scope(scope, 'eval_image', [image, height, width]): image = tf.image.decode_jpeg(image, channels=3) if image.dtype != tf.float32: image = tf.image.convert_image_dtype(image, dtype=tf.float32) # Crop the central region of the image with an area containing 87.5% of # the original image. if central_fraction: image = tf.image.central_crop(image, central_fraction=central_fraction) if height and width: # Resize the image to the specified height and width. image = tf.expand_dims(image, 0) image = tf.image.resize_bilinear(image, [height, width], align_corners=False) image = tf.squeeze(image, [0]) image.set_shape([height, width, 3]) return image
[ "def", "preprocess_for_eval", "(", "image", ",", "height", ",", "width", ",", "central_fraction", "=", "0.875", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'eval_image'", ",", "[", "image", ",", "height", ","...
https://github.com/clovaai/assembled-cnn/blob/9cdc29761d828ecd3708ea13e5acc44c696ec30f/preprocessing/inception_preprocessing.py#L302-L340
dustin/py-github
1b2f55e7b73ede3b16062b2a1195fb47153bae42
github/github.py
python
parses
(t)
return f
Parser for a specific type in the github response.
Parser for a specific type in the github response.
[ "Parser", "for", "a", "specific", "type", "in", "the", "github", "response", "." ]
def parses(t): """Parser for a specific type in the github response.""" def f(orig): orig.parses = t return orig return f
[ "def", "parses", "(", "t", ")", ":", "def", "f", "(", "orig", ")", ":", "orig", ".", "parses", "=", "t", "return", "orig", "return", "f" ]
https://github.com/dustin/py-github/blob/1b2f55e7b73ede3b16062b2a1195fb47153bae42/github/github.py#L85-L90
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/distutils/dist.py
python
Distribution._set_command_options
(self, command_obj, option_dict=None)
Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command'). 'command_obj' must be a Command instance. If 'option_dict' is not supplied, uses the standard option dictionary for this command (from 'self.command_options').
Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command').
[ "Set", "the", "options", "for", "command_obj", "from", "option_dict", ".", "Basically", "this", "means", "copying", "elements", "of", "a", "dictionary", "(", "option_dict", ")", "to", "attributes", "of", "an", "instance", "(", "command", ")", "." ]
def _set_command_options(self, command_obj, option_dict=None): """Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command'). 'command_obj' must be a Command instance. If 'option_dict' is not supplied, uses the standard option dictionary for this command (from 'self.command_options'). """ command_name = command_obj.get_command_name() if option_dict is None: option_dict = self.get_option_dict(command_name) if DEBUG: self.announce(" setting options for '%s' command:" % command_name) for (option, (source, value)) in option_dict.items(): if DEBUG: self.announce(" %s = %s (from %s)" % (option, value, source)) try: bool_opts = [translate_longopt(o) for o in command_obj.boolean_options] except AttributeError: bool_opts = [] try: neg_opt = command_obj.negative_opt except AttributeError: neg_opt = {} try: is_string = isinstance(value, str) if option in neg_opt and is_string: setattr(command_obj, neg_opt[option], not strtobool(value)) elif option in bool_opts and is_string: setattr(command_obj, option, strtobool(value)) elif hasattr(command_obj, option): setattr(command_obj, option, value) else: raise DistutilsOptionError( "error in %s: command '%s' has no such option '%s'" % (source, command_name, option)) except ValueError as msg: raise DistutilsOptionError(msg)
[ "def", "_set_command_options", "(", "self", ",", "command_obj", ",", "option_dict", "=", "None", ")", ":", "command_name", "=", "command_obj", ".", "get_command_name", "(", ")", "if", "option_dict", "is", "None", ":", "option_dict", "=", "self", ".", "get_opti...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/distutils/dist.py#L872-L914
songyingxin/python-algorithm
1c3cc9f73687f5bf291d95d4c6558d982ad98985
前缀树/leetcode_208_Trie.py
python
Trie.__init__
(self)
Initialize your data structure here.
Initialize your data structure here.
[ "Initialize", "your", "data", "structure", "here", "." ]
def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode()
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "root", "=", "TrieNode", "(", ")" ]
https://github.com/songyingxin/python-algorithm/blob/1c3cc9f73687f5bf291d95d4c6558d982ad98985/前缀树/leetcode_208_Trie.py#L51-L55
ShreyAmbesh/Traffic-Rule-Violation-Detection-System
ae0c327ce014ce6a427da920b5798a0d4bbf001e
utils/object_detection_evaluation.py
python
DetectionEvaluator.__init__
(self, categories)
Constructor. Args: categories: A list of dicts, each of which has the following keys - 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog'.
Constructor.
[ "Constructor", "." ]
def __init__(self, categories): """Constructor. Args: categories: A list of dicts, each of which has the following keys - 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog'. """ self._categories = categories
[ "def", "__init__", "(", "self", ",", "categories", ")", ":", "self", ".", "_categories", "=", "categories" ]
https://github.com/ShreyAmbesh/Traffic-Rule-Violation-Detection-System/blob/ae0c327ce014ce6a427da920b5798a0d4bbf001e/utils/object_detection_evaluation.py#L61-L69
xiadingZ/video-caption.pytorch
0597647c9f1f756202ba7ff9898ad0a26847480f
misc/utils.py
python
RewardCriterion.__init__
(self)
[]
def __init__(self): super(RewardCriterion, self).__init__()
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "RewardCriterion", ",", "self", ")", ".", "__init__", "(", ")" ]
https://github.com/xiadingZ/video-caption.pytorch/blob/0597647c9f1f756202ba7ff9898ad0a26847480f/misc/utils.py#L27-L28
OpenCobolIDE/OpenCobolIDE
c78d0d335378e5fe0a5e74f53c19b68b55e85388
open_cobol_ide/extlibs/future/types/newbytes.py
python
newbytes.__getslice__
(self, *args)
return self.__getitem__(slice(*args))
[]
def __getslice__(self, *args): return self.__getitem__(slice(*args))
[ "def", "__getslice__", "(", "self", ",", "*", "args", ")", ":", "return", "self", ".", "__getitem__", "(", "slice", "(", "*", "args", ")", ")" ]
https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/future/types/newbytes.py#L145-L146
minimaxir/person-blocker
82cc1bab629ff9faf610861bf94660d0131c38ec
utils.py
python
minimize_mask
(bbox, mask, mini_shape)
return mini_mask
Resize masks to a smaller version to cut memory load. Mini-masks can then resized back to image scale using expand_masks() See inspect_data.ipynb notebook for more details.
Resize masks to a smaller version to cut memory load. Mini-masks can then resized back to image scale using expand_masks()
[ "Resize", "masks", "to", "a", "smaller", "version", "to", "cut", "memory", "load", ".", "Mini", "-", "masks", "can", "then", "resized", "back", "to", "image", "scale", "using", "expand_masks", "()" ]
def minimize_mask(bbox, mask, mini_shape): """Resize masks to a smaller version to cut memory load. Mini-masks can then resized back to image scale using expand_masks() See inspect_data.ipynb notebook for more details. """ mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool) for i in range(mask.shape[-1]): m = mask[:, :, i] y1, x1, y2, x2 = bbox[i][:4] m = m[y1:y2, x1:x2] if m.size == 0: raise Exception("Invalid bounding box with area of zero") m = scipy.misc.imresize(m.astype(float), mini_shape, interp='bilinear') mini_mask[:, :, i] = np.where(m >= 128, 1, 0) return mini_mask
[ "def", "minimize_mask", "(", "bbox", ",", "mask", ",", "mini_shape", ")", ":", "mini_mask", "=", "np", ".", "zeros", "(", "mini_shape", "+", "(", "mask", ".", "shape", "[", "-", "1", "]", ",", ")", ",", "dtype", "=", "bool", ")", "for", "i", "in"...
https://github.com/minimaxir/person-blocker/blob/82cc1bab629ff9faf610861bf94660d0131c38ec/utils.py#L450-L465
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/template/defaulttags.py
python
templatetag
(parser, token)
return TemplateTagNode(tag)
Outputs one of the bits used to compose template tags. Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the ``{% templatetag %}`` tag. The argument tells which template bit to output: ================== ======= Argument Outputs ================== ======= ``openblock`` ``{%`` ``closeblock`` ``%}`` ``openvariable`` ``{{`` ``closevariable`` ``}}`` ``openbrace`` ``{`` ``closebrace`` ``}`` ``opencomment`` ``{#`` ``closecomment`` ``#}`` ================== =======
Outputs one of the bits used to compose template tags.
[ "Outputs", "one", "of", "the", "bits", "used", "to", "compose", "template", "tags", "." ]
def templatetag(parser, token): """ Outputs one of the bits used to compose template tags. Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the ``{% templatetag %}`` tag. The argument tells which template bit to output: ================== ======= Argument Outputs ================== ======= ``openblock`` ``{%`` ``closeblock`` ``%}`` ``openvariable`` ``{{`` ``closevariable`` ``}}`` ``openbrace`` ``{`` ``closebrace`` ``}`` ``opencomment`` ``{#`` ``closecomment`` ``#}`` ================== ======= """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'templatetag' statement takes one argument") tag = bits[1] if tag not in TemplateTagNode.mapping: raise TemplateSyntaxError("Invalid templatetag argument: '%s'." " Must be one of: %s" % (tag, list(TemplateTagNode.mapping))) return TemplateTagNode(tag)
[ "def", "templatetag", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "bits", ")", "!=", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'templatetag' statement takes one argument\"", ...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/template/defaulttags.py#L1167-L1197
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/core/leoKeys.py
python
FileNameChooser.do_back_space
(self)
Handle a back space.
Handle a back space.
[ "Handle", "a", "back", "space", "." ]
def do_back_space(self): """Handle a back space.""" w = self.c.k.w if w and w.hasSelection(): # s = w.getAllText() i, j = w.getSelectionRange() w.delete(i, j) s = self.get_label() else: s = self.get_label() if s: s = s[:-1] self.set_label(s) if s: common_prefix, tabList = self.compute_tab_list() # Do *not* extend the label to the common prefix. else: tabList = [] self.show_tab_list(tabList)
[ "def", "do_back_space", "(", "self", ")", ":", "w", "=", "self", ".", "c", ".", "k", ".", "w", "if", "w", "and", "w", ".", "hasSelection", "(", ")", ":", "# s = w.getAllText()", "i", ",", "j", "=", "w", ".", "getSelectionRange", "(", ")", "w", "....
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/leoKeys.py#L1098-L1116
TensorMSA/tensormsa
c36b565159cd934533636429add3c7d7263d622b
chatbot/services/service_provider.py
python
ServiceProvider.run
(self, share_data)
return share_data
run service based on decision :param share_data: :return:
run service based on decision :param share_data: :return:
[ "run", "service", "based", "on", "decision", ":", "param", "share_data", ":", ":", "return", ":" ]
def run(self, share_data): """ run service based on decision :param share_data: :return: """ print("■■■■■■■■■■ 서비스 호출 대상 판단 : " + share_data.get_story_id() ) #Call Image Reconize if(share_data.get_service_type() == "find_image") : share_data = self._internal_service_call(share_data) #Exist Story Response elif(share_data.get_story_id() != '99') : share_data = ResponseGenerator().select_response(share_data) return share_data
[ "def", "run", "(", "self", ",", "share_data", ")", ":", "print", "(", "\"■■■■■■■■■■ 서비스 호출 대상 판단 : \" + share_data.get_story_id() )", "", "", "", "", "", "", "", "#Call Image Reconize", "if", "(", "share_data", ".", "get_service_type", "(", ")", "==", "\"find_im...
https://github.com/TensorMSA/tensormsa/blob/c36b565159cd934533636429add3c7d7263d622b/chatbot/services/service_provider.py#L15-L28
mudpi/mudpi-core
fb206b1136f529c7197f1e6b29629ed05630d377
mudpi/extensions/nanpy/__init__.py
python
Node.connect
(self)
return conn
Setup connection to a node over wifi or serial
Setup connection to a node over wifi or serial
[ "Setup", "connection", "to", "a", "node", "over", "wifi", "or", "serial" ]
def connect(self): """ Setup connection to a node over wifi or serial """ if self.connected: return True with self._lock: # Check again if node connected while waiting on lock if self.connected: return True attempts = 3 conn = None if self.config.get('use_wifi', False): while attempts > 0 and self.mudpi.is_running: try: Logger.log_formatted(LOG_LEVEL["debug"], f'{self.name} -> Wifi ', 'Connecting', 'notice') attempts -= 1 conn = SocketManager( host=str(self.config.get('address', 'mudpi-nanpy.local'))) # Test the connection with api self.api = ArduinoApi(connection=conn) except (SocketManagerError, BrokenPipeError, ConnectionResetError, socket.timeout) as e: Logger.log_formatted(LOG_LEVEL["warning"], f'{self.name} -> Failed Connection ', 'Timeout', 'notice') if attempts > 0: Logger.log_formatted(LOG_LEVEL["info"], f'{self.name} -> Preparing Reconnect ', 'Pending', 'notice') else: Logger.log_formatted(LOG_LEVEL["error"], f'{self.name} -> Connection Attempts ', 'Failed', 'error') conn = None self.reset_connection() self._wait(5) except (OSError, KeyError) as e: Logger.log(LOG_LEVEL["error"], f"[{self.name}] Node Not Found. (Is it online?)") conn = None self.reset_connection() self._wait(5) else: Logger.log_formatted(LOG_LEVEL["info"], f"{self.name} -> Wifi Connection ", 'Connected', 'success') break else: while attempts > 0 and self.mudpi.is_running: try: attempts -= 1 conn = SerialManager(device=str(self.config.get('address', '/dev/ttyUSB1'))) self.api = ArduinoApi(connection=conn) except SerialManagerError: Logger.log_formatted(LOG_LEVEL["warning"], f"{self.name} -> Connecting ", 'Timeout', 'notice') if attempts > 0: Logger.log_formatted(LOG_LEVEL["info"], f'{self.name} -> Preparing Reconnect ', 'Pending', 'notice') else: Logger.log_formatted(LOG_LEVEL["error"], f'{self.name} -> Connection Attempts ', 'Failed', 'error') self.reset_connection() conn = None self._wait(5) else: if conn is not None: Logger.log_formatted(LOG_LEVEL["info"], f'[{self.name}] -> Serial Connection ', 'Connected', 'success') break if conn is not None: self.connection = conn self._node_connected.set() self._node_ready.set() return conn
[ "def", "connect", "(", "self", ")", ":", "if", "self", ".", "connected", ":", "return", "True", "with", "self", ".", "_lock", ":", "# Check again if node connected while waiting on lock", "if", "self", ".", "connected", ":", "return", "True", "attempts", "=", ...
https://github.com/mudpi/mudpi-core/blob/fb206b1136f529c7197f1e6b29629ed05630d377/mudpi/extensions/nanpy/__init__.py#L129-L201
rytilahti/python-miio
b6e53dd16fac77915426e7592e2528b78ef65190
miio/gateway/gateway.py
python
Gateway.discover_devices
(self)
return self._devices
Discovers SubDevices and returns a list of the discovered devices.
Discovers SubDevices and returns a list of the discovered devices.
[ "Discovers", "SubDevices", "and", "returns", "a", "list", "of", "the", "discovered", "devices", "." ]
def discover_devices(self): """Discovers SubDevices and returns a list of the discovered devices.""" self._devices = {} # Skip the models which do not support getting the device list if self.model == GATEWAY_MODEL_EU: _LOGGER.warning( "Gateway model '%s' does not (yet) support getting the device list, " "try using the get_devices_from_dict function with micloud", self.model, ) return self._devices if self.model == GATEWAY_MODEL_ZIG3: # self.get_prop("device_list") does not work for the GATEWAY_MODEL_ZIG3 # self.send("get_device_list") does work for the GATEWAY_MODEL_ZIG3 but gives slightly diffrent return values devices_raw = self.send("get_device_list") if type(devices_raw) != list: _LOGGER.debug( "Gateway response to 'get_device_list' not a list type, no zigbee devices connected." ) return self._devices for device in devices_raw: # Match 'model' to get the model_info model_info = self.match_zigbee_model(device["model"], device["did"]) # Extract discovered information dev_info = SubDeviceInfo( device["did"], model_info["type_id"], -1, -1, -1 ) # Setup the device self.setup_device(dev_info, model_info) else: devices_raw = self.get_prop("device_list") for x in range(0, len(devices_raw), 5): # Extract discovered information dev_info = SubDeviceInfo(*devices_raw[x : x + 5]) # Match 'type_id' to get the model_info model_info = self.match_type_id(dev_info.type_id, dev_info.sid) # Setup the device self.setup_device(dev_info, model_info) return self._devices
[ "def", "discover_devices", "(", "self", ")", ":", "self", ".", "_devices", "=", "{", "}", "# Skip the models which do not support getting the device list", "if", "self", ".", "model", "==", "GATEWAY_MODEL_EU", ":", "_LOGGER", ".", "warning", "(", "\"Gateway model '%s'...
https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/gateway/gateway.py#L162-L211
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/decimal.py
python
Decimal.to_integral_value
(self, rounding=None, context=None)
Rounds to the nearest integer, without raising inexact, rounded.
Rounds to the nearest integer, without raising inexact, rounded.
[ "Rounds", "to", "the", "nearest", "integer", "without", "raising", "inexact", "rounded", "." ]
def to_integral_value(self, rounding=None, context=None): """Rounds to the nearest integer, without raising inexact, rounded.""" if context is None: context = getcontext() if rounding is None: rounding = context.rounding if self._is_special: ans = self._check_nans(context=context) if ans: return ans return Decimal(self) if self._exp >= 0: return Decimal(self) else: return self._rescale(0, rounding)
[ "def", "to_integral_value", "(", "self", ",", "rounding", "=", "None", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "if", "rounding", "is", "None", ":", "rounding", "=", "context", "...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/decimal.py#L2625-L2639
pyscf/pyscf
0adfb464333f5ceee07b664f291d4084801bae64
pyscf/pbc/cc/kccsd_t_rhf.py
python
create_eris_vooo
(ooov, nkpts, nocc, nvir, kconserv, out=None)
return out
Creates vooo from ooov array. This is not exactly chemist's notation, but close. Here a chemist notation vooo is created from physicist ooov, and then the last two indices of vooo are swapped.
Creates vooo from ooov array.
[ "Creates", "vooo", "from", "ooov", "array", "." ]
def create_eris_vooo(ooov, nkpts, nocc, nvir, kconserv, out=None): '''Creates vooo from ooov array. This is not exactly chemist's notation, but close. Here a chemist notation vooo is created from physicist ooov, and then the last two indices of vooo are swapped. ''' assert(ooov.shape == (nkpts,nkpts,nkpts,nocc,nocc,nocc,nvir)) if out is None: out = np.empty((nkpts,nkpts,nkpts,nvir,nocc,nocc,nocc), dtype=ooov.dtype) for ki, kj, ka in product(range(nkpts), repeat=3): kb = kconserv[ki,kj,ka] # <bj|ai> -> (ba|ji) (Physicist->Chemist) # (ij|ab) = (ba|ij)* (Permutational symmetry) # out = (ij|ab).transpose(0,1,3,2) out[ki,kj,kb] = ooov[kb,kj,ka].conj().transpose(3,1,0,2) return out
[ "def", "create_eris_vooo", "(", "ooov", ",", "nkpts", ",", "nocc", ",", "nvir", ",", "kconserv", ",", "out", "=", "None", ")", ":", "assert", "(", "ooov", ".", "shape", "==", "(", "nkpts", ",", "nkpts", ",", "nkpts", ",", "nocc", ",", "nocc", ",", ...
https://github.com/pyscf/pyscf/blob/0adfb464333f5ceee07b664f291d4084801bae64/pyscf/pbc/cc/kccsd_t_rhf.py#L407-L423
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pytz/tzinfo.py
python
StaticTzInfo.normalize
(self, dt, is_dst=False)
return dt.astimezone(self)
Correct the timezone information on the given datetime. This is normally a no-op, as StaticTzInfo timezones never have ambiguous cases to correct: >>> from pytz import timezone >>> gmt = timezone('GMT') >>> isinstance(gmt, StaticTzInfo) True >>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt) >>> gmt.normalize(dt) is dt True The supported method of converting between timezones is to use datetime.astimezone(). Currently normalize() also works: >>> la = timezone('America/Los_Angeles') >>> dt = la.localize(datetime(2011, 5, 7, 1, 2, 3)) >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' >>> gmt.normalize(dt).strftime(fmt) '2011-05-07 08:02:03 GMT (+0000)'
Correct the timezone information on the given datetime.
[ "Correct", "the", "timezone", "information", "on", "the", "given", "datetime", "." ]
def normalize(self, dt, is_dst=False): '''Correct the timezone information on the given datetime. This is normally a no-op, as StaticTzInfo timezones never have ambiguous cases to correct: >>> from pytz import timezone >>> gmt = timezone('GMT') >>> isinstance(gmt, StaticTzInfo) True >>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt) >>> gmt.normalize(dt) is dt True The supported method of converting between timezones is to use datetime.astimezone(). Currently normalize() also works: >>> la = timezone('America/Los_Angeles') >>> dt = la.localize(datetime(2011, 5, 7, 1, 2, 3)) >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' >>> gmt.normalize(dt).strftime(fmt) '2011-05-07 08:02:03 GMT (+0000)' ''' if dt.tzinfo is self: return dt if dt.tzinfo is None: raise ValueError('Naive time - no tzinfo set') return dt.astimezone(self)
[ "def", "normalize", "(", "self", ",", "dt", ",", "is_dst", "=", "False", ")", ":", "if", "dt", ".", "tzinfo", "is", "self", ":", "return", "dt", "if", "dt", ".", "tzinfo", "is", "None", ":", "raise", "ValueError", "(", "'Naive time - no tzinfo set'", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pytz/tzinfo.py#L111-L138
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/datetime.py
python
datetime.combine
(cls, date, time)
return cls(date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond, time.tzinfo)
Construct a datetime from a given date and a given time.
Construct a datetime from a given date and a given time.
[ "Construct", "a", "datetime", "from", "a", "given", "date", "and", "a", "given", "time", "." ]
def combine(cls, date, time): "Construct a datetime from a given date and a given time." if not isinstance(date, _date_class): raise TypeError("date argument must be a date instance") if not isinstance(time, _time_class): raise TypeError("time argument must be a time instance") return cls(date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond, time.tzinfo)
[ "def", "combine", "(", "cls", ",", "date", ",", "time", ")", ":", "if", "not", "isinstance", "(", "date", ",", "_date_class", ")", ":", "raise", "TypeError", "(", "\"date argument must be a date instance\"", ")", "if", "not", "isinstance", "(", "time", ",", ...
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/datetime.py#L1406-L1414
qilingframework/qiling
32cc674f2f6fa4b4c9d64a35a1a57853fe1e4142
qiling/hw/peripheral.py
python
QlPeripheral.size
(self)
return sum(rbound-lbound for lbound, rbound in self.region)
Calculate the memory size occupyied by peripheral. Returns: int: Size
Calculate the memory size occupyied by peripheral.
[ "Calculate", "the", "memory", "size", "occupyied", "by", "peripheral", "." ]
def size(self) -> int: """Calculate the memory size occupyied by peripheral. Returns: int: Size """ return sum(rbound-lbound for lbound, rbound in self.region)
[ "def", "size", "(", "self", ")", "->", "int", ":", "return", "sum", "(", "rbound", "-", "lbound", "for", "lbound", ",", "rbound", "in", "self", ".", "region", ")" ]
https://github.com/qilingframework/qiling/blob/32cc674f2f6fa4b4c9d64a35a1a57853fe1e4142/qiling/hw/peripheral.py#L149-L155
aliyun/aliyun-oss-python-sdk
5f2afa0928a58c7c1cc6317ac147f3637481f6fd
oss2/xml_utils.py
python
to_create_live_channel
(live_channel)
return _node_to_string(root)
[]
def to_create_live_channel(live_channel): root = ElementTree.Element('LiveChannelConfiguration') _add_text_child(root, 'Description', live_channel.description) _add_text_child(root, 'Status', live_channel.status) target_node = _add_node_child(root, 'Target') _add_text_child(target_node, 'Type', live_channel.target.type) _add_text_child(target_node, 'FragDuration', str(live_channel.target.frag_duration)) _add_text_child(target_node, 'FragCount', str(live_channel.target.frag_count)) _add_text_child(target_node, 'PlaylistName', str(live_channel.target.playlist_name)) return _node_to_string(root)
[ "def", "to_create_live_channel", "(", "live_channel", ")", ":", "root", "=", "ElementTree", ".", "Element", "(", "'LiveChannelConfiguration'", ")", "_add_text_child", "(", "root", ",", "'Description'", ",", "live_channel", ".", "description", ")", "_add_text_child", ...
https://github.com/aliyun/aliyun-oss-python-sdk/blob/5f2afa0928a58c7c1cc6317ac147f3637481f6fd/oss2/xml_utils.py#L999-L1011
pretix/pretix
96f694cf61345f54132cd26cdeb07d5d11b34232
src/pretix/control/views/__init__.py
python
LargeResultSetPage.end_index
(self)
return self.number * self.paginator.per_page
Returns the 1-based index of the last object on this page, relative to total objects found (hits).
Returns the 1-based index of the last object on this page, relative to total objects found (hits).
[ "Returns", "the", "1", "-", "based", "index", "of", "the", "last", "object", "on", "this", "page", "relative", "to", "total", "objects", "found", "(", "hits", ")", "." ]
def end_index(self): """ Returns the 1-based index of the last object on this page, relative to total objects found (hits). """ # Special case for the last page because there can be orphans. if self.number == self.paginator.num_pages: return self.paginator.count return self.number * self.paginator.per_page
[ "def", "end_index", "(", "self", ")", ":", "# Special case for the last page because there can be orphans.", "if", "self", ".", "number", "==", "self", ".", "paginator", ".", "num_pages", ":", "return", "self", ".", "paginator", ".", "count", "return", "self", "."...
https://github.com/pretix/pretix/blob/96f694cf61345f54132cd26cdeb07d5d11b34232/src/pretix/control/views/__init__.py#L139-L147
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
vsphere/datadog_checks/vsphere/api_rest.py
python
VSphereRestAPI.get_resource_tags_for_mors
(self, mors)
return resource_tags
Get resource tags. Response structure: { <RESOURCE_TYPE>: { <RESOURCE_MOR_ID>: ['<CATEGORY_NAME>:<TAG_NAME>', ...] }, ... }
Get resource tags.
[ "Get", "resource", "tags", "." ]
def get_resource_tags_for_mors(self, mors): # type: (List[vim.ManagedEntity]) -> ResourceTags """ Get resource tags. Response structure: { <RESOURCE_TYPE>: { <RESOURCE_MOR_ID>: ['<CATEGORY_NAME>:<TAG_NAME>', ...] }, ... } """ tag_associations = [] for mors_batch in self.make_batch(mors): batch_tag_associations = self._client.tagging_tag_association_list_attached_tags_on_objects(mors_batch) tag_associations.extend(batch_tag_associations) self.log.debug("Fetched tag associations: %s", tag_associations) # Initialise resource_tags resource_tags = { resource_type: defaultdict(list) for resource_type in ALL_RESOURCES_WITH_METRICS } # type: ResourceTags all_tag_ids = set() for tag_asso in tag_associations: all_tag_ids.update(tag_asso["tag_ids"]) tags = self._get_tags(all_tag_ids) for tag_asso in tag_associations: mor_id = tag_asso["object_id"]["id"] mor_type = MOR_TYPE_MAPPING_FROM_STRING[tag_asso["object_id"]["type"]] mor_tag_ids = tag_asso["tag_ids"] for mor_tag_id in mor_tag_ids: if mor_tag_id not in tags: self.log.debug("MOR tag id '%s' was not found in response, ignoring.", mor_tag_id) continue resource_tags[mor_type][mor_id].append(tags[mor_tag_id]) self.log.debug("Result resource tags: %s", resource_tags) return resource_tags
[ "def", "get_resource_tags_for_mors", "(", "self", ",", "mors", ")", ":", "# type: (List[vim.ManagedEntity]) -> ResourceTags", "tag_associations", "=", "[", "]", "for", "mors_batch", "in", "self", ".", "make_batch", "(", "mors", ")", ":", "batch_tag_associations", "=",...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/vsphere/datadog_checks/vsphere/api_rest.py#L62-L105
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/psutil/_psbsd.py
python
cpu_count_logical
()
return cext.cpu_count_logical()
Return the number of logical CPUs in the system.
Return the number of logical CPUs in the system.
[ "Return", "the", "number", "of", "logical", "CPUs", "in", "the", "system", "." ]
def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical()
[ "def", "cpu_count_logical", "(", ")", ":", "return", "cext", ".", "cpu_count_logical", "(", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/psutil/_psbsd.py#L250-L252
apple/coremltools
141a83af482fcbdd5179807c9eaff9a7999c2c49
coremltools/converters/mil/backend/mil/helper.py
python
create_tensor_value
(np_tensor)
return val
Return TensorValue.
Return TensorValue.
[ "Return", "TensorValue", "." ]
def create_tensor_value(np_tensor): """ Return TensorValue. """ builtin_type = numpy_type_to_builtin_type(np_tensor.dtype) value_type = create_valuetype_tensor(np_tensor.shape, types_to_proto_primitive(builtin_type)) val = pm.Value(type=value_type) t_val = val.immediateValue.tensor # Copy the tensor values from the input tensor t_field = _tensor_field_by_type(t_val, builtin_type) if 0 not in np_tensor.shape: if builtin_type == types.str: for x in np.nditer(np_tensor): t_field.append(x.encode("utf-8")) elif builtin_type == types.fp16: bytevals = bytes() for x in np_tensor.flatten(): bytevals += to_py_type(x) val.immediateValue.tensor.bytes.values = bytevals else: for x in np_tensor.flatten(): t_field.append(to_py_type(x)) else: # This is an "empty" tensor (tensor with a dimension being size 0) _set_empty_tensor_field_by_type(t_val, builtin_type) return val
[ "def", "create_tensor_value", "(", "np_tensor", ")", ":", "builtin_type", "=", "numpy_type_to_builtin_type", "(", "np_tensor", ".", "dtype", ")", "value_type", "=", "create_valuetype_tensor", "(", "np_tensor", ".", "shape", ",", "types_to_proto_primitive", "(", "built...
https://github.com/apple/coremltools/blob/141a83af482fcbdd5179807c9eaff9a7999c2c49/coremltools/converters/mil/backend/mil/helper.py#L140-L167
nosmokingbandit/watcher
dadacd21a5790ee609058a98a17fcc8954d24439
lib/sqlalchemy/interfaces.py
python
PoolListener.checkout
(self, dbapi_con, con_record, con_proxy)
Called when a connection is retrieved from the Pool. dbapi_con A raw DB-API connection con_record The ``_ConnectionRecord`` that persistently manages the connection con_proxy The ``_ConnectionFairy`` which manages the connection for the span of the current checkout. If you raise an ``exc.DisconnectionError``, the current connection will be disposed and a fresh connection retrieved. Processing of all checkout listeners will abort and restart using the new connection.
Called when a connection is retrieved from the Pool.
[ "Called", "when", "a", "connection", "is", "retrieved", "from", "the", "Pool", "." ]
def checkout(self, dbapi_con, con_record, con_proxy): """Called when a connection is retrieved from the Pool. dbapi_con A raw DB-API connection con_record The ``_ConnectionRecord`` that persistently manages the connection con_proxy The ``_ConnectionFairy`` which manages the connection for the span of the current checkout. If you raise an ``exc.DisconnectionError``, the current connection will be disposed and a fresh connection retrieved. Processing of all checkout listeners will abort and restart using the new connection. """
[ "def", "checkout", "(", "self", ",", "dbapi_con", ",", "con_record", ",", "con_proxy", ")", ":" ]
https://github.com/nosmokingbandit/watcher/blob/dadacd21a5790ee609058a98a17fcc8954d24439/lib/sqlalchemy/interfaces.py#L119-L136
StrangerZhang/pysot-toolkit
8b5ced3b39129b26b3700c218ffcadba7d8ad278
pysot/evaluation/ope_benchmark.py
python
OPEBenchmark.eval_precision
(self, eval_trackers=None)
return precision_ret
Args: eval_trackers: list of tracker name or single tracker name Return: res: dict of results
Args: eval_trackers: list of tracker name or single tracker name Return: res: dict of results
[ "Args", ":", "eval_trackers", ":", "list", "of", "tracker", "name", "or", "single", "tracker", "name", "Return", ":", "res", ":", "dict", "of", "results" ]
def eval_precision(self, eval_trackers=None): """ Args: eval_trackers: list of tracker name or single tracker name Return: res: dict of results """ if eval_trackers is None: eval_trackers = self.dataset.tracker_names if isinstance(eval_trackers, str): eval_trackers = [eval_trackers] precision_ret = {} for tracker_name in eval_trackers: precision_ret_ = {} for video in self.dataset: gt_traj = np.array(video.gt_traj) if tracker_name not in video.pred_trajs: tracker_traj = video.load_tracker(self.dataset.tracker_path, tracker_name, False) tracker_traj = np.array(tracker_traj) else: tracker_traj = np.array(video.pred_trajs[tracker_name]) n_frame = len(gt_traj) if hasattr(video, 'absent'): gt_traj = gt_traj[video.absent == 1] tracker_traj = tracker_traj[video.absent == 1] gt_center = self.convert_bb_to_center(gt_traj) tracker_center = self.convert_bb_to_center(tracker_traj) thresholds = np.arange(0, 51, 1) precision_ret_[video.name] = success_error(gt_center, tracker_center, thresholds, n_frame) precision_ret[tracker_name] = precision_ret_ return precision_ret
[ "def", "eval_precision", "(", "self", ",", "eval_trackers", "=", "None", ")", ":", "if", "eval_trackers", "is", "None", ":", "eval_trackers", "=", "self", ".", "dataset", ".", "tracker_names", "if", "isinstance", "(", "eval_trackers", ",", "str", ")", ":", ...
https://github.com/StrangerZhang/pysot-toolkit/blob/8b5ced3b39129b26b3700c218ffcadba7d8ad278/pysot/evaluation/ope_benchmark.py#L54-L87
MrH0wl/Cloudmare
65e5bc9888f9d362ab2abfb103ea6c1e869d67aa
thirdparty/backports/configparser/helpers.py
python
_PathLike.__fspath__
(self)
Return the file system path representation of the object.
Return the file system path representation of the object.
[ "Return", "the", "file", "system", "path", "representation", "of", "the", "object", "." ]
def __fspath__(self): """Return the file system path representation of the object.""" raise NotImplementedError
[ "def", "__fspath__", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/MrH0wl/Cloudmare/blob/65e5bc9888f9d362ab2abfb103ea6c1e869d67aa/thirdparty/backports/configparser/helpers.py#L219-L221
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas_rhino/conversions/_shapes.py
python
cone_to_rhino
(cone)
return RhinoCone(plane_to_rhino(cone.circle.plane), cone.height, cone.circle.radius)
Convert a COMPAS cone to a Rhino cone. Parameters ---------- cone: :class:`compas.geometry.Cone` Returns ------- :class:`Rhino.Geometry.Cone`
Convert a COMPAS cone to a Rhino cone.
[ "Convert", "a", "COMPAS", "cone", "to", "a", "Rhino", "cone", "." ]
def cone_to_rhino(cone): """Convert a COMPAS cone to a Rhino cone. Parameters ---------- cone: :class:`compas.geometry.Cone` Returns ------- :class:`Rhino.Geometry.Cone` """ return RhinoCone(plane_to_rhino(cone.circle.plane), cone.height, cone.circle.radius)
[ "def", "cone_to_rhino", "(", "cone", ")", ":", "return", "RhinoCone", "(", "plane_to_rhino", "(", "cone", ".", "circle", ".", "plane", ")", ",", "cone", ".", "height", ",", "cone", ".", "circle", ".", "radius", ")" ]
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas_rhino/conversions/_shapes.py#L105-L116
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/tools/dev_appserver_login.py
python
CreateCookieData
(email, admin)
return urllib.quote_plus("{0}:{1}:{2}:{3}".format(email, nickname, app_list, hashed))
Creates cookie payload data. Args: email, admin: Parameters to incorporate into the cookie. Returns: String containing the cookie payload.
Creates cookie payload data.
[ "Creates", "cookie", "payload", "data", "." ]
def CreateCookieData(email, admin): """ Creates cookie payload data. Args: email, admin: Parameters to incorporate into the cookie. Returns: String containing the cookie payload. """ nickname = email.split("@")[0] if admin: app_list = os.environ['APPLICATION_ID'] else: app_list = '' secret = os.environ['COOKIE_SECRET'] hashed = sha.new(email+nickname+app_list+secret).hexdigest() return urllib.quote_plus("{0}:{1}:{2}:{3}".format(email, nickname, app_list, hashed))
[ "def", "CreateCookieData", "(", "email", ",", "admin", ")", ":", "nickname", "=", "email", ".", "split", "(", "\"@\"", ")", "[", "0", "]", "if", "admin", ":", "app_list", "=", "os", ".", "environ", "[", "'APPLICATION_ID'", "]", "else", ":", "app_list",...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/tools/dev_appserver_login.py#L127-L146
mediacloud/backend
d36b489e4fbe6e44950916a04d9543a1d6cd5df0
apps/common/src/python/mediawords/dbi/stories/ap.py
python
_get_dup_sentences_32
(db: DatabaseHandler, story_text: str)
Return the number of sentences in the story that are least 32 characters long and are a duplicate of a sentence in the associated press media source.
Return the number of sentences in the story that are least 32 characters long and are a duplicate of a sentence in the associated press media source.
[ "Return", "the", "number", "of", "sentences", "in", "the", "story", "that", "are", "least", "32", "characters", "long", "and", "are", "a", "duplicate", "of", "a", "sentence", "in", "the", "associated", "press", "media", "source", "." ]
def _get_dup_sentences_32(db: DatabaseHandler, story_text: str) -> int: """Return the number of sentences in the story that are least 32 characters long and are a duplicate of a sentence in the associated press media source.""" story_text = decode_object_from_bytes_if_needed(story_text) sentence_lengths = _get_ap_dup_sentence_lengths(db=db, story_text=story_text) num_sentences = 0 for sentence_length in sentence_lengths: if sentence_length >= 32: num_sentences += 1 if not num_sentences: return 0 elif num_sentences > 10: return 2 else: return 1
[ "def", "_get_dup_sentences_32", "(", "db", ":", "DatabaseHandler", ",", "story_text", ":", "str", ")", "->", "int", ":", "story_text", "=", "decode_object_from_bytes_if_needed", "(", "story_text", ")", "sentence_lengths", "=", "_get_ap_dup_sentence_lengths", "(", "db"...
https://github.com/mediacloud/backend/blob/d36b489e4fbe6e44950916a04d9543a1d6cd5df0/apps/common/src/python/mediawords/dbi/stories/ap.py#L175-L192
stopstalk/stopstalk-deployment
10c3ab44c4ece33ae515f6888c15033db2004bb1
aws_lambda/spoj_aws_lambda_function/lambda_code/requests/utils.py
python
parse_header_links
(value)
return links
Return a dict of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
Return a dict of parsed link headers proxies.
[ "Return", "a", "dict", "of", "parsed", "link", "headers", "proxies", "." ]
def parse_header_links(value): """Return a dict of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" """ links = [] replace_chars = ' \'"' for val in re.split(', *<', value): try: url, params = val.split(';', 1) except ValueError: url, params = val, '' link = {'url': url.strip('<> \'"')} for param in params.split(';'): try: key, value = param.split('=') except ValueError: break link[key.strip(replace_chars)] = value.strip(replace_chars) links.append(link) return links
[ "def", "parse_header_links", "(", "value", ")", ":", "links", "=", "[", "]", "replace_chars", "=", "' \\'\"'", "for", "val", "in", "re", ".", "split", "(", "', *<'", ",", "value", ")", ":", "try", ":", "url", ",", "params", "=", "val", ".", "split", ...
https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/requests/utils.py#L605-L634
open-cogsci/OpenSesame
c4a3641b097a80a76937edbd8c365f036bcc9705
libopensesame/var_store.py
python
var_store.set
(self, var, val)
desc: Sets and experimental variable. arguments: var: desc: The variable to assign. type: [str, unicode] val: desc: The value to assign. type: any example: | var.set(u'my_variable', u'my_value') # Equivalent to var.my_variable = u'my_value'
desc: Sets and experimental variable.
[ "desc", ":", "Sets", "and", "experimental", "variable", "." ]
def set(self, var, val): """ desc: Sets and experimental variable. arguments: var: desc: The variable to assign. type: [str, unicode] val: desc: The value to assign. type: any example: | var.set(u'my_variable', u'my_value') # Equivalent to var.my_variable = u'my_value' """ self._check_var_name(var) self.__setattr__(var, val)
[ "def", "set", "(", "self", ",", "var", ",", "val", ")", ":", "self", ".", "_check_var_name", "(", "var", ")", "self", ".", "__setattr__", "(", "var", ",", "val", ")" ]
https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/libopensesame/var_store.py#L314-L335
openstack/swift
b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100
swift/common/utils.py
python
find_shard_range
(item, ranges)
return None
Find a ShardRange in given list of ``shard_ranges`` whose namespace contains ``item``. :param item: The item for a which a ShardRange is to be found. :param ranges: a sorted list of ShardRanges. :return: the ShardRange whose namespace contains ``item``, or None if no suitable range is found.
Find a ShardRange in given list of ``shard_ranges`` whose namespace contains ``item``.
[ "Find", "a", "ShardRange", "in", "given", "list", "of", "shard_ranges", "whose", "namespace", "contains", "item", "." ]
def find_shard_range(item, ranges): """ Find a ShardRange in given list of ``shard_ranges`` whose namespace contains ``item``. :param item: The item for a which a ShardRange is to be found. :param ranges: a sorted list of ShardRanges. :return: the ShardRange whose namespace contains ``item``, or None if no suitable range is found. """ index = bisect.bisect_left(ranges, item) if index != len(ranges) and item in ranges[index]: return ranges[index] return None
[ "def", "find_shard_range", "(", "item", ",", "ranges", ")", ":", "index", "=", "bisect", ".", "bisect_left", "(", "ranges", ",", "item", ")", "if", "index", "!=", "len", "(", "ranges", ")", "and", "item", "in", "ranges", "[", "index", "]", ":", "retu...
https://github.com/openstack/swift/blob/b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100/swift/common/utils.py#L5800-L5813
dragonfly/dragonfly
a579b5eadf452e23b07d4caf27b402703b0012b7
dragonfly/opt/blackbox_optimiser.py
python
OptInitialiser.initialise
(self)
return self.optimise(0)
Initialise.
Initialise.
[ "Initialise", "." ]
def initialise(self): """ Initialise. """ return self.optimise(0)
[ "def", "initialise", "(", "self", ")", ":", "return", "self", ".", "optimise", "(", "0", ")" ]
https://github.com/dragonfly/dragonfly/blob/a579b5eadf452e23b07d4caf27b402703b0012b7/dragonfly/opt/blackbox_optimiser.py#L403-L405
skorokithakis/django-annoying
f3ef8063b1815e8bfd7b6ccea3adf89d9982f096
annoying/decorators.py
python
autostrip
(cls)
return cls
strip text fields before validation example: @autostrip class PersonForm(forms.Form): name = forms.CharField(min_length=2, max_length=10) email = forms.EmailField() Author: nail.xx
strip text fields before validation
[ "strip", "text", "fields", "before", "validation" ]
def autostrip(cls): """ strip text fields before validation example: @autostrip class PersonForm(forms.Form): name = forms.CharField(min_length=2, max_length=10) email = forms.EmailField() Author: nail.xx """ warnings.warn( "django-annoying autostrip is deprecated and will be removed in a " "future version. Django now has native support for stripping form " "fields. " "https://docs.djangoproject.com/en/stable/ref/forms/fields/#django.forms.CharField.strip", DeprecationWarning, stacklevel=2, ) fields = [(key, value) for key, value in cls.base_fields.items() if isinstance(value, forms.CharField)] for field_name, field_object in fields: def get_clean_func(original_clean): return lambda value: original_clean(value and value.strip()) clean_func = get_clean_func(getattr(field_object, 'clean')) setattr(field_object, 'clean', clean_func) return cls
[ "def", "autostrip", "(", "cls", ")", ":", "warnings", ".", "warn", "(", "\"django-annoying autostrip is deprecated and will be removed in a \"", "\"future version. Django now has native support for stripping form \"", "\"fields. \"", "\"https://docs.djangoproject.com/en/stable/ref/forms/fi...
https://github.com/skorokithakis/django-annoying/blob/f3ef8063b1815e8bfd7b6ccea3adf89d9982f096/annoying/decorators.py#L197-L223
haiwen/seafile-docker
2d2461d4c8cab3458ec9832611c419d47506c300
scripts_8.0/setup-seafile-mysql.py
python
AbstractDBConfigurator.ask_use_existing_db
()
return Utils.ask_question(question, key='1 or 2', note=note, validate=validate)
[]
def ask_use_existing_db(): def validate(choice): if choice not in ['1', '2']: raise InvalidAnswer('Please choose 1 or 2') return choice == '2' question = '''\ ------------------------------------------------------- Please choose a way to initialize seafile databases: ------------------------------------------------------- ''' note = '''\ [1] Create new ccnet/seafile/seahub databases [2] Use existing ccnet/seafile/seahub databases ''' return Utils.ask_question(question, key='1 or 2', note=note, validate=validate)
[ "def", "ask_use_existing_db", "(", ")", ":", "def", "validate", "(", "choice", ")", ":", "if", "choice", "not", "in", "[", "'1'", ",", "'2'", "]", ":", "raise", "InvalidAnswer", "(", "'Please choose 1 or 2'", ")", "return", "choice", "==", "'2'", "question...
https://github.com/haiwen/seafile-docker/blob/2d2461d4c8cab3458ec9832611c419d47506c300/scripts_8.0/setup-seafile-mysql.py#L402-L422
giswqs/geemap
ba8de85557a8a1bc9c8d19e75bac69416afe7fea
geemap/common.py
python
planet_quarterly_tiles
( api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet" )
return tiles
Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer.
Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
[ "Generates", "Planet", "quarterly", "imagery", "TileLayer", "based", "on", "an", "API", "key", ".", "To", "get", "a", "Planet", "API", "key", "see", "https", ":", "//", "developers", ".", "planet", ".", "com", "/", "quickstart", "/", "apis", "/" ]
def planet_quarterly_tiles( api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet" ): """Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. """ import folium import ipyleaflet if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") tiles = {} links = planet_quarterly(api_key, token_name) for url in links: index = url.find("20") name = "Planet_" + url[index: index + 6] if tile_format == "ipyleaflet": tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name) else: tile = folium.TileLayer( tiles=url, attr="Planet", name=name, overlay=True, control=True, ) tiles[name] = tile return tiles
[ "def", "planet_quarterly_tiles", "(", "api_key", "=", "None", ",", "token_name", "=", "\"PLANET_API_KEY\"", ",", "tile_format", "=", "\"ipyleaflet\"", ")", ":", "import", "folium", "import", "ipyleaflet", "if", "tile_format", "not", "in", "[", "\"ipyleaflet\"", ",...
https://github.com/giswqs/geemap/blob/ba8de85557a8a1bc9c8d19e75bac69416afe7fea/geemap/common.py#L7835-L7877
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/db/models/sql/query.py
python
Query.deferred_to_columns_cb
(self, target, model, fields)
Callback used by deferred_to_columns(). The "target" parameter should be a set instance.
Callback used by deferred_to_columns(). The "target" parameter should be a set instance.
[ "Callback", "used", "by", "deferred_to_columns", "()", ".", "The", "target", "parameter", "should", "be", "a", "set", "instance", "." ]
def deferred_to_columns_cb(self, target, model, fields): """ Callback used by deferred_to_columns(). The "target" parameter should be a set instance. """ table = model._meta.db_table if table not in target: target[table] = set() for field in fields: target[table].add(field.column)
[ "def", "deferred_to_columns_cb", "(", "self", ",", "target", ",", "model", ",", "fields", ")", ":", "table", "=", "model", ".", "_meta", ".", "db_table", "if", "table", "not", "in", "target", ":", "target", "[", "table", "]", "=", "set", "(", ")", "f...
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/db/models/sql/query.py#L644-L653
metachris/pdfx
9e6864c5f9bcc8801e12c63a64d6efdfd1960494
pdfx/threadpool.py
python
ThreadPool.wait_completion
(self)
Wait for completion of all the tasks in the queue
Wait for completion of all the tasks in the queue
[ "Wait", "for", "completion", "of", "all", "the", "tasks", "in", "the", "queue" ]
def wait_completion(self): """ Wait for completion of all the tasks in the queue """ self.tasks.join()
[ "def", "wait_completion", "(", "self", ")", ":", "self", ".", "tasks", ".", "join", "(", ")" ]
https://github.com/metachris/pdfx/blob/9e6864c5f9bcc8801e12c63a64d6efdfd1960494/pdfx/threadpool.py#L55-L57
klen/peewee_migrate
f4ed1f40afd9ed51638ef7d78e0e9882860891be
peewee_migrate/migrator.py
python
Migrator.drop_not_null
(self, model: pw.Model, *names: str)
return model
Drop not null.
Drop not null.
[ "Drop", "not", "null", "." ]
def drop_not_null(self, model: pw.Model, *names: str) -> pw.Model: """Drop not null.""" for name in names: field = model._meta.fields[name] field.null = True self.ops.append(self.migrator.drop_not_null(model._meta.table_name, field.column_name)) return model
[ "def", "drop_not_null", "(", "self", ",", "model", ":", "pw", ".", "Model", ",", "*", "names", ":", "str", ")", "->", "pw", ".", "Model", ":", "for", "name", "in", "names", ":", "field", "=", "model", ".", "_meta", ".", "fields", "[", "name", "]"...
https://github.com/klen/peewee_migrate/blob/f4ed1f40afd9ed51638ef7d78e0e9882860891be/peewee_migrate/migrator.py#L340-L346
sunpy/sunpy
528579df0a4c938c133bd08971ba75c131b189a7
sunpy/database/database.py
python
Database.redo
(self, n=1)
redo the last n commands. See Also -------- :meth:`sunpy.database.commands.CommandManager.redo`
redo the last n commands.
[ "redo", "the", "last", "n", "commands", "." ]
def redo(self, n=1): """redo the last n commands. See Also -------- :meth:`sunpy.database.commands.CommandManager.redo` """ self._command_manager.redo(n)
[ "def", "redo", "(", "self", ",", "n", "=", "1", ")", ":", "self", ".", "_command_manager", ".", "redo", "(", "n", ")" ]
https://github.com/sunpy/sunpy/blob/528579df0a4c938c133bd08971ba75c131b189a7/sunpy/database/database.py#L1068-L1076
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/python-openid-2.2.5/openid/server/server.py
python
DiffieHellmanSHA1ServerSession.fromMessage
(cls, message)
return cls(dh, consumer_pubkey)
@param message: The associate request message @type message: openid.message.Message @returntype: L{DiffieHellmanSHA1ServerSession} @raises ProtocolError: When parameters required to establish the session are missing.
@param message: The associate request message @type message: openid.message.Message
[ "@param", "message", ":", "The", "associate", "request", "message", "@type", "message", ":", "openid", ".", "message", ".", "Message" ]
def fromMessage(cls, message): """ @param message: The associate request message @type message: openid.message.Message @returntype: L{DiffieHellmanSHA1ServerSession} @raises ProtocolError: When parameters required to establish the session are missing. """ dh_modulus = message.getArg(OPENID_NS, 'dh_modulus') dh_gen = message.getArg(OPENID_NS, 'dh_gen') if (dh_modulus is None and dh_gen is not None or dh_gen is None and dh_modulus is not None): if dh_modulus is None: missing = 'modulus' else: missing = 'generator' raise ProtocolError(message, 'If non-default modulus or generator is ' 'supplied, both must be supplied. Missing %s' % (missing,)) if dh_modulus or dh_gen: dh_modulus = cryptutil.base64ToLong(dh_modulus) dh_gen = cryptutil.base64ToLong(dh_gen) dh = DiffieHellman(dh_modulus, dh_gen) else: dh = DiffieHellman.fromDefaults() consumer_pubkey = message.getArg(OPENID_NS, 'dh_consumer_public') if consumer_pubkey is None: raise ProtocolError(message, "Public key for DH-SHA1 session " "not found in message %s" % (message,)) consumer_pubkey = cryptutil.base64ToLong(consumer_pubkey) return cls(dh, consumer_pubkey)
[ "def", "fromMessage", "(", "cls", ",", "message", ")", ":", "dh_modulus", "=", "message", ".", "getArg", "(", "OPENID_NS", ",", "'dh_modulus'", ")", "dh_gen", "=", "message", ".", "getArg", "(", "OPENID_NS", ",", "'dh_gen'", ")", "if", "(", "dh_modulus", ...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/python-openid-2.2.5/openid/server/server.py#L318-L357
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/_pyio.py
python
IOBase.fileno
(self)
Returns underlying file descriptor if one exists. An IOError is raised if the IO object does not use a file descriptor.
Returns underlying file descriptor if one exists.
[ "Returns", "underlying", "file", "descriptor", "if", "one", "exists", "." ]
def fileno(self): """Returns underlying file descriptor if one exists. An IOError is raised if the IO object does not use a file descriptor. """ self._unsupported("fileno")
[ "def", "fileno", "(", "self", ")", ":", "self", ".", "_unsupported", "(", "\"fileno\"", ")" ]
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/_pyio.py#L445-L450
feincms/feincms
be35576fa86083a969ae56aaf848173d1a5a3c5d
feincms/templatetags/feincms_admin_tags.py
python
post_process_fieldsets
(context, fieldset)
return ""
Removes a few fields from FeinCMS admin inlines, those being ``id``, ``DELETE`` and ``ORDER`` currently. Additionally, it ensures that dynamically added fields (i.e. ``ApplicationContent``'s ``admin_fields`` option) are shown.
Removes a few fields from FeinCMS admin inlines, those being ``id``, ``DELETE`` and ``ORDER`` currently.
[ "Removes", "a", "few", "fields", "from", "FeinCMS", "admin", "inlines", "those", "being", "id", "DELETE", "and", "ORDER", "currently", "." ]
def post_process_fieldsets(context, fieldset): """ Removes a few fields from FeinCMS admin inlines, those being ``id``, ``DELETE`` and ``ORDER`` currently. Additionally, it ensures that dynamically added fields (i.e. ``ApplicationContent``'s ``admin_fields`` option) are shown. """ # abort if fieldset is customized if fieldset.model_admin.fieldsets: return fieldset fields_to_include = set(fieldset.form.fields.keys()) for f in ("id", "DELETE", "ORDER"): fields_to_include.discard(f) def _filter_recursive(fields): ret = [] for f in fields: if isinstance(f, (list, tuple)): # Several fields on one line sub = _filter_recursive(f) # Only add if there's at least one field left if sub: ret.append(sub) elif f in fields_to_include: ret.append(f) fields_to_include.discard(f) return ret new_fields = _filter_recursive(fieldset.fields) # Add all other fields (ApplicationContent's admin_fields) to # the end of the fieldset for f in fields_to_include: new_fields.append(f) if context.get("request"): new_fields.extend( list( fieldset.model_admin.get_readonly_fields( context.get("request"), context.get("original") ) ) ) fieldset.fields = new_fields return ""
[ "def", "post_process_fieldsets", "(", "context", ",", "fieldset", ")", ":", "# abort if fieldset is customized", "if", "fieldset", ".", "model_admin", ".", "fieldsets", ":", "return", "fieldset", "fields_to_include", "=", "set", "(", "fieldset", ".", "form", ".", ...
https://github.com/feincms/feincms/blob/be35576fa86083a969ae56aaf848173d1a5a3c5d/feincms/templatetags/feincms_admin_tags.py#L11-L57
sethmlarson/virtualbox-python
984a6e2cb0e8996f4df40f4444c1528849f1c70d
virtualbox/library.py
python
IStorageController.port_count
(self)
return ret
Get or set int value for 'portCount' The number of currently usable ports on the controller. The minimum and maximum number of ports for one controller are stored in :py:func:`IStorageController.min_port_count` and :py:func:`IStorageController.max_port_count` .
Get or set int value for 'portCount' The number of currently usable ports on the controller. The minimum and maximum number of ports for one controller are stored in :py:func:`IStorageController.min_port_count` and :py:func:`IStorageController.max_port_count` .
[ "Get", "or", "set", "int", "value", "for", "portCount", "The", "number", "of", "currently", "usable", "ports", "on", "the", "controller", ".", "The", "minimum", "and", "maximum", "number", "of", "ports", "for", "one", "controller", "are", "stored", "in", "...
def port_count(self): """Get or set int value for 'portCount' The number of currently usable ports on the controller. The minimum and maximum number of ports for one controller are stored in :py:func:`IStorageController.min_port_count` and :py:func:`IStorageController.max_port_count` . """ ret = self._get_attr("portCount") return ret
[ "def", "port_count", "(", "self", ")", ":", "ret", "=", "self", ".", "_get_attr", "(", "\"portCount\"", ")", "return", "ret" ]
https://github.com/sethmlarson/virtualbox-python/blob/984a6e2cb0e8996f4df40f4444c1528849f1c70d/virtualbox/library.py#L32774-L32782
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
pyrevitlib/pyrevit/coreutils/__init__.py
python
is_box_visible_on_screens
(left, top, width, height)
return False
Check if given box is visible on any screen.
Check if given box is visible on any screen.
[ "Check", "if", "given", "box", "is", "visible", "on", "any", "screen", "." ]
def is_box_visible_on_screens(left, top, width, height): """Check if given box is visible on any screen.""" bounds = \ framework.Drawing.Rectangle( framework.Convert.ToInt32(0 if math.isnan(left) else left), framework.Convert.ToInt32(0 if math.isnan(top) else top), framework.Convert.ToInt32(0 if math.isnan(width) else width), framework.Convert.ToInt32(0 if math.isnan(height) else height) ) for scr in framework.Forms.Screen.AllScreens: if bounds.IntersectsWith(scr.Bounds): return True return False
[ "def", "is_box_visible_on_screens", "(", "left", ",", "top", ",", "width", ",", "height", ")", ":", "bounds", "=", "framework", ".", "Drawing", ".", "Rectangle", "(", "framework", ".", "Convert", ".", "ToInt32", "(", "0", "if", "math", ".", "isnan", "(",...
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/pyrevitlib/pyrevit/coreutils/__init__.py#L1212-L1224
google-research/language
61fa7260ac7d690d11ef72ca863e45a37c0bdc80
language/tek_representations/run_mrqa.py
python
parse_prefix
()
Parse the string signifying the preprocessing.
Parse the string signifying the preprocessing.
[ "Parse", "the", "string", "signifying", "the", "preprocessing", "." ]
def parse_prefix(): """Parse the string signifying the preprocessing.""" if FLAGS.prefix is not None: parts = FLAGS.prefix.split("-") for part in parts: fname, value = part.split(".") if fname == "type": FLAGS.background_type = value if value != "None" else None elif fname == "msl": FLAGS.max_seq_length = int(value) elif fname == "mbg": FLAGS.max_background_tokens = int(value) else: raise NotImplementedError()
[ "def", "parse_prefix", "(", ")", ":", "if", "FLAGS", ".", "prefix", "is", "not", "None", ":", "parts", "=", "FLAGS", ".", "prefix", ".", "split", "(", "\"-\"", ")", "for", "part", "in", "parts", ":", "fname", ",", "value", "=", "part", ".", "split"...
https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/tek_representations/run_mrqa.py#L231-L244
google-research/language
61fa7260ac7d690d11ef72ca863e45a37c0bdc80
language/emql/cm_sketch.py
python
CountMinContext.intersection
(self, sk1, sk2)
return sk_intersection
Intersect two sketches. Args: sk1: first sketch sk2: second sketch Returns: a countmin sketch for intersection
Intersect two sketches.
[ "Intersect", "two", "sketches", "." ]
def intersection(self, sk1, sk2): """Intersect two sketches. Args: sk1: first sketch sk2: second sketch Returns: a countmin sketch for intersection """ assert sk1.shape == sk2.shape assert self.depth, self.width == sk1.shape sk_intersection = sk1 * sk2 return sk_intersection
[ "def", "intersection", "(", "self", ",", "sk1", ",", "sk2", ")", ":", "assert", "sk1", ".", "shape", "==", "sk2", ".", "shape", "assert", "self", ".", "depth", ",", "self", ".", "width", "==", "sk1", ".", "shape", "sk_intersection", "=", "sk1", "*", ...
https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/emql/cm_sketch.py#L159-L172
renatahodovan/fuzzinator
017264c683b4ecf23f56f30a1b9c0f891b4251a1
fuzzinator/executor.py
python
process_args
(args)
return None
[]
def process_args(args): config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation(), strict=False, allow_no_value=True) config.read_dict({ 'fuzzinator': { 'work_dir': os.path.join('~', '.fuzzinator', '{uid}'), 'cost_budget': str(os.cpu_count()), 'validate_after_update': 'False', 'db_uri': 'mongodb://localhost/fuzzinator', 'db_server_selection_timeout': '30000', } }) parsed_fn = config.read(args.config) if len(parsed_fn) != len(args.config): return 'Config file(s) do(es) not exist: {fn}'.format(fn=', '.join(fn for fn in args.config if fn not in parsed_fn)) for define in args.defines: parts = re.fullmatch('([^:=]*):([^:=]*)=(.*)', define) if not parts: return 'Config option definition not in SECT:OPT=VAL format: {d}'.format(d=define) section, option, value = parts.group(1, 2, 3) if not config.has_section(section): config.add_section(section) config.set(section, option, value) for undef in args.undefs: parts = re.fullmatch('([^:=]*)(:([^:=]*))?', undef) if not parts: return 'Config section/option undefinition not in SECT[:OPT] format: {u}'.format(u=undef) section, option = parts.group(1, 3) if option is None: config.remove_section(section) elif config.has_section(section): config.remove_option(section, option) if args.show_config: config.write(sys.stdout) args.config = config inators.arg.process_log_level_argument(args, root_logger) inators.arg.process_sys_recursion_limit_argument(args) return None
[ "def", "process_args", "(", "args", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", "interpolation", "=", "configparser", ".", "ExtendedInterpolation", "(", ")", ",", "strict", "=", "False", ",", "allow_no_value", "=", "True", ")", "config",...
https://github.com/renatahodovan/fuzzinator/blob/017264c683b4ecf23f56f30a1b9c0f891b4251a1/fuzzinator/executor.py#L23-L71
liuslevis/weiquncrawler
c430f7933a53a57d6d0a336f4425d48c3eed8b91
bs4/element.py
python
Tag.__len__
(self)
return len(self.contents)
The length of a tag is the length of its list of contents.
The length of a tag is the length of its list of contents.
[ "The", "length", "of", "a", "tag", "is", "the", "length", "of", "its", "list", "of", "contents", "." ]
def __len__(self): "The length of a tag is the length of its list of contents." return len(self.contents)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "contents", ")" ]
https://github.com/liuslevis/weiquncrawler/blob/c430f7933a53a57d6d0a336f4425d48c3eed8b91/bs4/element.py#L885-L887
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_ceph_fs_volume_source.py
python
V1CephFSVolumeSource.__init__
(self, monitors=None, path=None, read_only=None, secret_file=None, secret_ref=None, user=None)
V1CephFSVolumeSource - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
V1CephFSVolumeSource - a model defined in Swagger
[ "V1CephFSVolumeSource", "-", "a", "model", "defined", "in", "Swagger" ]
def __init__(self, monitors=None, path=None, read_only=None, secret_file=None, secret_ref=None, user=None): """ V1CephFSVolumeSource - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'monitors': 'list[str]', 'path': 'str', 'read_only': 'bool', 'secret_file': 'str', 'secret_ref': 'V1LocalObjectReference', 'user': 'str' } self.attribute_map = { 'monitors': 'monitors', 'path': 'path', 'read_only': 'readOnly', 'secret_file': 'secretFile', 'secret_ref': 'secretRef', 'user': 'user' } self._monitors = monitors self._path = path self._read_only = read_only self._secret_file = secret_file self._secret_ref = secret_ref self._user = user
[ "def", "__init__", "(", "self", ",", "monitors", "=", "None", ",", "path", "=", "None", ",", "read_only", "=", "None", ",", "secret_file", "=", "None", ",", "secret_ref", "=", "None", ",", "user", "=", "None", ")", ":", "self", ".", "swagger_types", ...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_ceph_fs_volume_source.py#L24-L56
modoboa/modoboa
9065b7a5679fee149fc6f6f0e1760699c194cf89
modoboa/core/handlers.py
python
update_permissions
(sender, instance, **kwargs)
Permissions cleanup.
Permissions cleanup.
[ "Permissions", "cleanup", "." ]
def update_permissions(sender, instance, **kwargs): """Permissions cleanup.""" request = get_request() # request migth be None (management command context) if request: from_user = request.user if from_user == instance: raise exceptions.PermDeniedException( _("You can't delete your own account") ) if not from_user.can_access(instance): raise exceptions.PermDeniedException # We send an additional signal before permissions are removed core_signals.account_deleted.send( sender="update_permissions", user=instance) owner = permissions.get_object_owner(instance) if owner == instance: # The default admin is being removed... owner = from_user # Change ownership of existing objects for ooentry in instance.objectaccess_set.filter(is_owner=True): if ooentry.content_object is not None: permissions.grant_access_to_object( owner, ooentry.content_object, True) permissions.ungrant_access_to_object( ooentry.content_object, instance) # Remove existing permissions on this user permissions.ungrant_access_to_object(instance)
[ "def", "update_permissions", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "request", "=", "get_request", "(", ")", "# request migth be None (management command context)", "if", "request", ":", "from_user", "=", "request", ".", "user", "if", ...
https://github.com/modoboa/modoboa/blob/9065b7a5679fee149fc6f6f0e1760699c194cf89/modoboa/core/handlers.py#L87-L116
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/src/gui/toast/toast.py
python
opacity_to_byte
(val)
Map a number from 0-100 to 0-255, returning 255 if it's not a number.
Map a number from 0-100 to 0-255, returning 255 if it's not a number.
[ "Map", "a", "number", "from", "0", "-", "100", "to", "0", "-", "255", "returning", "255", "if", "it", "s", "not", "a", "number", "." ]
def opacity_to_byte(val): '''Map a number from 0-100 to 0-255, returning 255 if it's not a number.''' try: int(val) except ValueError: return 255 else: return int(min(100, max(0, val)) / 100.0 * 255)
[ "def", "opacity_to_byte", "(", "val", ")", ":", "try", ":", "int", "(", "val", ")", "except", "ValueError", ":", "return", "255", "else", ":", "return", "int", "(", "min", "(", "100", ",", "max", "(", "0", ",", "val", ")", ")", "/", "100.0", "*",...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/gui/toast/toast.py#L1495-L1503
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py
python
DeploymentConfig.update_replicas
(self, replicas)
update replicas value
update replicas value
[ "update", "replicas", "value" ]
def update_replicas(self, replicas): ''' update replicas value ''' self.put(DeploymentConfig.replicas_path, replicas)
[ "def", "update_replicas", "(", "self", ",", "replicas", ")", ":", "self", ".", "put", "(", "DeploymentConfig", ".", "replicas_path", ",", "replicas", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_scale.py#L1721-L1723
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/db/sqlalchemy/api.py
python
init_node_get_by_host
(context, host, session=None)
return init_node_ref
Get init node ref by host name.
Get init node ref by host name.
[ "Get", "init", "node", "ref", "by", "host", "name", "." ]
def init_node_get_by_host(context, host, session=None): """Get init node ref by host name.""" if not session: session = get_session() init_node_ref = model_query(context, models.InitNode, read_deleted="no", session=session).\ options(joinedload('zone')).\ filter_by(host=host).\ first() #if not init_node_ref: # LOG.warn('Can not find init_node_ref by %s' % host) return init_node_ref
[ "def", "init_node_get_by_host", "(", "context", ",", "host", ",", "session", "=", "None", ")", ":", "if", "not", "session", ":", "session", "=", "get_session", "(", ")", "init_node_ref", "=", "model_query", "(", "context", ",", "models", ".", "InitNode", "...
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/db/sqlalchemy/api.py#L2751-L2767
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/sim_type.py
python
SimTypeFixedSizeArray.store
(self, state, addr, values)
[]
def store(self, state, addr, values): for i, val in enumerate(values): self.elem_type.store(state, addr + i * (self.elem_type.size // state.arch.byte_width), val)
[ "def", "store", "(", "self", ",", "state", ",", "addr", ",", "values", ")", ":", "for", "i", ",", "val", "in", "enumerate", "(", "values", ")", ":", "self", ".", "elem_type", ".", "store", "(", "state", ",", "addr", "+", "i", "*", "(", "self", ...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/sim_type.py#L663-L665
charlesq34/pointnet
539db60eb63335ae00fe0da0c8e38c791c764d2b
utils/pc_util.py
python
write_ply
(points, filename, text=True)
input: Nx3, write points to filename as PLY format.
input: Nx3, write points to filename as PLY format.
[ "input", ":", "Nx3", "write", "points", "to", "filename", "as", "PLY", "format", "." ]
def write_ply(points, filename, text=True): """ input: Nx3, write points to filename as PLY format. """ points = [(points[i,0], points[i,1], points[i,2]) for i in range(points.shape[0])] vertex = np.array(points, dtype=[('x', 'f4'), ('y', 'f4'),('z', 'f4')]) el = PlyElement.describe(vertex, 'vertex', comments=['vertices']) PlyData([el], text=text).write(filename)
[ "def", "write_ply", "(", "points", ",", "filename", ",", "text", "=", "True", ")", ":", "points", "=", "[", "(", "points", "[", "i", ",", "0", "]", ",", "points", "[", "i", ",", "1", "]", ",", "points", "[", "i", ",", "2", "]", ")", "for", ...
https://github.com/charlesq34/pointnet/blob/539db60eb63335ae00fe0da0c8e38c791c764d2b/utils/pc_util.py#L85-L90
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/sql_db/management/commands/configure_pl_proxy_cluster.py
python
get_user_mapping_sql
(cluster_config)
return USER_MAPPING_TEMPLATE.format(**proxy_db_config)
[]
def get_user_mapping_sql(cluster_config): proxy_db = cluster_config.proxy_db proxy_db_config = settings.DATABASES[proxy_db].copy() proxy_db_config['server_name'] = cluster_config.cluster_name return USER_MAPPING_TEMPLATE.format(**proxy_db_config)
[ "def", "get_user_mapping_sql", "(", "cluster_config", ")", ":", "proxy_db", "=", "cluster_config", ".", "proxy_db", "proxy_db_config", "=", "settings", ".", "DATABASES", "[", "proxy_db", "]", ".", "copy", "(", ")", "proxy_db_config", "[", "'server_name'", "]", "...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/sql_db/management/commands/configure_pl_proxy_cluster.py#L183-L187
gcollazo/BrowserRefresh-Sublime
daee0eda6480c07f8636ed24e5c555d24e088886
win/pywinauto/controls/common_controls.py
python
_toolbar_button.IsPressable
(self)
return self.Style() & win32defines.TBSTYLE_BUTTON
Return if the button can be pressed
Return if the button can be pressed
[ "Return", "if", "the", "button", "can", "be", "pressed" ]
def IsPressable(self): "Return if the button can be pressed" return self.Style() & win32defines.TBSTYLE_BUTTON
[ "def", "IsPressable", "(", "self", ")", ":", "return", "self", ".", "Style", "(", ")", "&", "win32defines", ".", "TBSTYLE_BUTTON" ]
https://github.com/gcollazo/BrowserRefresh-Sublime/blob/daee0eda6480c07f8636ed24e5c555d24e088886/win/pywinauto/controls/common_controls.py#L1756-L1758
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/carddav/datastore/file.py
python
AddressBookObject._text
(self)
return text
[]
def _text(self): if self._objectText is not None: return self._objectText try: fh = self._path.open() except IOError, e: if e[0] == ENOENT: raise NoSuchObjectResourceError(self) else: raise try: text = fh.read() finally: fh.close() if not ( text.startswith("BEGIN:VCARD\r\n") or text.endswith("\r\nEND:VCARD\r\n") ): raise InternalDataStoreError( "File corruption detected (improper start) in file: %s" % (self._path.path,) ) self._objectText = text return text
[ "def", "_text", "(", "self", ")", ":", "if", "self", ".", "_objectText", "is", "not", "None", ":", "return", "self", ".", "_objectText", "try", ":", "fh", "=", "self", ".", "_path", ".", "open", "(", ")", "except", "IOError", ",", "e", ":", "if", ...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/carddav/datastore/file.py#L240-L267
cloudkick/libcloud
9c8605e1518c6b5e2511f0780e1946089a7256dd
libcloud/compute/drivers/gogrid.py
python
GoGridNodeDriver.ex_edit_image
(self, **kwargs)
return self._to_image(object['list'][0])
Edit metadata of a server image. @keyword image: image to be edited @type image: L{NodeImage} @keyword public: should be the image public? @type public: C{bool} @keyword ex_description: description of the image (optional) @type ex_description: C{string} @keyword name: name of the image @type name C{string}
Edit metadata of a server image.
[ "Edit", "metadata", "of", "a", "server", "image", "." ]
def ex_edit_image(self, **kwargs): """Edit metadata of a server image. @keyword image: image to be edited @type image: L{NodeImage} @keyword public: should be the image public? @type public: C{bool} @keyword ex_description: description of the image (optional) @type ex_description: C{string} @keyword name: name of the image @type name C{string} """ image = kwargs['image'] public = kwargs['public'] params = {'id': image.id, 'isPublic': str(public).lower()} if 'ex_description' in kwargs: params['description'] = kwargs['ex_description'] if 'name' in kwargs: params['friendlyName'] = kwargs['name'] object = self.connection.request('/api/grid/image/edit', params=params).object return self._to_image(object['list'][0])
[ "def", "ex_edit_image", "(", "self", ",", "*", "*", "kwargs", ")", ":", "image", "=", "kwargs", "[", "'image'", "]", "public", "=", "kwargs", "[", "'public'", "]", "params", "=", "{", "'id'", ":", "image", ".", "id", ",", "'isPublic'", ":", "str", ...
https://github.com/cloudkick/libcloud/blob/9c8605e1518c6b5e2511f0780e1946089a7256dd/libcloud/compute/drivers/gogrid.py#L406-L435
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py
python
Standard_Suite_Events.select
(self, _object=None, _attributes={}, **_arguments)
select: select the specified object Required argument: the object to select Keyword argument _attributes: AppleEvent attribute dictionary
select: select the specified object Required argument: the object to select Keyword argument _attributes: AppleEvent attribute dictionary
[ "select", ":", "select", "the", "specified", "object", "Required", "argument", ":", "the", "object", "to", "select", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def select(self, _object=None, _attributes={}, **_arguments): """select: select the specified object Required argument: the object to select Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'misc' _subcode = 'slct' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "select", "(", "self", ",", "_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'misc'", "_subcode", "=", "'slct'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py#L129-L147
interpretml/DiCE
e6a1dc3893799a364da993d4a368b7ccfabe4447
dice_ml/data_interfaces/private_data_interface.py
python
PrivateData.get_inverse_ohe_min_max_normalized_data
(self, transformed_data)
return raw_data
Transforms one-hot-encoded and min-max normalized data into raw user-fed data format. transformed_data should be a dataframe or an array
Transforms one-hot-encoded and min-max normalized data into raw user-fed data format. transformed_data should be a dataframe or an array
[ "Transforms", "one", "-", "hot", "-", "encoded", "and", "min", "-", "max", "normalized", "data", "into", "raw", "user", "-", "fed", "data", "format", ".", "transformed_data", "should", "be", "a", "dataframe", "or", "an", "array" ]
def get_inverse_ohe_min_max_normalized_data(self, transformed_data): """Transforms one-hot-encoded and min-max normalized data into raw user-fed data format. transformed_data should be a dataframe or an array""" raw_data = self.get_decoded_data(transformed_data, encoding='one-hot') raw_data = self.de_normalize_data(raw_data) precisions = self.get_decimal_precisions() for ix, feature in enumerate(self.continuous_feature_names): raw_data[feature] = raw_data[feature].astype(float).round(precisions[ix]) raw_data = raw_data[self.feature_names] # returns a pandas dataframe return raw_data
[ "def", "get_inverse_ohe_min_max_normalized_data", "(", "self", ",", "transformed_data", ")", ":", "raw_data", "=", "self", ".", "get_decoded_data", "(", "transformed_data", ",", "encoding", "=", "'one-hot'", ")", "raw_data", "=", "self", ".", "de_normalize_data", "(...
https://github.com/interpretml/DiCE/blob/e6a1dc3893799a364da993d4a368b7ccfabe4447/dice_ml/data_interfaces/private_data_interface.py#L356-L366
nettitude/scrounger
dd393666aa1ba1117d1c472cfdef4d0b18216904
scrounger/utils/ios.py
python
_get_attribute_properties
(attribute_string)
return "({})".format(fully_named_attributes)
Returns the properties of the attribute from a dumped sting :param str attribute_string: the string from a class dump containing an attribute :return: a string containing the parsed properties of an attribute
Returns the properties of the attribute from a dumped sting
[ "Returns", "the", "properties", "of", "the", "attribute", "from", "a", "dumped", "sting" ]
def _get_attribute_properties(attribute_string): """ Returns the properties of the attribute from a dumped sting :param str attribute_string: the string from a class dump containing an attribute :return: a string containing the parsed properties of an attribute """ known_attributes = { "N": "nonatomic", "R": "readonly", "C": "copy", "&": "retain" } # split the whole string by spaces to get the last argument which contains # the type and the properties of the attribute - [1:] gets only the # properties attributes = attribute_string.rsplit(" ", 1)[-1].split(",")[1:] fully_named_attributes = ", ".join([ known_attributes[attribute] for attribute in attributes if attribute in known_attributes]) # check if weak attribute if "W" in attributes: return "({}) __weak".format(fully_named_attributes) return "({})".format(fully_named_attributes)
[ "def", "_get_attribute_properties", "(", "attribute_string", ")", ":", "known_attributes", "=", "{", "\"N\"", ":", "\"nonatomic\"", ",", "\"R\"", ":", "\"readonly\"", ",", "\"C\"", ":", "\"copy\"", ",", "\"&\"", ":", "\"retain\"", "}", "# split the whole string by s...
https://github.com/nettitude/scrounger/blob/dd393666aa1ba1117d1c472cfdef4d0b18216904/scrounger/utils/ios.py#L727-L755
openstack/ironic
b392dc19bcd29cef5a69ec00d2f18a7a19a679e5
ironic/conductor/rpcapi.py
python
ConductorAPI.change_node_boot_mode
(self, context, node_id, new_state, topic=None)
return cctxt.call(context, 'change_node_boot_mode', node_id=node_id, new_state=new_state)
Change a node's boot mode. Synchronously, acquire lock and start the conductor background task to change boot mode of a node. :param context: request context. :param node_id: node id or uuid. :param new_state: one of ironic.common.boot_modes values ('bios' or 'uefi') :param topic: RPC topic. Defaults to self.topic. :raises: NoFreeConductorWorker when there is no free worker to start async task.
Change a node's boot mode.
[ "Change", "a", "node", "s", "boot", "mode", "." ]
def change_node_boot_mode(self, context, node_id, new_state, topic=None): """Change a node's boot mode. Synchronously, acquire lock and start the conductor background task to change boot mode of a node. :param context: request context. :param node_id: node id or uuid. :param new_state: one of ironic.common.boot_modes values ('bios' or 'uefi') :param topic: RPC topic. Defaults to self.topic. :raises: NoFreeConductorWorker when there is no free worker to start async task. """ cctxt = self._prepare_call(topic=topic, version='1.55') return cctxt.call(context, 'change_node_boot_mode', node_id=node_id, new_state=new_state)
[ "def", "change_node_boot_mode", "(", "self", ",", "context", ",", "node_id", ",", "new_state", ",", "topic", "=", "None", ")", ":", "cctxt", "=", "self", ".", "_prepare_call", "(", "topic", "=", "topic", ",", "version", "=", "'1.55'", ")", "return", "cct...
https://github.com/openstack/ironic/blob/b392dc19bcd29cef5a69ec00d2f18a7a19a679e5/ironic/conductor/rpcapi.py#L365-L383
SUSE/DeepSea
9c7fad93915ba1250c40d50c855011e9fe41ed21
srv/salt/_modules/dg.py
python
Output._guide
(osd_ids: list, can_have_osds: bool = False, error='')
return dict(message="No issues found.")
Return dict with meaningful message for a specific category
Return dict with meaningful message for a specific category
[ "Return", "dict", "with", "meaningful", "message", "for", "a", "specific", "category" ]
def _guide(osd_ids: list, can_have_osds: bool = False, error='') -> dict: """ Return dict with meaningful message for a specific category """ if error: return dict(message=error) if osd_ids and can_have_osds: return dict(osds=osd_ids) if osd_ids and not can_have_osds: return dict( conflict= f"Detected OSD(s) {' '.join(osd_ids)} in a non-admissible category." ) if can_have_osds: return dict( message= "No OSD detected (Will be created in the next deployment run)") # also detect if db/wal-device is _actually_ a wal/db device of a already deployed OSD return dict(message="No issues found.")
[ "def", "_guide", "(", "osd_ids", ":", "list", ",", "can_have_osds", ":", "bool", "=", "False", ",", "error", "=", "''", ")", "->", "dict", ":", "if", "error", ":", "return", "dict", "(", "message", "=", "error", ")", "if", "osd_ids", "and", "can_have...
https://github.com/SUSE/DeepSea/blob/9c7fad93915ba1250c40d50c855011e9fe41ed21/srv/salt/_modules/dg.py#L1207-L1226
jmcnamara/XlsxWriter
fd30f221bf4326ca7814cec0d3a87a89b9e3edd5
dev/performance/bench_excel_writers.py
python
time_openpyxl
()
Run OpenPyXL in default mode.
Run OpenPyXL in default mode.
[ "Run", "OpenPyXL", "in", "default", "mode", "." ]
def time_openpyxl(): """ Run OpenPyXL in default mode. """ start_time = perf_counter() workbook = openpyxl.workbook.Workbook() worksheet = workbook.active for row in range(row_max // 2): for col in range(col_max): worksheet.cell(row * 2 + 1, col + 1, "Row: %d Col: %d" % (row, col)) for col in range(col_max): worksheet.cell(row * 2 + 2, col + 1, row + col) workbook.save('openpyxl.xlsx') elapsed = perf_counter() - start_time print_elapsed_time('openpyxl', elapsed)
[ "def", "time_openpyxl", "(", ")", ":", "start_time", "=", "perf_counter", "(", ")", "workbook", "=", "openpyxl", ".", "workbook", ".", "Workbook", "(", ")", "worksheet", "=", "workbook", ".", "active", "for", "row", "in", "range", "(", "row_max", "//", "...
https://github.com/jmcnamara/XlsxWriter/blob/fd30f221bf4326ca7814cec0d3a87a89b9e3edd5/dev/performance/bench_excel_writers.py#L75-L91
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/plat-mac/videoreader.py
python
_Reader.GetVideoDuration
(self)
return self._gettrackduration_ms(self.videotrack)
[]
def GetVideoDuration(self): if not self.videotrack: return 0 return self._gettrackduration_ms(self.videotrack)
[ "def", "GetVideoDuration", "(", "self", ")", ":", "if", "not", "self", ".", "videotrack", ":", "return", "0", "return", "self", ".", "_gettrackduration_ms", "(", "self", ".", "videotrack", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/plat-mac/videoreader.py#L149-L152
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/nodetags.py
python
TagController.remove_tag
(self, p, tag)
removes 'tag' from the taglist of position p.
removes 'tag' from the taglist of position p.
[ "removes", "tag", "from", "the", "taglist", "of", "position", "p", "." ]
def remove_tag(self, p, tag): """ removes 'tag' from the taglist of position p. """ v = p.v tags = set(v.u.get(self.TAG_LIST_KEY, set([]))) # in case JSON storage (leo_cloud plugin) converted to list. if tag in tags: tags.remove(tag) if tags: v.u[self.TAG_LIST_KEY] = tags else: del v.u[self.TAG_LIST_KEY] # prevent a few corner cases, and conserve disk space self.c.setChanged() self.update_taglist(tag)
[ "def", "remove_tag", "(", "self", ",", "p", ",", "tag", ")", ":", "v", "=", "p", ".", "v", "tags", "=", "set", "(", "v", ".", "u", ".", "get", "(", "self", ".", "TAG_LIST_KEY", ",", "set", "(", "[", "]", ")", ")", ")", "# in case JSON storage (...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/nodetags.py#L232-L245