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
openid/python-openid
afa6adacbe1a41d8f614c8bce2264dfbe9e76489
openid/extensions/pape.py
python
Request.parseExtensionArgs
(self, args, is_openid1, strict=False)
Set the state of this request to be that expressed in these PAPE arguments @param args: The PAPE arguments without a namespace @param strict: Whether to raise an exception if the input is out of spec or otherwise malformed. If strict is false, malformed input will be ignored. @param is_openid1: Whether the input should be treated as part of an OpenID1 request @rtype: None @raises ValueError: When the max_auth_age is not parseable as an integer
Set the state of this request to be that expressed in these PAPE arguments
[ "Set", "the", "state", "of", "this", "request", "to", "be", "that", "expressed", "in", "these", "PAPE", "arguments" ]
def parseExtensionArgs(self, args, is_openid1, strict=False): """Set the state of this request to be that expressed in these PAPE arguments @param args: The PAPE arguments without a namespace @param strict: Whether to raise an exception if the input is out of spec or otherwise malformed. If strict is false, malformed input will be ignored. @param is_openid1: Whether the input should be treated as part of an OpenID1 request @rtype: None @raises ValueError: When the max_auth_age is not parseable as an integer """ # preferred_auth_policies is a space-separated list of policy URIs self.preferred_auth_policies = [] policies_str = args.get('preferred_auth_policies') if policies_str: for uri in policies_str.split(' '): if uri not in self.preferred_auth_policies: self.preferred_auth_policies.append(uri) # max_auth_age is base-10 integer number of seconds max_auth_age_str = args.get('max_auth_age') self.max_auth_age = None if max_auth_age_str: try: self.max_auth_age = int(max_auth_age_str) except ValueError: if strict: raise # Parse auth level information preferred_auth_level_types = args.get('preferred_auth_level_types') if preferred_auth_level_types: aliases = preferred_auth_level_types.strip().split() for alias in aliases: key = 'auth_level.ns.%s' % (alias,) try: uri = args[key] except KeyError: if is_openid1: uri = self._default_auth_level_aliases.get(alias) else: uri = None if uri is None: if strict: raise ValueError('preferred auth level %r is not ' 'defined in this message' % (alias,)) else: self.addAuthLevel(uri, alias)
[ "def", "parseExtensionArgs", "(", "self", ",", "args", ",", "is_openid1", ",", "strict", "=", "False", ")", ":", "# preferred_auth_policies is a space-separated list of policy URIs", "self", ".", "preferred_auth_policies", "=", "[", "]", "policies_str", "=", "args", "...
https://github.com/openid/python-openid/blob/afa6adacbe1a41d8f614c8bce2264dfbe9e76489/openid/extensions/pape.py#L194-L253
readthedocs/commonmark.py
d031003aa23cfce1787cfb29c1eb109b369ca5b7
commonmark/inlines.py
python
InlineParser.handleDelim
(self, cc, block)
return True
Handle a delimiter marker for emphasis or a quote.
Handle a delimiter marker for emphasis or a quote.
[ "Handle", "a", "delimiter", "marker", "for", "emphasis", "or", "a", "quote", "." ]
def handleDelim(self, cc, block): """Handle a delimiter marker for emphasis or a quote.""" res = self.scanDelims(cc) if not res: return False numdelims = res.get('numdelims') startpos = self.pos self.pos += numdelims if cc == "'": contents = '\u2019' elif cc == '"': contents = '\u201C' else: contents = self.subject[startpos:self.pos] node = text(contents) block.append_child(node) # Add entry to stack for this opener self.delimiters = { 'cc': cc, 'numdelims': numdelims, 'origdelims': numdelims, 'node': node, 'previous': self.delimiters, 'next': None, 'can_open': res.get('can_open'), 'can_close': res.get('can_close'), } if self.delimiters['previous'] is not None: self.delimiters['previous']['next'] = self.delimiters return True
[ "def", "handleDelim", "(", "self", ",", "cc", ",", "block", ")", ":", "res", "=", "self", ".", "scanDelims", "(", "cc", ")", "if", "not", "res", ":", "return", "False", "numdelims", "=", "res", ".", "get", "(", "'numdelims'", ")", "startpos", "=", ...
https://github.com/readthedocs/commonmark.py/blob/d031003aa23cfce1787cfb29c1eb109b369ca5b7/commonmark/inlines.py#L311-L342
statsmodels/statsmodels
debbe7ea6ba28fe5bdb78f09f8cac694bef98722
statsmodels/sandbox/predict_functional.py
python
_make_exog_from_formula
(result, focus_var, summaries, values, num_points)
return dexog, fexog, fvals
Create dataframes for exploring a fitted model as a function of one variable. This works for models fit with a formula. Returns ------- dexog : data frame A data frame in which the focus variable varies and the other variables are fixed at specified or computed values. fexog : data frame The data frame `dexog` processed through the model formula.
Create dataframes for exploring a fitted model as a function of one variable.
[ "Create", "dataframes", "for", "exploring", "a", "fitted", "model", "as", "a", "function", "of", "one", "variable", "." ]
def _make_exog_from_formula(result, focus_var, summaries, values, num_points): """ Create dataframes for exploring a fitted model as a function of one variable. This works for models fit with a formula. Returns ------- dexog : data frame A data frame in which the focus variable varies and the other variables are fixed at specified or computed values. fexog : data frame The data frame `dexog` processed through the model formula. """ model = result.model exog = model.data.frame if summaries is None: summaries = {} if values is None: values = {} if exog[focus_var].dtype is np.dtype('O'): raise ValueError('focus variable may not have object type') colnames = list(summaries.keys()) + list(values.keys()) + [focus_var] dtypes = [exog[x].dtype for x in colnames] # Check for variables whose values are not set either through # `values` or `summaries`. Since the model data frame can contain # extra variables not referenced in the formula RHS, this may not # be a problem, so just warn. There is no obvious way to extract # from a formula all the variable names that it references. varl = set(exog.columns.tolist()) - set([model.endog_names]) unmatched = varl - set(colnames) unmatched = list(unmatched) if len(unmatched) > 0: warnings.warn("%s in data frame but not in summaries or values." % ", ".join(["'%s'" % x for x in unmatched]), ValueWarning) # Initialize at zero so each column can be converted to any dtype. ix = range(num_points) fexog = pd.DataFrame(index=ix, columns=colnames) for d, x in zip(dtypes, colnames): fexog[x] = pd.Series(index=ix, dtype=d) # The values of the 'focus variable' are a sequence of percentiles pctls = np.linspace(0, 100, num_points).tolist() fvals = np.percentile(exog[focus_var], pctls) fvals = np.asarray(fvals) fexog.loc[:, focus_var] = fvals # The values of the other variables may be given by summary functions... for ky in summaries.keys(): fexog.loc[:, ky] = summaries[ky](exog.loc[:, ky]) # or they may be provided as given values. for ky in values.keys(): fexog.loc[:, ky] = values[ky] dexog = patsy.dmatrix(model.data.design_info, fexog, return_type='dataframe') return dexog, fexog, fvals
[ "def", "_make_exog_from_formula", "(", "result", ",", "focus_var", ",", "summaries", ",", "values", ",", "num_points", ")", ":", "model", "=", "result", ".", "model", "exog", "=", "model", ".", "data", ".", "frame", "if", "summaries", "is", "None", ":", ...
https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/sandbox/predict_functional.py#L131-L195
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/salt_proxy.py
python
configure_proxy
(name, proxyname="p8000", start=True)
return ret
Create the salt proxy file and start the proxy process if required Parameters: name: The name of this state proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started Example: .. code-block:: yaml salt-proxy-configure: salt_proxy.configure_proxy: - proxyname: p8000 - start: True
Create the salt proxy file and start the proxy process if required
[ "Create", "the", "salt", "proxy", "file", "and", "start", "the", "proxy", "process", "if", "required" ]
def configure_proxy(name, proxyname="p8000", start=True): """ Create the salt proxy file and start the proxy process if required Parameters: name: The name of this state proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started Example: .. code-block:: yaml salt-proxy-configure: salt_proxy.configure_proxy: - proxyname: p8000 - start: True """ ret = __salt__["salt_proxy.configure_proxy"](proxyname, start=start) ret.update({"name": name, "comment": "{} config messages".format(name)}) return ret
[ "def", "configure_proxy", "(", "name", ",", "proxyname", "=", "\"p8000\"", ",", "start", "=", "True", ")", ":", "ret", "=", "__salt__", "[", "\"salt_proxy.configure_proxy\"", "]", "(", "proxyname", ",", "start", "=", "start", ")", "ret", ".", "update", "("...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/salt_proxy.py#L31-L56
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/visualization/bloch.py
python
Bloch.add_vectors
(self, vectors)
Add a list of vectors to Bloch sphere. Args: vectors (array_like): Array with vectors of unit length or smaller.
Add a list of vectors to Bloch sphere.
[ "Add", "a", "list", "of", "vectors", "to", "Bloch", "sphere", "." ]
def add_vectors(self, vectors): """Add a list of vectors to Bloch sphere. Args: vectors (array_like): Array with vectors of unit length or smaller. """ if isinstance(vectors[0], (list, np.ndarray)): for vec in vectors: self.vectors.append(vec) else: self.vectors.append(vectors)
[ "def", "add_vectors", "(", "self", ",", "vectors", ")", ":", "if", "isinstance", "(", "vectors", "[", "0", "]", ",", "(", "list", ",", "np", ".", "ndarray", ")", ")", ":", "for", "vec", "in", "vectors", ":", "self", ".", "vectors", ".", "append", ...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/visualization/bloch.py#L358-L369
pyscf/pyscf
0adfb464333f5ceee07b664f291d4084801bae64
pyscf/gto/mole.py
python
Mole.intor
(self, intor, comp=None, hermi=0, aosym='s1', out=None, shls_slice=None, grids=None)
return moleintor.getints(intor, self._atm, bas, env, shls_slice, comp, hermi, aosym, out=out)
Integral generator. Args: intor : str Name of the 1e or 2e AO integrals. Ref to :func:`getints` for the complete list of available 1-electron integral names Kwargs: comp : int Components of the integrals, e.g. int1e_ipovlp_sph has 3 components. hermi : int Symmetry of the integrals | 0 : no symmetry assumed (default) | 1 : hermitian | 2 : anti-hermitian grids : ndarray Coordinates of grids for the int1e_grids integrals Returns: ndarray of 1-electron integrals, can be either 2-dim or 3-dim, depending on comp Examples: >>> mol.build(atom='H 0 0 0; H 0 0 1.1', basis='sto-3g') >>> mol.intor('int1e_ipnuc_sph', comp=3) # <nabla i | V_nuc | j> [[[ 0. 0. ] [ 0. 0. ]] [[ 0. 0. ] [ 0. 0. ]] [[ 0.10289944 0.48176097] [-0.48176097 -0.10289944]]] >>> mol.intor('int1e_nuc_spinor') [[-1.69771092+0.j 0.00000000+0.j -0.67146312+0.j 0.00000000+0.j] [ 0.00000000+0.j -1.69771092+0.j 0.00000000+0.j -0.67146312+0.j] [-0.67146312+0.j 0.00000000+0.j -1.69771092+0.j 0.00000000+0.j] [ 0.00000000+0.j -0.67146312+0.j 0.00000000+0.j -1.69771092+0.j]]
Integral generator.
[ "Integral", "generator", "." ]
def intor(self, intor, comp=None, hermi=0, aosym='s1', out=None, shls_slice=None, grids=None): '''Integral generator. Args: intor : str Name of the 1e or 2e AO integrals. Ref to :func:`getints` for the complete list of available 1-electron integral names Kwargs: comp : int Components of the integrals, e.g. int1e_ipovlp_sph has 3 components. hermi : int Symmetry of the integrals | 0 : no symmetry assumed (default) | 1 : hermitian | 2 : anti-hermitian grids : ndarray Coordinates of grids for the int1e_grids integrals Returns: ndarray of 1-electron integrals, can be either 2-dim or 3-dim, depending on comp Examples: >>> mol.build(atom='H 0 0 0; H 0 0 1.1', basis='sto-3g') >>> mol.intor('int1e_ipnuc_sph', comp=3) # <nabla i | V_nuc | j> [[[ 0. 0. ] [ 0. 0. ]] [[ 0. 0. ] [ 0. 0. ]] [[ 0.10289944 0.48176097] [-0.48176097 -0.10289944]]] >>> mol.intor('int1e_nuc_spinor') [[-1.69771092+0.j 0.00000000+0.j -0.67146312+0.j 0.00000000+0.j] [ 0.00000000+0.j -1.69771092+0.j 0.00000000+0.j -0.67146312+0.j] [-0.67146312+0.j 0.00000000+0.j -1.69771092+0.j 0.00000000+0.j] [ 0.00000000+0.j -0.67146312+0.j 0.00000000+0.j -1.69771092+0.j]] ''' if not self._built: logger.warn(self, 'Warning: intor envs of %s not initialized.', self) # FIXME: Whether to check _built and call build? ._bas and .basis # may not be consistent. calling .build() may leads to wrong intor env. #self.build(False, False) intor = self._add_suffix(intor) bas = self._bas env = self._env if 'ECP' in intor: assert(self._ecp is not None) bas = numpy.vstack((self._bas, self._ecpbas)) env[AS_ECPBAS_OFFSET] = len(self._bas) env[AS_NECPBAS] = len(self._ecpbas) if shls_slice is None: shls_slice = (0, self.nbas, 0, self.nbas) elif '_grids' in intor: assert grids is not None env = numpy.append(env, grids.ravel()) env[NGRIDS] = grids.shape[0] env[PTR_GRIDS] = env.size - grids.size return moleintor.getints(intor, self._atm, bas, env, shls_slice, comp, hermi, aosym, out=out)
[ "def", "intor", "(", "self", ",", "intor", ",", "comp", "=", "None", ",", "hermi", "=", "0", ",", "aosym", "=", "'s1'", ",", "out", "=", "None", ",", "shls_slice", "=", "None", ",", "grids", "=", "None", ")", ":", "if", "not", "self", ".", "_bu...
https://github.com/pyscf/pyscf/blob/0adfb464333f5ceee07b664f291d4084801bae64/pyscf/gto/mole.py#L3233-L3295
c0rv4x/project-black
2d3df00ba1b1453c99ec5a247793a74e11adba2a
black/workers/patator/patator_task.py
python
PatatorTask.client_connected_cb
(self, reader, writer)
Callback which is called, after unix socket (the socket which is responsible for transporting socket data) receives a new connection
Callback which is called, after unix socket (the socket which is responsible for transporting socket data) receives a new connection
[ "Callback", "which", "is", "called", "after", "unix", "socket", "(", "the", "socket", "which", "is", "responsible", "for", "transporting", "socket", "data", ")", "receives", "a", "new", "connection" ]
def client_connected_cb(self, reader, writer): """ Callback which is called, after unix socket (the socket which is responsible for transporting socket data) receives a new connection """ self.loop.create_task(self.poll_status(reader))
[ "def", "client_connected_cb", "(", "self", ",", "reader", ",", "writer", ")", ":", "self", ".", "loop", ".", "create_task", "(", "self", ".", "poll_status", "(", "reader", ")", ")" ]
https://github.com/c0rv4x/project-black/blob/2d3df00ba1b1453c99ec5a247793a74e11adba2a/black/workers/patator/patator_task.py#L63-L66
inspurer/WorkAttendanceSystem
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/requests/sessions.py
python
Session.get
(self, url, **kwargs)
return self.request('GET', url, **kwargs)
Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
Sends a GET request. Returns :class:`Response` object.
[ "Sends", "a", "GET", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def get(self, url, **kwargs): """Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
[ "def", "get", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'GET'", ",", "url", ",", "*", "*", "kwargs", ")" ]
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/requests/sessions.py#L479-L488
cassieeric/python_crawler
b50b5b55404e32164dc82ff0c23cdae0c4b168ae
weixin_crawler/project/Application/gzh_crawler/__init__.py
python
GZHCrawler.gzh_report
(self,gzh)
:param gzh: :return:生成公众号历史文章数据报告
:param gzh: :return:生成公众号历史文章数据报告
[ ":", "param", "gzh", ":", ":", "return", ":", "生成公众号历史文章数据报告" ]
def gzh_report(self,gzh): """ :param gzh: :return:生成公众号历史文章数据报告 """ pass
[ "def", "gzh_report", "(", "self", ",", "gzh", ")", ":", "pass" ]
https://github.com/cassieeric/python_crawler/blob/b50b5b55404e32164dc82ff0c23cdae0c4b168ae/weixin_crawler/project/Application/gzh_crawler/__init__.py#L137-L142
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1beta1_flow_schema_status.py
python
V1beta1FlowSchemaStatus.conditions
(self)
return self._conditions
Gets the conditions of this V1beta1FlowSchemaStatus. # noqa: E501 `conditions` is a list of the current states of FlowSchema. # noqa: E501 :return: The conditions of this V1beta1FlowSchemaStatus. # noqa: E501 :rtype: list[V1beta1FlowSchemaCondition]
Gets the conditions of this V1beta1FlowSchemaStatus. # noqa: E501
[ "Gets", "the", "conditions", "of", "this", "V1beta1FlowSchemaStatus", ".", "#", "noqa", ":", "E501" ]
def conditions(self): """Gets the conditions of this V1beta1FlowSchemaStatus. # noqa: E501 `conditions` is a list of the current states of FlowSchema. # noqa: E501 :return: The conditions of this V1beta1FlowSchemaStatus. # noqa: E501 :rtype: list[V1beta1FlowSchemaCondition] """ return self._conditions
[ "def", "conditions", "(", "self", ")", ":", "return", "self", ".", "_conditions" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1beta1_flow_schema_status.py#L56-L64
akirafukui/vqa-mcb
172775b2ec927456eecbe1aa5878b673482f2a54
train/v4/train_v4.py
python
make_vocab_files
()
return question_vocab, answer_vocab
Produce the question and answer vocabulary files.
Produce the question and answer vocabulary files.
[ "Produce", "the", "question", "and", "answer", "vocabulary", "files", "." ]
def make_vocab_files(): """ Produce the question and answer vocabulary files. """ print 'making question vocab...', config.QUESTION_VOCAB_SPACE qdic, _ = VQADataProvider.load_data(config.QUESTION_VOCAB_SPACE) question_vocab = make_question_vocab(qdic) print 'making answer vocab...', config.ANSWER_VOCAB_SPACE _, adic = VQADataProvider.load_data(config.ANSWER_VOCAB_SPACE) answer_vocab = make_answer_vocab(adic, config.NUM_OUTPUT_UNITS) return question_vocab, answer_vocab
[ "def", "make_vocab_files", "(", ")", ":", "print", "'making question vocab...'", ",", "config", ".", "QUESTION_VOCAB_SPACE", "qdic", ",", "_", "=", "VQADataProvider", ".", "load_data", "(", "config", ".", "QUESTION_VOCAB_SPACE", ")", "question_vocab", "=", "make_que...
https://github.com/akirafukui/vqa-mcb/blob/172775b2ec927456eecbe1aa5878b673482f2a54/train/v4/train_v4.py#L135-L145
holland-backup/holland
77dcfe9f23d4254e4c351cdc18f29a8d34945812
holland/core/config/config.py
python
BaseConfig.lookup
(self, key, safe=True)
return result
Lookup a configuration item based on the dot-separated path.
Lookup a configuration item based on the dot-separated path.
[ "Lookup", "a", "configuration", "item", "based", "on", "the", "dot", "-", "separated", "path", "." ]
def lookup(self, key, safe=True): """ Lookup a configuration item based on the dot-separated path. """ parts = key.split(".") # lookup key as a . separated hierarchy path section = self result = None count = 0 for count, name in enumerate(parts): if not isinstance(section, Section): result = None break result = section.get(name) section = result if not result and not safe: raise KeyError("%r not found (%r)" % (key, parts[count])) if isinstance(result, bytes): return result.decode("utf-8") return result
[ "def", "lookup", "(", "self", ",", "key", ",", "safe", "=", "True", ")", ":", "parts", "=", "key", ".", "split", "(", "\".\"", ")", "# lookup key as a . separated hierarchy path", "section", "=", "self", "result", "=", "None", "count", "=", "0", "for", "...
https://github.com/holland-backup/holland/blob/77dcfe9f23d4254e4c351cdc18f29a8d34945812/holland/core/config/config.py#L105-L125
MediaBrowser/plugin.video.emby
71162fc7704656833d8b228dc9014f88742215b1
resources/lib/library.py
python
Library.startup
(self)
return False
Run at startup. Check databases. Check for the server plugin.
Run at startup. Check databases. Check for the server plugin.
[ "Run", "at", "startup", ".", "Check", "databases", ".", "Check", "for", "the", "server", "plugin", "." ]
def startup(self): ''' Run at startup. Check databases. Check for the server plugin. ''' self.started = True Views().get_views() Views().get_nodes() try: if get_sync()['Libraries']: self.sync_libraries() elif not settings('SyncInstallRunDone.bool'): with self.sync(self, self.server) as sync: sync.libraries() Views().get_nodes() xbmc.executebuiltin('ReloadSkin()') return True self.get_fast_sync() return True except LibraryException as error: LOG.error(error.status) if error.status in 'SyncLibraryLater': dialog("ok", heading="{emby}", line1=_(33129)) settings('SyncInstallRunDone.bool', True) sync = get_sync() sync['Libraries'] = [] save_sync(sync) return True elif error.status == 'CompanionMissing': dialog("ok", heading="{emby}", line1=_(33099)) settings('kodiCompanion.bool', False) return True elif error.status == 'StopWriteCalled': self.verify_libs = True raise except Exception as error: LOG.exception(error) return False
[ "def", "startup", "(", "self", ")", ":", "self", ".", "started", "=", "True", "Views", "(", ")", ".", "get_views", "(", ")", "Views", "(", ")", ".", "get_nodes", "(", ")", "try", ":", "if", "get_sync", "(", ")", "[", "'Libraries'", "]", ":", "sel...
https://github.com/MediaBrowser/plugin.video.emby/blob/71162fc7704656833d8b228dc9014f88742215b1/resources/lib/library.py#L485-L540
projecthamster/hamster
19d160090de30e756bdc3122ff935bdaa86e2843
src/hamster/lib/fact.py
python
Fact.end_time
(self)
return self.range.end
Fact range end. Deprecated, use self.range.end instead.
Fact range end.
[ "Fact", "range", "end", "." ]
def end_time(self): """Fact range end. Deprecated, use self.range.end instead. """ return self.range.end
[ "def", "end_time", "(", "self", ")", ":", "return", "self", ".", "range", ".", "end" ]
https://github.com/projecthamster/hamster/blob/19d160090de30e756bdc3122ff935bdaa86e2843/src/hamster/lib/fact.py#L151-L156
sigmavirus24/github3.py
f642a27833d6bef93daf5bb27b35e5ddbcfbb773
src/github3/users.py
python
_User.followers
(self, number=-1, etag=None)
return self._iter(int(number), url, ShortUser, etag=etag)
r"""Iterate over the followers of this user. :param int number: (optional), number of followers to return. Default: -1 returns all available :param str etag: (optional), ETag from a previous request to the same endpoint :returns: generator of :class:`User <User>`\ s
r"""Iterate over the followers of this user.
[ "r", "Iterate", "over", "the", "followers", "of", "this", "user", "." ]
def followers(self, number=-1, etag=None): r"""Iterate over the followers of this user. :param int number: (optional), number of followers to return. Default: -1 returns all available :param str etag: (optional), ETag from a previous request to the same endpoint :returns: generator of :class:`User <User>`\ s """ url = self._build_url("followers", base_url=self._api) return self._iter(int(number), url, ShortUser, etag=etag)
[ "def", "followers", "(", "self", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "url", "=", "self", ".", "_build_url", "(", "\"followers\"", ",", "base_url", "=", "self", ".", "_api", ")", "return", "self", ".", "_iter", "(", "in...
https://github.com/sigmavirus24/github3.py/blob/f642a27833d6bef93daf5bb27b35e5ddbcfbb773/src/github3/users.py#L380-L390
astroML/astroML
f66558232f6d33cb34ecd1bed8a80b9db7ae1c30
astroML/plotting/tools.py
python
devectorize_axes
(ax=None, dpi=None, transparent=True)
return ax
Convert axes contents to a png. This is useful when plotting many points, as the size of the saved file can become very large otherwise. Parameters ---------- ax : Axes instance (optional) Axes to de-vectorize. If None, this uses the current active axes (plt.gca()) dpi: int (optional) resolution of the png image. If not specified, the default from 'savefig.dpi' in rcParams will be used transparent : bool (optional) if True (default) then the PNG will be made transparent Returns ------- ax : Axes instance the in-place modified Axes instance Examples -------- The code can be used in the following way:: >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from astroML.plotting.tools import devectorize_axes >>> fig, ax = plt.subplots() >>> x, y = np.random.random((2, 10000)) >>> ax.scatter(x, y) # doctest: +IGNORE_OUTPUT >>> devectorize_axes(ax) # doctest: +IGNORE_OUTPUT The resulting figure will be much smaller than the vectorized version.
Convert axes contents to a png.
[ "Convert", "axes", "contents", "to", "a", "png", "." ]
def devectorize_axes(ax=None, dpi=None, transparent=True): """Convert axes contents to a png. This is useful when plotting many points, as the size of the saved file can become very large otherwise. Parameters ---------- ax : Axes instance (optional) Axes to de-vectorize. If None, this uses the current active axes (plt.gca()) dpi: int (optional) resolution of the png image. If not specified, the default from 'savefig.dpi' in rcParams will be used transparent : bool (optional) if True (default) then the PNG will be made transparent Returns ------- ax : Axes instance the in-place modified Axes instance Examples -------- The code can be used in the following way:: >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from astroML.plotting.tools import devectorize_axes >>> fig, ax = plt.subplots() >>> x, y = np.random.random((2, 10000)) >>> ax.scatter(x, y) # doctest: +IGNORE_OUTPUT >>> devectorize_axes(ax) # doctest: +IGNORE_OUTPUT The resulting figure will be much smaller than the vectorized version. """ if ax is None: ax = plt.gca() fig = ax.figure axlim = ax.axis() # setup: make all visible spines (axes & ticks) & text invisible # we need to set these back later, so we save their current state _sp = {} _txt_vis = [t.get_visible() for t in ax.texts] for k in ax.spines: _sp[k] = ax.spines[k].get_visible() ax.spines[k].set_visible(False) for t in ax.texts: t.set_visible(False) _xax = ax.xaxis.get_visible() _yax = ax.yaxis.get_visible() _patch = ax.patch.get_visible() ax.patch.set_visible(False) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) # convert canvas to PNG extents = ax.bbox.extents / fig.dpi output = BytesIO() plt.savefig(output, format='png', dpi=dpi, transparent=transparent, bbox_inches=Bbox([extents[:2], extents[2:]])) output.seek(0) im = image.imread(output) # clear everything on axis (but not text) ax.lines = [] ax.patches = [] ax.tables = [] ax.artists = [] ax.images = [] ax.collections = [] # Show the image ax.imshow(im, extent=axlim, aspect='auto', interpolation='nearest') # restore all the spines & text for k in ax.spines: ax.spines[k].set_visible(_sp[k]) for t, v in zip(ax.texts, _txt_vis): t.set_visible(v) ax.patch.set_visible(_patch) ax.xaxis.set_visible(_xax) ax.yaxis.set_visible(_yax) if plt.isinteractive(): plt.draw() return ax
[ "def", "devectorize_axes", "(", "ax", "=", "None", ",", "dpi", "=", "None", ",", "transparent", "=", "True", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "fig", "=", "ax", ".", "figure", "axlim", "=", "ax", "...
https://github.com/astroML/astroML/blob/f66558232f6d33cb34ecd1bed8a80b9db7ae1c30/astroML/plotting/tools.py#L12-L103
standardebooks/tools
f57af3c5938a9aeed9e97e82b2c130424f6033e5
se/vendor/kindleunpack/mobi_html.py
python
XHTMLK8Processor.buildXHTML
(self)
return self.used
[]
def buildXHTML(self): # first need to update all links that are internal which # are based on positions within the xhtml files **BEFORE** # cutting and pasting any pieces into the xhtml text files # kindle:pos:fid:XXXX:off:YYYYYYYYYY (used for internal link within xhtml) # XXXX is the offset in records into divtbl # YYYYYYYYYYYY is a base32 number you add to the divtbl insertpos to get final position # pos:fid pattern posfid_pattern = re.compile(br'''(<a.*?href=.*?>)''', re.IGNORECASE) posfid_index_pattern = re.compile(br'''['"]kindle:pos:fid:([0-9|A-V]+):off:([0-9|A-V]+).*?["']''') parts = [] print("Building proper xhtml for each file") for i in range(self.k8proc.getNumberOfParts()): part = self.k8proc.getPart(i) [partnum, dir, filename, beg, end, aidtext] = self.k8proc.getPartInfo(i) # internal links srcpieces = posfid_pattern.split(part) for j in range(1, len(srcpieces),2): tag = srcpieces[j] if tag.startswith(b'<'): for m in posfid_index_pattern.finditer(tag): posfid = m.group(1) offset = m.group(2) filename, idtag = self.k8proc.getIDTagByPosFid(posfid, offset) if idtag == b'': replacement= b'"' + utf8_str(filename) + b'"' else: replacement = b'"' + utf8_str(filename) + b'#' + idtag + b'"' tag = posfid_index_pattern.sub(replacement, tag, 1) srcpieces[j] = tag part = b"".join(srcpieces) parts.append(part) # we are free to cut and paste as we see fit # we can safely remove all of the Kindlegen generated aid tags # change aid ids that are in k8proc.linked_aids to xhtml ids find_tag_with_aid_pattern = re.compile(br'''(<[^>]*\said\s*=[^>]*>)''', re.IGNORECASE) within_tag_aid_position_pattern = re.compile(br'''\said\s*=['"]([^'"]*)['"]''') for i in range(len(parts)): part = parts[i] srcpieces = find_tag_with_aid_pattern.split(part) for j in range(len(srcpieces)): tag = srcpieces[j] if tag.startswith(b'<'): for m in within_tag_aid_position_pattern.finditer(tag): try: aid = m.group(1) except IndexError: aid = None replacement = b'' if aid in self.k8proc.linked_aids: replacement = b' id="aid-' + aid + b'"' tag = within_tag_aid_position_pattern.sub(replacement, tag, 1) srcpieces[j] = tag part = b"".join(srcpieces) parts[i] = part # we can safely replace all of the Kindlegen generated data-AmznPageBreak tags # with page-break-after style patterns find_tag_with_AmznPageBreak_pattern = re.compile(br'''(<[^>]*\sdata-AmznPageBreak=[^>]*>)''', re.IGNORECASE) within_tag_AmznPageBreak_position_pattern = re.compile(br'''\sdata-AmznPageBreak=['"]([^'"]*)['"]''') for i in range(len(parts)): part = parts[i] srcpieces = find_tag_with_AmznPageBreak_pattern.split(part) for j in range(len(srcpieces)): tag = srcpieces[j] if tag.startswith(b'<'): srcpieces[j] = within_tag_AmznPageBreak_position_pattern.sub( lambda m:b' style="page-break-after:' + m.group(1) + b'"', tag) part = b"".join(srcpieces) parts[i] = part # we have to handle substitutions for the flows pieces first as they may # be inlined into the xhtml text # kindle:embed:XXXX?mime=image/gif (png, jpeg, etc) (used for images) # kindle:flow:XXXX?mime=YYYY/ZZZ (used for style sheets, svg images, etc) # kindle:embed:XXXX (used for fonts) flows = [] flows.append(None) flowinfo = [] flowinfo.append([None, None, None, None]) # regular expression search patterns img_pattern = re.compile(br'''(<[img\s|image\s][^>]*>)''', re.IGNORECASE) img_index_pattern = re.compile(br'''[('"]kindle:embed:([0-9|A-V]+)[^'"]*['")]''', re.IGNORECASE) tag_pattern = re.compile(br'''(<[^>]*>)''') flow_pattern = re.compile(br'''['"]kindle:flow:([0-9|A-V]+)\?mime=([^'"]+)['"]''', re.IGNORECASE) url_pattern = re.compile(br'''(url\(.*?\))''', re.IGNORECASE) url_img_index_pattern = re.compile(br'''[('"]kindle:embed:([0-9|A-V]+)\?mime=image/[^\)]*["')]''', re.IGNORECASE) font_index_pattern = re.compile(br'''[('"]kindle:embed:([0-9|A-V]+)["')]''', re.IGNORECASE) url_css_index_pattern = re.compile(br'''kindle:flow:([0-9|A-V]+)\?mime=text/css[^\)]*''', re.IGNORECASE) for i in range(1, self.k8proc.getNumberOfFlows()): [ftype, format, dir, filename] = self.k8proc.getFlowInfo(i) flowpart = self.k8proc.getFlow(i) # links to raster image files from image tags # image_pattern srcpieces = img_pattern.split(flowpart) for j in range(1, len(srcpieces),2): tag = srcpieces[j] if tag.startswith(b'<im'): for m in img_index_pattern.finditer(tag): imageNumber = fromBase32(m.group(1)) imageName = self.rscnames[imageNumber-1] if imageName is not None: replacement = b'"../Images/' + utf8_str(imageName) + b'"' self.used[imageName] = 'used' tag = img_index_pattern.sub(replacement, tag, 1) else: print("Error: Referenced image %s was not recognized as a valid image in %s" % (imageNumber, tag)) srcpieces[j] = tag flowpart = b"".join(srcpieces) # replacements inside css url(): srcpieces = url_pattern.split(flowpart) for j in range(1, len(srcpieces),2): tag = srcpieces[j] # process links to raster image files for m in url_img_index_pattern.finditer(tag): imageNumber = fromBase32(m.group(1)) imageName = self.rscnames[imageNumber-1] osep = m.group()[0:1] csep = m.group()[-1:] if imageName is not None: replacement = osep + b'../Images/' + utf8_str(imageName) + csep self.used[imageName] = 'used' tag = url_img_index_pattern.sub(replacement, tag, 1) else: print("Error: Referenced image %s was not recognized as a valid image in %s" % (imageNumber, tag)) # process links to fonts for m in font_index_pattern.finditer(tag): fontNumber = fromBase32(m.group(1)) fontName = self.rscnames[fontNumber-1] osep = m.group()[0:1] csep = m.group()[-1:] if fontName is None: print("Error: Referenced font %s was not recognized as a valid font in %s" % (fontNumber, tag)) else: replacement = osep + b'../Fonts/' + utf8_str(fontName) + csep tag = font_index_pattern.sub(replacement, tag, 1) self.used[fontName] = 'used' # process links to other css pieces for m in url_css_index_pattern.finditer(tag): num = fromBase32(m.group(1)) [typ, fmt, pdir, fnm] = self.k8proc.getFlowInfo(num) replacement = b'"../' + utf8_str(pdir) + b'/' + utf8_str(fnm) + b'"' tag = url_css_index_pattern.sub(replacement, tag, 1) self.used[fnm] = 'used' srcpieces[j] = tag flowpart = b"".join(srcpieces) # store away in our own copy flows.append(flowpart) # I do not think this case exists and even if it does exist, it needs to be done in a separate # pass to prevent inlining a flow piece into another flow piece before the inserted one or the # target one has been fully processed # but keep it around if it ends up we do need it # flow pattern not inside url() # srcpieces = tag_pattern.split(flowpart) # for j in range(1, len(srcpieces),2): # tag = srcpieces[j] # if tag.startswith(b'<'): # for m in flow_pattern.finditer(tag): # num = fromBase32(m.group(1)) # [typ, fmt, pdir, fnm] = self.k8proc.getFlowInfo(num) # flowtext = self.k8proc.getFlow(num) # if fmt == b'inline': # tag = flowtext # else: # replacement = b'"../' + utf8_str(pdir) + b'/' + utf8_str(fnm) + b'"' # tag = flow_pattern.sub(replacement, tag, 1) # self.used[fnm] = 'used' # srcpieces[j] = tag # flowpart = b"".join(srcpieces) # now handle the main text xhtml parts # Handle the flow items in the XHTML text pieces # kindle:flow:XXXX?mime=YYYY/ZZZ (used for style sheets, svg images, etc) tag_pattern = re.compile(br'''(<[^>]*>)''') flow_pattern = re.compile(br'''['"]kindle:flow:([0-9|A-V]+)\?mime=([^'"]+)['"]''', re.IGNORECASE) for i in range(len(parts)): part = parts[i] [partnum, dir, filename, beg, end, aidtext] = self.k8proc.partinfo[i] # flow pattern srcpieces = tag_pattern.split(part) for j in range(1, len(srcpieces),2): tag = srcpieces[j] if tag.startswith(b'<'): for m in flow_pattern.finditer(tag): num = fromBase32(m.group(1)) if num > 0 and num < len(self.k8proc.flowinfo): [typ, fmt, pdir, fnm] = self.k8proc.getFlowInfo(num) flowpart = flows[num] if fmt == b'inline': tag = flowpart else: replacement = b'"../' + utf8_str(pdir) + b'/' + utf8_str(fnm) + b'"' tag = flow_pattern.sub(replacement, tag, 1) self.used[fnm] = 'used' else: print("warning: ignoring non-existent flow link", tag, " value 0x%x" % num) srcpieces[j] = tag part = b''.join(srcpieces) # store away modified version parts[i] = part # Handle any embedded raster images links in style= attributes urls style_pattern = re.compile(br'''(<[a-zA-Z0-9]+\s[^>]*style\s*=\s*[^>]*>)''', re.IGNORECASE) img_index_pattern = re.compile(br'''[('"]kindle:embed:([0-9|A-V]+)[^'"]*['")]''', re.IGNORECASE) for i in range(len(parts)): part = parts[i] [partnum, dir, filename, beg, end, aidtext] = self.k8proc.partinfo[i] # replace urls in style attributes srcpieces = style_pattern.split(part) for j in range(1, len(srcpieces),2): tag = srcpieces[j] if b'kindle:embed' in tag: for m in img_index_pattern.finditer(tag): imageNumber = fromBase32(m.group(1)) imageName = self.rscnames[imageNumber-1] osep = m.group()[0:1] csep = m.group()[-1:] if imageName is not None: replacement = osep + b'../Images/'+ utf8_str(imageName) + csep self.used[imageName] = 'used' tag = img_index_pattern.sub(replacement, tag, 1) else: print("Error: Referenced image %s in style url was not recognized in %s" % (imageNumber, tag)) srcpieces[j] = tag part = b"".join(srcpieces) # store away modified version parts[i] = part # Handle any embedded raster images links in the xhtml text # kindle:embed:XXXX?mime=image/gif (png, jpeg, etc) (used for images) img_pattern = re.compile(br'''(<[img\s|image\s][^>]*>)''', re.IGNORECASE) img_index_pattern = re.compile(br'''['"]kindle:embed:([0-9|A-V]+)[^'"]*['"]''') for i in range(len(parts)): part = parts[i] [partnum, dir, filename, beg, end, aidtext] = self.k8proc.partinfo[i] # links to raster image files # image_pattern srcpieces = img_pattern.split(part) for j in range(1, len(srcpieces),2): tag = srcpieces[j] if tag.startswith(b'<im'): for m in img_index_pattern.finditer(tag): imageNumber = fromBase32(m.group(1)) imageName = self.rscnames[imageNumber-1] if imageName is not None: replacement = b'"../Images/' + utf8_str(imageName) + b'"' self.used[imageName] = 'used' tag = img_index_pattern.sub(replacement, tag, 1) else: print("Error: Referenced image %s was not recognized as a valid image in %s" % (imageNumber, tag)) srcpieces[j] = tag part = b"".join(srcpieces) # store away modified version parts[i] = part # finally perform any general cleanups needed to make valid XHTML # these include: # in svg tags replace "perserveaspectratio" attributes with "perserveAspectRatio" # in svg tags replace "viewbox" attributes with "viewBox" # in <li> remove value="XX" attributes since these are illegal tag_pattern = re.compile(br'''(<[^>]*>)''') li_value_pattern = re.compile(br'''\svalue\s*=\s*['"][^'"]*['"]''', re.IGNORECASE) for i in range(len(parts)): part = parts[i] [partnum, dir, filename, beg, end, aidtext] = self.k8proc.partinfo[i] # tag pattern srcpieces = tag_pattern.split(part) for j in range(1, len(srcpieces),2): tag = srcpieces[j] if tag.startswith(b'<svg') or tag.startswith(b'<SVG'): tag = tag.replace(b'preserveaspectratio',b'preserveAspectRatio') tag = tag.replace(b'viewbox',b'viewBox') elif tag.startswith(b'<li ') or tag.startswith(b'<LI '): tagpieces = li_value_pattern.split(tag) tag = b"".join(tagpieces) srcpieces[j] = tag part = b"".join(srcpieces) # store away modified version parts[i] = part self.k8proc.setFlows(flows) self.k8proc.setParts(parts) return self.used
[ "def", "buildXHTML", "(", "self", ")", ":", "# first need to update all links that are internal which", "# are based on positions within the xhtml files **BEFORE**", "# cutting and pasting any pieces into the xhtml text files", "# kindle:pos:fid:XXXX:off:YYYYYYYYYY (used for internal link withi...
https://github.com/standardebooks/tools/blob/f57af3c5938a9aeed9e97e82b2c130424f6033e5/se/vendor/kindleunpack/mobi_html.py#L117-L430
microsoft/unilm
65f15af2a307ebb64cfb25adf54375b002e6fe8d
xtune/src/transformers/modeling_tf_bert.py
python
TFBertMainLayer._prune_heads
(self, heads_to_prune)
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel
[ "Prunes", "heads", "of", "the", "model", ".", "heads_to_prune", ":", "dict", "of", "{", "layer_num", ":", "list", "of", "heads", "to", "prune", "in", "this", "layer", "}", "See", "base", "class", "PreTrainedModel" ]
def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ raise NotImplementedError
[ "def", "_prune_heads", "(", "self", ",", "heads_to_prune", ")", ":", "raise", "NotImplementedError" ]
https://github.com/microsoft/unilm/blob/65f15af2a307ebb64cfb25adf54375b002e6fe8d/xtune/src/transformers/modeling_tf_bert.py#L489-L494
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py
python
EvaluationInstance.date_created
(self)
return self._properties['date_created']
:returns: The date_created :rtype: datetime
:returns: The date_created :rtype: datetime
[ ":", "returns", ":", "The", "date_created", ":", "rtype", ":", "datetime" ]
def date_created(self): """ :returns: The date_created :rtype: datetime """ return self._properties['date_created']
[ "def", "date_created", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'date_created'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py#L337-L342
rcorcs/NatI
fdf014f4292afdc95250add7b6658468043228e1
en/parser/nltk_lite/draw/chart.py
python
ChartView._analyze_edge
(self, edge)
Given a new edge, recalculate: - _text_height - _unitsize (if the edge text is too big for the current _unitsize, then increase _unitsize)
Given a new edge, recalculate:
[ "Given", "a", "new", "edge", "recalculate", ":" ]
def _analyze_edge(self, edge): """ Given a new edge, recalculate: - _text_height - _unitsize (if the edge text is too big for the current _unitsize, then increase _unitsize) """ c = self._chart_canvas if isinstance(edge, TreeEdge): lhs = edge.lhs() rhselts = [] for elt in edge.rhs(): if isinstance(elt, cfg.Nonterminal): rhselts.append(str(elt.symbol())) else: rhselts.append(repr(elt)) rhs = ' '.join(rhselts) else: lhs = edge.lhs() rhs = '' for s in (lhs, rhs): tag = c.create_text(0,0, text=s, font=self._boldfont, anchor='nw', justify='left') bbox = c.bbox(tag) c.delete(tag) width = bbox[2] #+ ChartView._LEAF_SPACING edgelen = max(edge.length(), 1) self._unitsize = max(self._unitsize, width/edgelen) self._text_height = max(self._text_height, bbox[3] - bbox[1])
[ "def", "_analyze_edge", "(", "self", ",", "edge", ")", ":", "c", "=", "self", ".", "_chart_canvas", "if", "isinstance", "(", "edge", ",", "TreeEdge", ")", ":", "lhs", "=", "edge", ".", "lhs", "(", ")", "rhselts", "=", "[", "]", "for", "elt", "in", ...
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/en/parser/nltk_lite/draw/chart.py#L1098-L1130
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/plat-sunos5/IN.py
python
ntohl
(x)
return (x)
[]
def ntohl(x): return (x)
[ "def", "ntohl", "(", "x", ")", ":", "return", "(", "x", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/plat-sunos5/IN.py#L1239-L1239
yaqwsx/KiKit
14de7f60b64e6d03ce638e78d279915d09bb9ac7
kikit/panelize_ui_impl.py
python
obtainPreset
(presetPaths, validate=True, **kwargs)
return preset
Given a preset paths from the user and the overrides in the form of named arguments, construt the preset. Ensures a valid preset is always found
Given a preset paths from the user and the overrides in the form of named arguments, construt the preset.
[ "Given", "a", "preset", "paths", "from", "the", "user", "and", "the", "overrides", "in", "the", "form", "of", "named", "arguments", "construt", "the", "preset", "." ]
def obtainPreset(presetPaths, validate=True, **kwargs): """ Given a preset paths from the user and the overrides in the form of named arguments, construt the preset. Ensures a valid preset is always found """ presetChain = [":default"] + list(presetPaths) preset = loadPresetChain(presetChain) for name, section in kwargs.items(): if section is not None: mergePresets(preset, {name: section}) if validate: validateSections(preset) postProcessPreset(preset) return preset
[ "def", "obtainPreset", "(", "presetPaths", ",", "validate", "=", "True", ",", "*", "*", "kwargs", ")", ":", "presetChain", "=", "[", "\":default\"", "]", "+", "list", "(", "presetPaths", ")", "preset", "=", "loadPresetChain", "(", "presetChain", ")", "for"...
https://github.com/yaqwsx/KiKit/blob/14de7f60b64e6d03ce638e78d279915d09bb9ac7/kikit/panelize_ui_impl.py#L199-L214
google/TensorNetwork
e12580f1749493dbe05f474d2fecdec4eaba73c5
tensornetwork/backends/abstract_backend.py
python
AbstractBackend.item
(self, tensor)
Return the item of a 1-element tensor. Args: tensor: A 1-element tensor Returns: The value in tensor.
Return the item of a 1-element tensor.
[ "Return", "the", "item", "of", "a", "1", "-", "element", "tensor", "." ]
def item(self, tensor) -> Union[float, int, complex]: """ Return the item of a 1-element tensor. Args: tensor: A 1-element tensor Returns: The value in tensor. """ raise NotImplementedError("Backend {self.name} has not implemented item")
[ "def", "item", "(", "self", ",", "tensor", ")", "->", "Union", "[", "float", ",", "int", ",", "complex", "]", ":", "raise", "NotImplementedError", "(", "\"Backend {self.name} has not implemented item\"", ")" ]
https://github.com/google/TensorNetwork/blob/e12580f1749493dbe05f474d2fecdec4eaba73c5/tensornetwork/backends/abstract_backend.py#L1014-L1024
encode/django-rest-framework
c5be86a6dbf3d21b00a296af5994fa075826bf0b
rest_framework/schemas/coreapi.py
python
SchemaGenerator.get_links
(self, request=None)
return links
Return a dictionary containing all the links that should be included in the API schema.
Return a dictionary containing all the links that should be included in the API schema.
[ "Return", "a", "dictionary", "containing", "all", "the", "links", "that", "should", "be", "included", "in", "the", "API", "schema", "." ]
def get_links(self, request=None): """ Return a dictionary containing all the links that should be included in the API schema. """ links = LinkNode() paths, view_endpoints = self._get_paths_and_endpoints(request) # Only generate the path prefix for paths that will be included if not paths: return None prefix = self.determine_path_prefix(paths) for path, method, view in view_endpoints: if not self.has_view_permissions(path, method, view): continue link = view.schema.get_link(path, method, base_url=self.url) subpath = path[len(prefix):] keys = self.get_keys(subpath, method, view) insert_into(links, keys, link) return links
[ "def", "get_links", "(", "self", ",", "request", "=", "None", ")", ":", "links", "=", "LinkNode", "(", ")", "paths", ",", "view_endpoints", "=", "self", ".", "_get_paths_and_endpoints", "(", "request", ")", "# Only generate the path prefix for paths that will be inc...
https://github.com/encode/django-rest-framework/blob/c5be86a6dbf3d21b00a296af5994fa075826bf0b/rest_framework/schemas/coreapi.py#L126-L148
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/asn1crypto/util.py
python
extended_datetime.utcoffset
(self)
return self.tzinfo.utcoffset(self.replace(year=2000))
:return: None or a datetime.timedelta() of the offset from UTC
:return: None or a datetime.timedelta() of the offset from UTC
[ ":", "return", ":", "None", "or", "a", "datetime", ".", "timedelta", "()", "of", "the", "offset", "from", "UTC" ]
def utcoffset(self): """ :return: None or a datetime.timedelta() of the offset from UTC """ if self.tzinfo is None: return None return self.tzinfo.utcoffset(self.replace(year=2000))
[ "def", "utcoffset", "(", "self", ")", ":", "if", "self", ".", "tzinfo", "is", "None", ":", "return", "None", "return", "self", ".", "tzinfo", ".", "utcoffset", "(", "self", ".", "replace", "(", "year", "=", "2000", ")", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/asn1crypto/util.py#L473-L481
yihui-he/KL-Loss
66c0ed9e886a2218f4cf88c0efd4f40199bff54a
detectron/roi_data/fast_rcnn.py
python
add_fast_rcnn_blobs
(blobs, im_scales, roidb)
return valid
Add blobs needed for training Fast R-CNN style models.
Add blobs needed for training Fast R-CNN style models.
[ "Add", "blobs", "needed", "for", "training", "Fast", "R", "-", "CNN", "style", "models", "." ]
def add_fast_rcnn_blobs(blobs, im_scales, roidb): """Add blobs needed for training Fast R-CNN style models.""" # Sample training RoIs from each image and append them to the blob lists for im_i, entry in enumerate(roidb): frcn_blobs = _sample_rois(entry, im_scales[im_i], im_i) for k, v in frcn_blobs.items(): blobs[k].append(v) # Concat the training blob lists into tensors for k, v in blobs.items(): if isinstance(v, list) and len(v) > 0: blobs[k] = np.concatenate(v) # Add FPN multilevel training RoIs, if configured if cfg.FPN.FPN_ON and cfg.FPN.MULTILEVEL_ROIS: _add_multilevel_rois(blobs) # Perform any final work and validity checks after the collating blobs for # all minibatch images valid = True if cfg.MODEL.KEYPOINTS_ON: valid = keypoint_rcnn_roi_data.finalize_keypoint_minibatch(blobs, valid) return valid
[ "def", "add_fast_rcnn_blobs", "(", "blobs", ",", "im_scales", ",", "roidb", ")", ":", "# Sample training RoIs from each image and append them to the blob lists", "for", "im_i", ",", "entry", "in", "enumerate", "(", "roidb", ")", ":", "frcn_blobs", "=", "_sample_rois", ...
https://github.com/yihui-he/KL-Loss/blob/66c0ed9e886a2218f4cf88c0efd4f40199bff54a/detectron/roi_data/fast_rcnn.py#L108-L129
IdentityPython/pysaml2
6badb32d212257bd83ffcc816f9b625f68281b47
src/saml2/response.py
python
LogoutResponse.__init__
(self, sec_context, return_addrs=None, timeslack=0, asynchop=True, conv_info=None)
[]
def __init__(self, sec_context, return_addrs=None, timeslack=0, asynchop=True, conv_info=None): StatusResponse.__init__(self, sec_context, return_addrs, timeslack, asynchop=asynchop, conv_info=conv_info) self.signature_check = self.sec.correctly_signed_logout_response
[ "def", "__init__", "(", "self", ",", "sec_context", ",", "return_addrs", "=", "None", ",", "timeslack", "=", "0", ",", "asynchop", "=", "True", ",", "conv_info", "=", "None", ")", ":", "StatusResponse", ".", "__init__", "(", "self", ",", "sec_context", "...
https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/response.py#L449-L453
JulianEberius/SublimePythonIDE
d70e40abc0c9f347af3204c7b910e0d6bfd6e459
server/lib/python2/rope/base/codeanalyze.py
python
CachingLogicalLineFinder._init_logicals
(self)
Should initialize _starts and _ends attributes
Should initialize _starts and _ends attributes
[ "Should", "initialize", "_starts", "and", "_ends", "attributes" ]
def _init_logicals(self): """Should initialize _starts and _ends attributes""" size = self.lines.length() + 1 self._starts = [None] * size self._ends = [None] * size for start, end in self._generate(self.lines): self._starts[start] = True self._ends[end] = True
[ "def", "_init_logicals", "(", "self", ")", ":", "size", "=", "self", ".", "lines", ".", "length", "(", ")", "+", "1", "self", ".", "_starts", "=", "[", "None", "]", "*", "size", "self", ".", "_ends", "=", "[", "None", "]", "*", "size", "for", "...
https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python2/rope/base/codeanalyze.py#L270-L277
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/itsdangerous.py
python
Signer.get_signature
(self, value)
return base64_encode(sig)
Returns the signature for the given value
Returns the signature for the given value
[ "Returns", "the", "signature", "for", "the", "given", "value" ]
def get_signature(self, value): """Returns the signature for the given value""" value = want_bytes(value) key = self.derive_key() sig = self.algorithm.get_signature(key, value) return base64_encode(sig)
[ "def", "get_signature", "(", "self", ",", "value", ")", ":", "value", "=", "want_bytes", "(", "value", ")", "key", "=", "self", ".", "derive_key", "(", ")", "sig", "=", "self", ".", "algorithm", ".", "get_signature", "(", "key", ",", "value", ")", "r...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/itsdangerous.py#L344-L349
JasonKessler/scattertext
ef33f06d4c31f9d64b551a7ab86bf157aca82644
scattertext/PValGetter.py
python
get_p_vals
(df, positive_category, term_significance)
return term_significance.get_p_vals(X)
Parameters ---------- df : A data frame from, e.g., get_term_freq_df : pd.DataFrame positive_category : str The positive category name. term_significance : TermSignificance A TermSignificance instance from which to extract p-values.
Parameters ---------- df : A data frame from, e.g., get_term_freq_df : pd.DataFrame positive_category : str The positive category name. term_significance : TermSignificance A TermSignificance instance from which to extract p-values.
[ "Parameters", "----------", "df", ":", "A", "data", "frame", "from", "e", ".", "g", ".", "get_term_freq_df", ":", "pd", ".", "DataFrame", "positive_category", ":", "str", "The", "positive", "category", "name", ".", "term_significance", ":", "TermSignificance", ...
def get_p_vals(df, positive_category, term_significance): ''' Parameters ---------- df : A data frame from, e.g., get_term_freq_df : pd.DataFrame positive_category : str The positive category name. term_significance : TermSignificance A TermSignificance instance from which to extract p-values. ''' df_pos = df[[positive_category]] df_pos.columns = ['pos'] df_neg = pd.DataFrame(df[[c for c in df.columns if c != positive_category and c.endswith(' freq')]].sum(axis=1)) df_neg.columns = ['neg'] X = df_pos.join(df_neg)[['pos','neg']].values return term_significance.get_p_vals(X)
[ "def", "get_p_vals", "(", "df", ",", "positive_category", ",", "term_significance", ")", ":", "df_pos", "=", "df", "[", "[", "positive_category", "]", "]", "df_pos", ".", "columns", "=", "[", "'pos'", "]", "df_neg", "=", "pd", ".", "DataFrame", "(", "df"...
https://github.com/JasonKessler/scattertext/blob/ef33f06d4c31f9d64b551a7ab86bf157aca82644/scattertext/PValGetter.py#L4-L21
boto/boto
b2a6f08122b2f1b89888d2848e730893595cd001
boto/cloudsearch2/search.py
python
SearchResults.next_page
(self)
Call Cloudsearch to get the next page of search results :rtype: :class:`boto.cloudsearch2.search.SearchResults` :return: the following page of search results
Call Cloudsearch to get the next page of search results
[ "Call", "Cloudsearch", "to", "get", "the", "next", "page", "of", "search", "results" ]
def next_page(self): """Call Cloudsearch to get the next page of search results :rtype: :class:`boto.cloudsearch2.search.SearchResults` :return: the following page of search results """ if self.query.page <= self.num_pages_needed: self.query.start += self.query.real_size self.query.page += 1 return self.search_service(self.query) else: raise StopIteration
[ "def", "next_page", "(", "self", ")", ":", "if", "self", ".", "query", ".", "page", "<=", "self", ".", "num_pages_needed", ":", "self", ".", "query", ".", "start", "+=", "self", ".", "query", ".", "real_size", "self", ".", "query", ".", "page", "+=",...
https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/cloudsearch2/search.py#L62-L73
Jorl17/open-elevation
677f9de1b6c1a10b48028f36e072bf8b6ba19b9e
gdal_interfaces.py
python
GDALTileInterface.read_summary_json
(self)
[]
def read_summary_json(self): with open(self.summary_file) as f: self.all_coords = json.load(f) self._build_index()
[ "def", "read_summary_json", "(", "self", ")", ":", "with", "open", "(", "self", ".", "summary_file", ")", "as", "f", ":", "self", ".", "all_coords", "=", "json", ".", "load", "(", "f", ")", "self", ".", "_build_index", "(", ")" ]
https://github.com/Jorl17/open-elevation/blob/677f9de1b6c1a10b48028f36e072bf8b6ba19b9e/gdal_interfaces.py#L157-L161
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/autogroup.py
python
Autogroup.set_exclude
(self, exclude)
Set the list of classes to exclude in the autogrouping. :param exclude: a list of valid entry point strings (might contain '%' to be used as string to be matched using SQL's ``LIKE`` pattern-making logic), or ``None`` to specify no include list.
Set the list of classes to exclude in the autogrouping.
[ "Set", "the", "list", "of", "classes", "to", "exclude", "in", "the", "autogrouping", "." ]
def set_exclude(self, exclude): """Set the list of classes to exclude in the autogrouping. :param exclude: a list of valid entry point strings (might contain '%' to be used as string to be matched using SQL's ``LIKE`` pattern-making logic), or ``None`` to specify no include list. """ if isinstance(exclude, str): exclude = [exclude] self.validate(exclude) if exclude is not None and self.get_include() is not None: # It's ok to set None, both as a default, or to 'undo' the exclude list raise exceptions.ValidationError('Cannot both specify exclude and include') self._exclude = exclude
[ "def", "set_exclude", "(", "self", ",", "exclude", ")", ":", "if", "isinstance", "(", "exclude", ",", "str", ")", ":", "exclude", "=", "[", "exclude", "]", "self", ".", "validate", "(", "exclude", ")", "if", "exclude", "is", "not", "None", "and", "se...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/autogroup.py#L86-L99
miguelgrinberg/Flask-Migrate
c051a000c1518a71e0a5d045c1f8065b9add5122
src/flask_migrate/__init__.py
python
stamp
(directory=None, revision='head', sql=False, tag=None)
stamp' the revision table with the given revision; don't run any migrations
stamp' the revision table with the given revision; don't run any migrations
[ "stamp", "the", "revision", "table", "with", "the", "given", "revision", ";", "don", "t", "run", "any", "migrations" ]
def stamp(directory=None, revision='head', sql=False, tag=None): """'stamp' the revision table with the given revision; don't run any migrations""" config = current_app.extensions['migrate'].migrate.get_config(directory) command.stamp(config, revision, sql=sql, tag=tag)
[ "def", "stamp", "(", "directory", "=", "None", ",", "revision", "=", "'head'", ",", "sql", "=", "False", ",", "tag", "=", "None", ")", ":", "config", "=", "current_app", ".", "extensions", "[", "'migrate'", "]", ".", "migrate", ".", "get_config", "(", ...
https://github.com/miguelgrinberg/Flask-Migrate/blob/c051a000c1518a71e0a5d045c1f8065b9add5122/src/flask_migrate/__init__.py#L240-L244
mars-project/mars
6afd7ed86db77f29cc9470485698ef192ecc6d33
mars/tensor/base/atleast_3d.py
python
atleast_3d
(*tensors)
return ExecutableTuple(new_tensors)
View inputs as tensors with at least three dimensions. Parameters ---------- tensors1, tensors2, ... : array_like One or more tensor-like sequences. Non-tensor inputs are converted to tensors. Tensors that already have three or more dimensions are preserved. Returns ------- res1, res2, ... : Tensor A tensor, or list of tensors, each with ``a.ndim >= 3``. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D tensor of shape ``(N,)`` becomes a view of shape ``(1, N, 1)``, and a 2-D tensor of shape ``(M, N)`` becomes a view of shape ``(M, N, 1)``. See Also -------- atleast_1d, atleast_2d Examples -------- >>> import mars.tensor as mt >>> mt.atleast_3d(3.0).execute() array([[[ 3.]]]) >>> x = mt.arange(3.0) >>> mt.atleast_3d(x).shape (1, 3, 1) >>> x = mt.arange(12.0).reshape(4,3) >>> mt.atleast_3d(x).shape (4, 3, 1) >>> for arr in mt.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]).execute(): ... print(arr, arr.shape) ... [[[1] [2]]] (1, 2, 1) [[[1] [2]]] (1, 2, 1) [[[1 2]]] (1, 1, 2)
View inputs as tensors with at least three dimensions.
[ "View", "inputs", "as", "tensors", "with", "at", "least", "three", "dimensions", "." ]
def atleast_3d(*tensors): """ View inputs as tensors with at least three dimensions. Parameters ---------- tensors1, tensors2, ... : array_like One or more tensor-like sequences. Non-tensor inputs are converted to tensors. Tensors that already have three or more dimensions are preserved. Returns ------- res1, res2, ... : Tensor A tensor, or list of tensors, each with ``a.ndim >= 3``. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D tensor of shape ``(N,)`` becomes a view of shape ``(1, N, 1)``, and a 2-D tensor of shape ``(M, N)`` becomes a view of shape ``(M, N, 1)``. See Also -------- atleast_1d, atleast_2d Examples -------- >>> import mars.tensor as mt >>> mt.atleast_3d(3.0).execute() array([[[ 3.]]]) >>> x = mt.arange(3.0) >>> mt.atleast_3d(x).shape (1, 3, 1) >>> x = mt.arange(12.0).reshape(4,3) >>> mt.atleast_3d(x).shape (4, 3, 1) >>> for arr in mt.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]).execute(): ... print(arr, arr.shape) ... [[[1] [2]]] (1, 2, 1) [[[1] [2]]] (1, 2, 1) [[[1 2]]] (1, 1, 2) """ new_tensors = [] for x in tensors: x = astensor(x) if x.ndim == 0: x = x[np.newaxis, np.newaxis, np.newaxis] elif x.ndim == 1: x = x[np.newaxis, :, np.newaxis] elif x.ndim == 2: x = x[:, :, None] new_tensors.append(x) if len(new_tensors) == 1: return new_tensors[0] return ExecutableTuple(new_tensors)
[ "def", "atleast_3d", "(", "*", "tensors", ")", ":", "new_tensors", "=", "[", "]", "for", "x", "in", "tensors", ":", "x", "=", "astensor", "(", "x", ")", "if", "x", ".", "ndim", "==", "0", ":", "x", "=", "x", "[", "np", ".", "newaxis", ",", "n...
https://github.com/mars-project/mars/blob/6afd7ed86db77f29cc9470485698ef192ecc6d33/mars/tensor/base/atleast_3d.py#L23-L86
cloudmarker/cloudmarker
0dd2daadfa0203b3d1062e5067b14e4e0f189697
cloudmarker/events/azwebappclientcertevent.py
python
AzWebAppClientCertEvent.eval
(self, record)
Evaluate Azure web app to check if client cert is disabled. Arguments: record (dict): A web app record. Yields: dict: An event record representing a web app with client certificate (mTLS) disabled.
Evaluate Azure web app to check if client cert is disabled.
[ "Evaluate", "Azure", "web", "app", "to", "check", "if", "client", "cert", "is", "disabled", "." ]
def eval(self, record): """Evaluate Azure web app to check if client cert is disabled. Arguments: record (dict): A web app record. Yields: dict: An event record representing a web app with client certificate (mTLS) disabled. """ com = record.get('com', {}) if com is None: return if com.get('cloud_type') != 'azure': return ext = record.get('ext', {}) if ext is None: return if ext.get('record_type') != 'web_app_config': return if ext.get('client_cert_enabled'): return yield from _get_azure_web_app_client_cert_event(com, ext)
[ "def", "eval", "(", "self", ",", "record", ")", ":", "com", "=", "record", ".", "get", "(", "'com'", ",", "{", "}", ")", "if", "com", "is", "None", ":", "return", "if", "com", ".", "get", "(", "'cloud_type'", ")", "!=", "'azure'", ":", "return", ...
https://github.com/cloudmarker/cloudmarker/blob/0dd2daadfa0203b3d1062e5067b14e4e0f189697/cloudmarker/events/azwebappclientcertevent.py#L23-L51
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/backends/backend_cairo.py
python
_cairo_font_args_from_font_prop
(prop)
return name, slant, weight
Convert a `.FontProperties` or a `.FontEntry` to arguments that can be passed to `.Context.select_font_face`.
Convert a `.FontProperties` or a `.FontEntry` to arguments that can be passed to `.Context.select_font_face`.
[ "Convert", "a", ".", "FontProperties", "or", "a", ".", "FontEntry", "to", "arguments", "that", "can", "be", "passed", "to", ".", "Context", ".", "select_font_face", "." ]
def _cairo_font_args_from_font_prop(prop): """ Convert a `.FontProperties` or a `.FontEntry` to arguments that can be passed to `.Context.select_font_face`. """ def attr(field): try: return getattr(prop, f"get_{field}")() except AttributeError: return getattr(prop, field) name = attr("name") slant = getattr(cairo, f"FONT_SLANT_{attr('style').upper()}") weight = attr("weight") weight = (cairo.FONT_WEIGHT_NORMAL if font_manager.weight_dict.get(weight, weight) < 550 else cairo.FONT_WEIGHT_BOLD) return name, slant, weight
[ "def", "_cairo_font_args_from_font_prop", "(", "prop", ")", ":", "def", "attr", "(", "field", ")", ":", "try", ":", "return", "getattr", "(", "prop", ",", "f\"get_{field}\"", ")", "(", ")", "except", "AttributeError", ":", "return", "getattr", "(", "prop", ...
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/backends/backend_cairo.py#L75-L92
mozilla/addons-server
cbfb29e5be99539c30248d70b93bb15e1c1bc9d7
src/olympia/scanners/tasks.py
python
_run_scanner_for_url
(scanner_result, url, scanner, api_url, api_key)
Inner function to run a scanner on a particular URL via RPC and add results to the given scanner_result. The caller is responsible for saving the scanner_result to the database.
Inner function to run a scanner on a particular URL via RPC and add results to the given scanner_result. The caller is responsible for saving the scanner_result to the database.
[ "Inner", "function", "to", "run", "a", "scanner", "on", "a", "particular", "URL", "via", "RPC", "and", "add", "results", "to", "the", "given", "scanner_result", ".", "The", "caller", "is", "responsible", "for", "saving", "the", "scanner_result", "to", "the",...
def _run_scanner_for_url(scanner_result, url, scanner, api_url, api_key): """ Inner function to run a scanner on a particular URL via RPC and add results to the given scanner_result. The caller is responsible for saving the scanner_result to the database. """ with requests.Session() as http: adapter = make_adapter_with_retry() http.mount('http://', adapter) http.mount('https://', adapter) json_payload = { 'api_key': api_key, 'download_url': url, } response = http.post( url=api_url, json=json_payload, timeout=settings.SCANNER_TIMEOUT ) try: data = response.json() except ValueError: # Log the response body when JSON decoding has failed. raise ValueError(response.text) if response.status_code != 200 or 'error' in data: raise ValueError(data) scanner_result.results = data
[ "def", "_run_scanner_for_url", "(", "scanner_result", ",", "url", ",", "scanner", ",", "api_url", ",", "api_key", ")", ":", "with", "requests", ".", "Session", "(", ")", "as", "http", ":", "adapter", "=", "make_adapter_with_retry", "(", ")", "http", ".", "...
https://github.com/mozilla/addons-server/blob/cbfb29e5be99539c30248d70b93bb15e1c1bc9d7/src/olympia/scanners/tasks.py#L107-L135
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/visualize/owviolinplot.py
python
ViolinPlot.order_items
(self)
[]
def order_items(self): assert self.__group_var is not None indices = self._sorted_group_indices for i, index in enumerate(indices): violin: ViolinItem = self.__violin_items[index] box: BoxItem = self.__box_items[index] median: MedianItem = self.__median_items[index] strip: StripItem = self.__strip_items[index] sel_rect: QGraphicsRectItem = self.__selection_rects[index] if self.__orientation == Qt.Vertical: x = i * self._max_item_width violin.setX(x) box.setX(x) median.setX(x) strip.setX(x) sel_rect.setX(x) else: y = - i * self._max_item_width violin.setY(y) box.setY(y) median.setY(y) strip.setY(y) sel_rect.setY(y) sign = 1 if self.__orientation == Qt.Vertical else -1 side = "bottom" if self.__orientation == Qt.Vertical else "left" ticks = [[(i * self._max_item_width * sign, self.__group_var.values[index]) for i, index in enumerate(indices)]] self.getAxis(side).setTicks(ticks)
[ "def", "order_items", "(", "self", ")", ":", "assert", "self", ".", "__group_var", "is", "not", "None", "indices", "=", "self", ".", "_sorted_group_indices", "for", "i", ",", "index", "in", "enumerate", "(", "indices", ")", ":", "violin", ":", "ViolinItem"...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/owviolinplot.py#L495-L527
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/gettext.py
python
NullTranslations.add_fallback
(self, fallback)
[]
def add_fallback(self, fallback): if self._fallback: self._fallback.add_fallback(fallback) else: self._fallback = fallback
[ "def", "add_fallback", "(", "self", ",", "fallback", ")", ":", "if", "self", ".", "_fallback", ":", "self", ".", "_fallback", ".", "add_fallback", "(", "fallback", ")", "else", ":", "self", ".", "_fallback", "=", "fallback" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/gettext.py#L260-L264
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/series.py
python
Series.to_frame
(self, name=None)
return df
Convert Series to DataFrame. Parameters ---------- name : object, default None The passed name should substitute for the series name (if it has one). Returns ------- data_frame : DataFrame
Convert Series to DataFrame.
[ "Convert", "Series", "to", "DataFrame", "." ]
def to_frame(self, name=None): """ Convert Series to DataFrame. Parameters ---------- name : object, default None The passed name should substitute for the series name (if it has one). Returns ------- data_frame : DataFrame """ if name is None: df = self._constructor_expanddim(self) else: df = self._constructor_expanddim({name: self}) return df
[ "def", "to_frame", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "df", "=", "self", ".", "_constructor_expanddim", "(", "self", ")", "else", ":", "df", "=", "self", ".", "_constructor_expanddim", "(", "{", "name", ...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/series.py#L1497-L1516
matsui528/nanopq
4c1d724494a71f9736b15928a8c03b0ba13ffd19
nanopq/pq.py
python
PQ.decode
(self, codes)
return vecs
Given PQ-codes, reconstruct original D-dimensional vectors approximately by fetching the codewords. Args: codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype. Each row is a PQ-code Returns: np.ndarray: Reconstructed vectors with shape=(N, D) and dtype=np.float32
Given PQ-codes, reconstruct original D-dimensional vectors approximately by fetching the codewords.
[ "Given", "PQ", "-", "codes", "reconstruct", "original", "D", "-", "dimensional", "vectors", "approximately", "by", "fetching", "the", "codewords", "." ]
def decode(self, codes): """Given PQ-codes, reconstruct original D-dimensional vectors approximately by fetching the codewords. Args: codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype. Each row is a PQ-code Returns: np.ndarray: Reconstructed vectors with shape=(N, D) and dtype=np.float32 """ assert codes.ndim == 2 N, M = codes.shape assert M == self.M assert codes.dtype == self.code_dtype vecs = np.empty((N, self.Ds * self.M), dtype=np.float32) for m in range(self.M): vecs[:, m * self.Ds : (m + 1) * self.Ds] = self.codewords[m][codes[:, m], :] return vecs
[ "def", "decode", "(", "self", ",", "codes", ")", ":", "assert", "codes", ".", "ndim", "==", "2", "N", ",", "M", "=", "codes", ".", "shape", "assert", "M", "==", "self", ".", "M", "assert", "codes", ".", "dtype", "==", "self", ".", "code_dtype", "...
https://github.com/matsui528/nanopq/blob/4c1d724494a71f9736b15928a8c03b0ba13ffd19/nanopq/pq.py#L121-L142
salesforce/cloudsplaining
c932ea61de7b0f12d77bb4144fee343245d68d3f
cloudsplaining/scan/user_details.py
python
UserDetailList.get_all_iam_statements_for_user
( self, name: str )
return None
Returns a list of all StatementDetail objects across all the policies assigned to the user
Returns a list of all StatementDetail objects across all the policies assigned to the user
[ "Returns", "a", "list", "of", "all", "StatementDetail", "objects", "across", "all", "the", "policies", "assigned", "to", "the", "user" ]
def get_all_iam_statements_for_user( self, name: str ) -> Optional[List[StatementDetail]]: """Returns a list of all StatementDetail objects across all the policies assigned to the user""" for user_detail in self.users: if user_detail.user_name == name: return user_detail.all_iam_statements return None
[ "def", "get_all_iam_statements_for_user", "(", "self", ",", "name", ":", "str", ")", "->", "Optional", "[", "List", "[", "StatementDetail", "]", "]", ":", "for", "user_detail", "in", "self", ".", "users", ":", "if", "user_detail", ".", "user_name", "==", "...
https://github.com/salesforce/cloudsplaining/blob/c932ea61de7b0f12d77bb4144fee343245d68d3f/cloudsplaining/scan/user_details.py#L47-L54
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/mhlib.py
python
Folder.parsesequence
(self, seq)
Parse an MH sequence specification into a message list. Attempt to mimic mh-sequence(5) as close as possible. Also attempt to mimic observed behavior regarding which conditions cause which error messages.
Parse an MH sequence specification into a message list. Attempt to mimic mh-sequence(5) as close as possible. Also attempt to mimic observed behavior regarding which conditions cause which error messages.
[ "Parse", "an", "MH", "sequence", "specification", "into", "a", "message", "list", ".", "Attempt", "to", "mimic", "mh", "-", "sequence", "(", "5", ")", "as", "close", "as", "possible", ".", "Also", "attempt", "to", "mimic", "observed", "behavior", "regardin...
def parsesequence(self, seq): """Parse an MH sequence specification into a message list. Attempt to mimic mh-sequence(5) as close as possible. Also attempt to mimic observed behavior regarding which conditions cause which error messages.""" # XXX Still not complete (see mh-format(5)). # Missing are: # - 'prev', 'next' as count # - Sequence-Negation option all = self.listmessages() # Observed behavior: test for empty folder is done first if not all: raise Error, "no messages in %s" % self.name # Common case first: all is frequently the default if seq == 'all': return all # Test for X:Y before X-Y because 'seq:-n' matches both i = seq.find(':') if i >= 0: head, dir, tail = seq[:i], '', seq[i+1:] if tail[:1] in '-+': dir, tail = tail[:1], tail[1:] if not isnumeric(tail): raise Error, "bad message list %s" % seq try: count = int(tail) except (ValueError, OverflowError): # Can't use sys.maxint because of i+count below count = len(all) try: anchor = self._parseindex(head, all) except Error, msg: seqs = self.getsequences() if not head in seqs: if not msg: msg = "bad message list %s" % seq raise Error, msg, sys.exc_info()[2] msgs = seqs[head] if not msgs: raise Error, "sequence %s empty" % head if dir == '-': return msgs[-count:] else: return msgs[:count] else: if not dir: if head in ('prev', 'last'): dir = '-' if dir == '-': i = bisect(all, anchor) return all[max(0, i-count):i] else: i = bisect(all, anchor-1) return all[i:i+count] # Test for X-Y next i = seq.find('-') if i >= 0: begin = self._parseindex(seq[:i], all) end = self._parseindex(seq[i+1:], all) i = bisect(all, begin-1) j = bisect(all, end) r = all[i:j] if not r: raise Error, "bad message list %s" % seq return r # Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence try: n = self._parseindex(seq, all) except Error, msg: seqs = self.getsequences() if not seq in seqs: if not msg: msg = "bad message list %s" % seq raise Error, msg return seqs[seq] else: if n not in all: if isnumeric(seq): raise Error, "message %d doesn't exist" % n else: raise Error, "no %s message" % seq else: return [n]
[ "def", "parsesequence", "(", "self", ",", "seq", ")", ":", "# XXX Still not complete (see mh-format(5)).", "# Missing are:", "# - 'prev', 'next' as count", "# - Sequence-Negation option", "all", "=", "self", ".", "listmessages", "(", ")", "# Observed behavior: test for empty fo...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/mhlib.py#L346-L428
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_adm_registry.py
python
DeploymentConfig.exists_volume_mount
(self, volume_mount)
return volume_mount_found
return whether a volume mount exists
return whether a volume mount exists
[ "return", "whether", "a", "volume", "mount", "exists" ]
def exists_volume_mount(self, volume_mount): ''' return whether a volume mount exists ''' exist_volume_mounts = self.get_volume_mounts() if not exist_volume_mounts: return False volume_mount_found = False for exist_volume_mount in exist_volume_mounts: if exist_volume_mount['name'] == volume_mount['name']: volume_mount_found = True break return volume_mount_found
[ "def", "exists_volume_mount", "(", "self", ",", "volume_mount", ")", ":", "exist_volume_mounts", "=", "self", ".", "get_volume_mounts", "(", ")", "if", "not", "exist_volume_mounts", ":", "return", "False", "volume_mount_found", "=", "False", "for", "exist_volume_mou...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_adm_registry.py#L1749-L1762
fofix/fofix
7730d1503c66562b901f62b33a5bd46c3d5e5c34
fofix/core/Image.py
python
drawImage
(image, scale=(1.0, -1.0), coord=(0, 0), rot=0, color=(1, 1, 1, 1), rect=(0, 1, 0, 1), stretched=0, fit=CENTER, alignment=CENTER, valignment=CENTER)
return True
Draws the image/surface to screen :param image: The OpenGL surface :param scale: Scale factor (between 0.0 and 1.0, second value must be negative due to texture flipping) :param coord: Where the image will be translated to on the screen :param rot: How many degrees it will be rotated :param color: The color of the image (R, G, B, A) (values are between 0.0 and 1.0, Alpha is 1.0 by default) :param rect: The surface rectangle, this is used for cropping the texture. Any other values will have the image maintain its size passed by scale :param alignment: Adjusts the texture so the coordinate for x-axis placement can either be on the left side (0), center point (1), or right(2) side of the image :param valignment: Adjusts the texture so the coordinate for y-axis placement can either be on the bottom side (0), center point (1), or top(2) side of the image :rtype: boolean
Draws the image/surface to screen
[ "Draws", "the", "image", "/", "surface", "to", "screen" ]
def drawImage(image, scale=(1.0, -1.0), coord=(0, 0), rot=0, color=(1, 1, 1, 1), rect=(0, 1, 0, 1), stretched=0, fit=CENTER, alignment=CENTER, valignment=CENTER): """ Draws the image/surface to screen :param image: The OpenGL surface :param scale: Scale factor (between 0.0 and 1.0, second value must be negative due to texture flipping) :param coord: Where the image will be translated to on the screen :param rot: How many degrees it will be rotated :param color: The color of the image (R, G, B, A) (values are between 0.0 and 1.0, Alpha is 1.0 by default) :param rect: The surface rectangle, this is used for cropping the texture. Any other values will have the image maintain its size passed by scale :param alignment: Adjusts the texture so the coordinate for x-axis placement can either be on the left side (0), center point (1), or right(2) side of the image :param valignment: Adjusts the texture so the coordinate for y-axis placement can either be on the bottom side (0), center point (1), or top(2) side of the image :rtype: boolean """ if not isinstance(image, ImgDrawing): return False image.setRect(rect) image.setScale(scale[0], scale[1], stretched) image.setPosition(coord[0], coord[1], fit) image.setAlignment(alignment) image.setVAlignment(valignment) image.setAngle(rot) image.setColor(color) image.draw() return True
[ "def", "drawImage", "(", "image", ",", "scale", "=", "(", "1.0", ",", "-", "1.0", ")", ",", "coord", "=", "(", "0", ",", "0", ")", ",", "rot", "=", "0", ",", "color", "=", "(", "1", ",", "1", ",", "1", ",", "1", ")", ",", "rect", "=", "...
https://github.com/fofix/fofix/blob/7730d1503c66562b901f62b33a5bd46c3d5e5c34/fofix/core/Image.py#L65-L98
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/ext/ndb/context.py
python
Context._use_memcache
(self, key, options=None)
return flag
Return whether to use memcache for this key. Args: key: Key instance. options: ContextOptions instance, or None. Returns: True if the key should be cached in memcache, False otherwise.
Return whether to use memcache for this key.
[ "Return", "whether", "to", "use", "memcache", "for", "this", "key", "." ]
def _use_memcache(self, key, options=None): """Return whether to use memcache for this key. Args: key: Key instance. options: ContextOptions instance, or None. Returns: True if the key should be cached in memcache, False otherwise. """ flag = ContextOptions.use_memcache(options) if flag is None: flag = self._memcache_policy(key) if flag is None: flag = ContextOptions.use_memcache(self._conn.config) if flag is None: flag = True return flag
[ "def", "_use_memcache", "(", "self", ",", "key", ",", "options", "=", "None", ")", ":", "flag", "=", "ContextOptions", ".", "use_memcache", "(", "options", ")", "if", "flag", "is", "None", ":", "flag", "=", "self", ".", "_memcache_policy", "(", "key", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/ndb/context.py#L494-L511
elimintz/justpy
42275e9c6e00373f09affd7d781a278383171807
justpy/chartcomponents.py
python
HighCharts.select_point
(self, point_list, websocket)
return True
point_list is list of of dictionaries whose keys are: 'id': the chart id 'series': the series index 'point': the point index Values are all integers Example: {'id': chart_id, 'series': msg.series_index, 'point': msg.point_index}
point_list is list of of dictionaries whose keys are: 'id': the chart id 'series': the series index 'point': the point index Values are all integers Example: {'id': chart_id, 'series': msg.series_index, 'point': msg.point_index}
[ "point_list", "is", "list", "of", "of", "dictionaries", "whose", "keys", "are", ":", "id", ":", "the", "chart", "id", "series", ":", "the", "series", "index", "point", ":", "the", "point", "index", "Values", "are", "all", "integers", "Example", ":", "{",...
async def select_point(self, point_list, websocket): """ point_list is list of of dictionaries whose keys are: 'id': the chart id 'series': the series index 'point': the point index Values are all integers Example: {'id': chart_id, 'series': msg.series_index, 'point': msg.point_index} """ await websocket.send_json({'type': 'select_point', 'data': point_list}) # Return True not None so that the page does not update return True
[ "async", "def", "select_point", "(", "self", ",", "point_list", ",", "websocket", ")", ":", "await", "websocket", ".", "send_json", "(", "{", "'type'", ":", "'select_point'", ",", "'data'", ":", "point_list", "}", ")", "# Return True not None so that the page does...
https://github.com/elimintz/justpy/blob/42275e9c6e00373f09affd7d781a278383171807/justpy/chartcomponents.py#L114-L126
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/video/v1/room/__init__.py
python
RoomPage.get_instance
(self, payload)
return RoomInstance(self._version, payload, )
Build an instance of RoomInstance :param dict payload: Payload response from the API :returns: twilio.rest.video.v1.room.RoomInstance :rtype: twilio.rest.video.v1.room.RoomInstance
Build an instance of RoomInstance
[ "Build", "an", "instance", "of", "RoomInstance" ]
def get_instance(self, payload): """ Build an instance of RoomInstance :param dict payload: Payload response from the API :returns: twilio.rest.video.v1.room.RoomInstance :rtype: twilio.rest.video.v1.room.RoomInstance """ return RoomInstance(self._version, payload, )
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "RoomInstance", "(", "self", ".", "_version", ",", "payload", ",", ")" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/video/v1/room/__init__.py#L253-L262
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/backends/sqlalchemy/migrations/versions/b8b23ddefad4_dbgroup_name_to_label_type_to_type_string.py
python
upgrade
()
The upgrade migration actions.
The upgrade migration actions.
[ "The", "upgrade", "migration", "actions", "." ]
def upgrade(): """The upgrade migration actions.""" # dropping op.drop_constraint('db_dbgroup_name_type_key', 'db_dbgroup') op.drop_index('ix_db_dbgroup_name', 'db_dbgroup') op.drop_index('ix_db_dbgroup_type', 'db_dbgroup') # renaming op.alter_column('db_dbgroup', 'name', new_column_name='label') op.alter_column('db_dbgroup', 'type', new_column_name='type_string') # creating op.create_unique_constraint('db_dbgroup_label_type_string_key', 'db_dbgroup', ['label', 'type_string']) op.create_index('ix_db_dbgroup_label', 'db_dbgroup', ['label']) op.create_index('ix_db_dbgroup_type_string', 'db_dbgroup', ['type_string'])
[ "def", "upgrade", "(", ")", ":", "# dropping", "op", ".", "drop_constraint", "(", "'db_dbgroup_name_type_key'", ",", "'db_dbgroup'", ")", "op", ".", "drop_index", "(", "'ix_db_dbgroup_name'", ",", "'db_dbgroup'", ")", "op", ".", "drop_index", "(", "'ix_db_dbgroup_...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/backends/sqlalchemy/migrations/versions/b8b23ddefad4_dbgroup_name_to_label_type_to_type_string.py#L28-L42
napari/napari
dbf4158e801fa7a429de8ef1cdee73bf6d64c61e
napari/utils/perf/_config.py
python
_patch_perf_timer
(parent, callable: str, label: str)
Patches the callable to run it inside a perf_timer. Parameters ---------- parent The module or class that contains the callable. callable : str The name of the callable (function or method). label : str The <function> or <class>.<method> we are patching.
Patches the callable to run it inside a perf_timer.
[ "Patches", "the", "callable", "to", "run", "it", "inside", "a", "perf_timer", "." ]
def _patch_perf_timer(parent, callable: str, label: str) -> None: """Patches the callable to run it inside a perf_timer. Parameters ---------- parent The module or class that contains the callable. callable : str The name of the callable (function or method). label : str The <function> or <class>.<method> we are patching. """ @wrapt.patch_function_wrapper(parent, callable) def perf_time_callable(wrapped, instance, args, kwargs): with perf_timer(f"{label}"): return wrapped(*args, **kwargs)
[ "def", "_patch_perf_timer", "(", "parent", ",", "callable", ":", "str", ",", "label", ":", "str", ")", "->", "None", ":", "@", "wrapt", ".", "patch_function_wrapper", "(", "parent", ",", "callable", ")", "def", "perf_time_callable", "(", "wrapped", ",", "i...
https://github.com/napari/napari/blob/dbf4158e801fa7a429de8ef1cdee73bf6d64c61e/napari/utils/perf/_config.py#L24-L40
deanishe/zothero
5b057ef080ee730d82d5dd15e064d2a4730c2b11
src/lib/workflow/workflow.py
python
Workflow.data_serializer
(self, serializer_name)
Set the default cache serialization format. .. versionadded:: 1.8 This serializer is used by :meth:`store_data()` and :meth:`stored_data()` The specified serializer must already by registered with the :class:`SerializerManager` at `~workflow.workflow.manager`, otherwise a :class:`ValueError` will be raised. :param serializer_name: Name of serializer to use by default.
Set the default cache serialization format.
[ "Set", "the", "default", "cache", "serialization", "format", "." ]
def data_serializer(self, serializer_name): """Set the default cache serialization format. .. versionadded:: 1.8 This serializer is used by :meth:`store_data()` and :meth:`stored_data()` The specified serializer must already by registered with the :class:`SerializerManager` at `~workflow.workflow.manager`, otherwise a :class:`ValueError` will be raised. :param serializer_name: Name of serializer to use by default. """ if manager.serializer(serializer_name) is None: raise ValueError( 'Unknown serializer : `{0}`. Register your serializer ' 'with `manager` first.'.format(serializer_name)) self.logger.debug('default data serializer: %s', serializer_name) self._data_serializer = serializer_name
[ "def", "data_serializer", "(", "self", ",", "serializer_name", ")", ":", "if", "manager", ".", "serializer", "(", "serializer_name", ")", "is", "None", ":", "raise", "ValueError", "(", "'Unknown serializer : `{0}`. Register your serializer '", "'with `manager` first.'", ...
https://github.com/deanishe/zothero/blob/5b057ef080ee730d82d5dd15e064d2a4730c2b11/src/lib/workflow/workflow.py#L1534-L1556
wummel/linkchecker
c2ce810c3fb00b895a841a7be6b2e78c64e7b042
linkcheck/HtmlParser/htmllib.py
python
HtmlPrettyPrinter.comment
(self, data)
Print HTML comment. @param data: the comment @type data: string @return: None
Print HTML comment.
[ "Print", "HTML", "comment", "." ]
def comment (self, data): """ Print HTML comment. @param data: the comment @type data: string @return: None """ data = data.encode(self.encoding, "ignore") self.fd.write("<!--%s-->" % data)
[ "def", "comment", "(", "self", ",", "data", ")", ":", "data", "=", "data", ".", "encode", "(", "self", ".", "encoding", ",", "\"ignore\"", ")", "self", ".", "fd", ".", "write", "(", "\"<!--%s-->\"", "%", "data", ")" ]
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/HtmlParser/htmllib.py#L79-L88
thenetcircle/dino
1047c3458e91a1b4189e9f48f1393b3a68a935b3
dino/storage/cassandra_interface.py
python
IDriver.msgs_select
(self, to_user_id: str)
find all messages sent to a user id/room id :param to_user_id: either a user id or room uuid :return: all messages to this user/room
find all messages sent to a user id/room id
[ "find", "all", "messages", "sent", "to", "a", "user", "id", "/", "room", "id" ]
def msgs_select(self, to_user_id: str): """ find all messages sent to a user id/room id :param to_user_id: either a user id or room uuid :return: all messages to this user/room """
[ "def", "msgs_select", "(", "self", ",", "to_user_id", ":", "str", ")", ":" ]
https://github.com/thenetcircle/dino/blob/1047c3458e91a1b4189e9f48f1393b3a68a935b3/dino/storage/cassandra_interface.py#L60-L66
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/Queue.py
python
Queue.put
(self, item, block=True, timeout=None)
Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case).
Put an item into the queue.
[ "Put", "an", "item", "into", "the", "queue", "." ]
def put(self, item, block=True, timeout=None): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case). """ self.not_full.acquire() try: if self.maxsize > 0: if not block: if self._qsize() == self.maxsize: raise Full elif timeout is None: while self._qsize() == self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a positive number") else: endtime = _time() + timeout while self._qsize() == self.maxsize: remaining = endtime - _time() if remaining <= 0.0: raise Full self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 self.not_empty.notify() finally: self.not_full.release()
[ "def", "put", "(", "self", ",", "item", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "self", ".", "not_full", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "maxsize", ">", "0", ":", "if", "not", "block", ":", "if...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/Queue.py#L107-L140
quantopian/pgcontents
51f8febcf6ece4e88b047768b9ce18553162d63c
pgcontents/pgmanager.py
python
PostgresContentsManager._directory_model_from_db
(self, record, content)
return model
Build a directory model from database directory record.
Build a directory model from database directory record.
[ "Build", "a", "directory", "model", "from", "database", "directory", "record", "." ]
def _directory_model_from_db(self, record, content): """ Build a directory model from database directory record. """ model = base_directory_model(to_api_path(record['name'])) if content: model['format'] = 'json' model['content'] = list( chain( self._convert_file_records(record['files']), ( self._directory_model_from_db(subdir, False) for subdir in record['subdirs'] ), ) ) return model
[ "def", "_directory_model_from_db", "(", "self", ",", "record", ",", "content", ")", ":", "model", "=", "base_directory_model", "(", "to_api_path", "(", "record", "[", "'name'", "]", ")", ")", "if", "content", ":", "model", "[", "'format'", "]", "=", "'json...
https://github.com/quantopian/pgcontents/blob/51f8febcf6ece4e88b047768b9ce18553162d63c/pgcontents/pgmanager.py#L246-L262
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/tomlkit/items.py
python
Float.__init__
(self, _, trivia, raw)
[]
def __init__(self, _, trivia, raw): # type: (float, Trivia, str) -> None super(Float, self).__init__(trivia) self._raw = raw self._sign = False if re.match(r"^[+\-].+$", raw): self._sign = True
[ "def", "__init__", "(", "self", ",", "_", ",", "trivia", ",", "raw", ")", ":", "# type: (float, Trivia, str) -> None", "super", "(", "Float", ",", "self", ")", ".", "__init__", "(", "trivia", ")", "self", ".", "_raw", "=", "raw", "self", ".", "_sign", ...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/tomlkit/items.py#L453-L460
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/cuda/simulator/cudadrv/nvvm.py
python
get_supported_ccs
()
return ()
[]
def get_supported_ccs(): return ()
[ "def", "get_supported_ccs", "(", ")", ":", "return", "(", ")" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cuda/simulator/cudadrv/nvvm.py#L29-L30
BigBrotherBot/big-brother-bot
848823c71413c86e7f1ff9584f43e08d40a7f2c0
b3/fake.py
python
FakeClient.__init__
(self, console, **kwargs)
Object constructor. :param console: The console implementation
Object constructor. :param console: The console implementation
[ "Object", "constructor", ".", ":", "param", "console", ":", "The", "console", "implementation" ]
def __init__(self, console, **kwargs): """ Object constructor. :param console: The console implementation """ self.console = console self.message_history = [] # this allows unittests to check if a message was sent to the client b3.clients.Client.__init__(self, **kwargs)
[ "def", "__init__", "(", "self", ",", "console", ",", "*", "*", "kwargs", ")", ":", "self", ".", "console", "=", "console", "self", ".", "message_history", "=", "[", "]", "# this allows unittests to check if a message was sent to the client", "b3", ".", "clients", ...
https://github.com/BigBrotherBot/big-brother-bot/blob/848823c71413c86e7f1ff9584f43e08d40a7f2c0/b3/fake.py#L265-L272
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-modules/twisted/twisted/news/nntp.py
python
NNTPClient.gotXHeader
(self, headers)
Override for notification when getXHeader() action is successful
Override for notification when getXHeader() action is successful
[ "Override", "for", "notification", "when", "getXHeader", "()", "action", "is", "successful" ]
def gotXHeader(self, headers): "Override for notification when getXHeader() action is successful"
[ "def", "gotXHeader", "(", "self", ",", "headers", ")", ":" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/news/nntp.py#L166-L167
zhreshold/mxnet-ssd
821a1c5049679f798976c8bf58b460ffaa098458
evaluate/evaluate_net.py
python
evaluate_net
(net, path_imgrec, num_classes, mean_pixels, data_shape, model_prefix, epoch, ctx=mx.cpu(), batch_size=1, path_imglist="", nms_thresh=0.45, force_nms=False, ovp_thresh=0.5, use_difficult=False, class_names=None, voc07_metric=False, frequent=20)
evalute network given validation record file Parameters: ---------- net : str or None Network name or use None to load from json without modifying path_imgrec : str path to the record validation file path_imglist : str path to the list file to replace labels in record file, optional num_classes : int number of classes, not including background mean_pixels : tuple (mean_r, mean_g, mean_b) data_shape : tuple or int (3, height, width) or height/width model_prefix : str model prefix of saved checkpoint epoch : int load model epoch ctx : mx.ctx mx.gpu() or mx.cpu() batch_size : int validation batch size nms_thresh : float non-maximum suppression threshold force_nms : boolean whether suppress different class objects ovp_thresh : float AP overlap threshold for true/false postives use_difficult : boolean whether to use difficult objects in evaluation if applicable class_names : comma separated str class names in string, must correspond to num_classes if set voc07_metric : boolean whether to use 11-point evluation as in VOC07 competition frequent : int frequency to print out validation status
evalute network given validation record file
[ "evalute", "network", "given", "validation", "record", "file" ]
def evaluate_net(net, path_imgrec, num_classes, mean_pixels, data_shape, model_prefix, epoch, ctx=mx.cpu(), batch_size=1, path_imglist="", nms_thresh=0.45, force_nms=False, ovp_thresh=0.5, use_difficult=False, class_names=None, voc07_metric=False, frequent=20): """ evalute network given validation record file Parameters: ---------- net : str or None Network name or use None to load from json without modifying path_imgrec : str path to the record validation file path_imglist : str path to the list file to replace labels in record file, optional num_classes : int number of classes, not including background mean_pixels : tuple (mean_r, mean_g, mean_b) data_shape : tuple or int (3, height, width) or height/width model_prefix : str model prefix of saved checkpoint epoch : int load model epoch ctx : mx.ctx mx.gpu() or mx.cpu() batch_size : int validation batch size nms_thresh : float non-maximum suppression threshold force_nms : boolean whether suppress different class objects ovp_thresh : float AP overlap threshold for true/false postives use_difficult : boolean whether to use difficult objects in evaluation if applicable class_names : comma separated str class names in string, must correspond to num_classes if set voc07_metric : boolean whether to use 11-point evluation as in VOC07 competition frequent : int frequency to print out validation status """ # set up logger logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) # args if isinstance(data_shape, int): data_shape = (3, data_shape, data_shape) assert len(data_shape) == 3 and data_shape[0] == 3 #model_prefix += '_' + str(data_shape[1]) # iterator eval_iter = DetRecordIter(path_imgrec, batch_size, data_shape, path_imglist=path_imglist, **cfg.valid) # model params load_net, args, auxs = mx.model.load_checkpoint(model_prefix, epoch) # network if net is None: net = load_net else: net = get_symbol(net, data_shape[1], num_classes=num_classes, nms_thresh=nms_thresh, force_suppress=force_nms) if not 'label' in net.list_arguments(): label = mx.sym.Variable(name='label') net = mx.sym.Group([net, label]) # init module mod = mx.mod.Module(net, label_names=('label',), logger=logger, context=ctx, fixed_param_names=net.list_arguments()) mod.bind(data_shapes=eval_iter.provide_data, label_shapes=eval_iter.provide_label) mod.set_params(args, auxs, allow_missing=False, force_init=True) # run evaluation if voc07_metric: metric = VOC07MApMetric(ovp_thresh, use_difficult, class_names, roc_output_path=os.path.join(os.path.dirname(model_prefix), 'roc')) else: metric = MApMetric(ovp_thresh, use_difficult, class_names, roc_output_path=os.path.join(os.path.dirname(model_prefix), 'roc')) results = mod.score(eval_iter, metric, num_batch=None, batch_end_callback=mx.callback.Speedometer(batch_size, frequent=frequent, auto_reset=False)) for k, v in results: print("{}: {}".format(k, v))
[ "def", "evaluate_net", "(", "net", ",", "path_imgrec", ",", "num_classes", ",", "mean_pixels", ",", "data_shape", ",", "model_prefix", ",", "epoch", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "batch_size", "=", "1", ",", "path_imglist", "=", "\"\"...
https://github.com/zhreshold/mxnet-ssd/blob/821a1c5049679f798976c8bf58b460ffaa098458/evaluate/evaluate_net.py#L12-L101
reddit-archive/reddit
753b17407e9a9dca09558526805922de24133d53
r2/r2/models/ip.py
python
set_account_ip
(account_id, ip, date=None)
Set an IP address as having accessed an account. Updates all underlying datastores.
Set an IP address as having accessed an account.
[ "Set", "an", "IP", "address", "as", "having", "accessed", "an", "account", "." ]
def set_account_ip(account_id, ip, date=None): """Set an IP address as having accessed an account. Updates all underlying datastores. """ # don't store private IPs, send event + string so we can investigate this if ip_address(ip).is_private: g.stats.simple_event('ip.private_ip_storage_prevented') g.stats.count_string('private_ip_storage_prevented', ip) return if date is None: date = datetime.datetime.now(g.tz) m = Mutator(CONNECTION_POOL) m.insert(IPsByAccount._cf, str(account_id), {date: ip}, ttl=CF_TTL) m.insert(AccountsByIP._cf, ip, {date: str(account_id)}, ttl=CF_TTL) m.send()
[ "def", "set_account_ip", "(", "account_id", ",", "ip", ",", "date", "=", "None", ")", ":", "# don't store private IPs, send event + string so we can investigate this", "if", "ip_address", "(", "ip", ")", ".", "is_private", ":", "g", ".", "stats", ".", "simple_event"...
https://github.com/reddit-archive/reddit/blob/753b17407e9a9dca09558526805922de24133d53/r2/r2/models/ip.py#L135-L151
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
rpython/rlib/rposix_stat.py
python
make_stat_result
(tup)
return os.stat_result(positional, kwds)
Turn a tuple into an os.stat_result object.
Turn a tuple into an os.stat_result object.
[ "Turn", "a", "tuple", "into", "an", "os", ".", "stat_result", "object", "." ]
def make_stat_result(tup): """Turn a tuple into an os.stat_result object.""" assert len(tup) == len(STAT_FIELDS) assert float not in [type(x) for x in tup] positional = [] for i in range(N_INDEXABLE_FIELDS): name, TYPE = STAT_FIELDS[i] value = lltype.cast_primitive(TYPE, tup[i]) positional.append(value) kwds = {} if sys.platform == 'win32': kwds['st_atime'] = tup[7] + 1e-9 * tup[-5] kwds['st_mtime'] = tup[8] + 1e-9 * tup[-4] kwds['st_ctime'] = tup[9] + 1e-9 * tup[-3] kwds['st_file_attributes'] = tup[-2] kwds['st_reparse_tag'] = tup[-1] else: kwds['st_atime'] = tup[7] + 1e-9 * tup[-3] kwds['st_mtime'] = tup[8] + 1e-9 * tup[-2] kwds['st_ctime'] = tup[9] + 1e-9 * tup[-1] for value, (name, TYPE) in zip(tup, STAT_FIELDS)[N_INDEXABLE_FIELDS:]: if name.startswith('nsec_'): continue # ignore the nsec_Xtime here kwds[name] = lltype.cast_primitive(TYPE, value) return os.stat_result(positional, kwds)
[ "def", "make_stat_result", "(", "tup", ")", ":", "assert", "len", "(", "tup", ")", "==", "len", "(", "STAT_FIELDS", ")", "assert", "float", "not", "in", "[", "type", "(", "x", ")", "for", "x", "in", "tup", "]", "positional", "=", "[", "]", "for", ...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/rpython/rlib/rposix_stat.py#L278-L302
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pip/_internal/index.py
python
PackageFinder.__init__
( self, find_links, # type: List[str] index_urls, # type: List[str] allow_all_prereleases=False, # type: bool trusted_hosts=None, # type: Optional[Iterable[str]] session=None, # type: Optional[PipSession] format_control=None, # type: Optional[FormatControl] platform=None, # type: Optional[str] versions=None, # type: Optional[List[str]] abi=None, # type: Optional[str] implementation=None, # type: Optional[str] prefer_binary=False # type: bool )
Create a PackageFinder. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packages when consulting the index and links. :param platform: A string or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platform passed in. These packages will only be downloaded for distribution: they will not be built locally. :param versions: A list of strings or None. This is passed directly to pep425tags.py in the get_supported() method. :param abi: A string or None. This is passed directly to pep425tags.py in the get_supported() method. :param implementation: A string or None. This is passed directly to pep425tags.py in the get_supported() method. :param prefer_binary: Whether to prefer an old, but valid, binary dist over a new source dist.
Create a PackageFinder.
[ "Create", "a", "PackageFinder", "." ]
def __init__( self, find_links, # type: List[str] index_urls, # type: List[str] allow_all_prereleases=False, # type: bool trusted_hosts=None, # type: Optional[Iterable[str]] session=None, # type: Optional[PipSession] format_control=None, # type: Optional[FormatControl] platform=None, # type: Optional[str] versions=None, # type: Optional[List[str]] abi=None, # type: Optional[str] implementation=None, # type: Optional[str] prefer_binary=False # type: bool ): # type: (...) -> None """Create a PackageFinder. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packages when consulting the index and links. :param platform: A string or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platform passed in. These packages will only be downloaded for distribution: they will not be built locally. :param versions: A list of strings or None. This is passed directly to pep425tags.py in the get_supported() method. :param abi: A string or None. This is passed directly to pep425tags.py in the get_supported() method. :param implementation: A string or None. This is passed directly to pep425tags.py in the get_supported() method. :param prefer_binary: Whether to prefer an old, but valid, binary dist over a new source dist. """ if session is None: raise TypeError( "PackageFinder() missing 1 required keyword argument: " "'session'" ) # Build find_links. If an argument starts with ~, it may be # a local file relative to a home directory. So try normalizing # it and if it exists, use the normalized version. # This is deliberately conservative - it might be fine just to # blindly normalize anything starting with a ~... self.find_links = [] # type: List[str] for link in find_links: if link.startswith('~'): new_link = normalize_path(link) if os.path.exists(new_link): link = new_link self.find_links.append(link) self.index_urls = index_urls # These are boring links that have already been logged somehow: self.logged_links = set() # type: Set[Link] self.format_control = format_control or FormatControl(set(), set()) # Domains that we won't emit warnings for when not using HTTPS self.secure_origins = [ ("*", host, "*") for host in (trusted_hosts if trusted_hosts else []) ] # type: List[SecureOrigin] # Do we want to allow _all_ pre-releases? self.allow_all_prereleases = allow_all_prereleases # The Session we'll use to make requests self.session = session # The valid tags to check potential found wheel candidates against valid_tags = get_supported( versions=versions, platform=platform, abi=abi, impl=implementation, ) self.candidate_evaluator = CandidateEvaluator( valid_tags=valid_tags, prefer_binary=prefer_binary, ) # If we don't have TLS enabled, then WARN if anyplace we're looking # relies on TLS. if not HAS_TLS: for link in itertools.chain(self.index_urls, self.find_links): parsed = urllib_parse.urlparse(link) if parsed.scheme == "https": logger.warning( "pip is configured with locations that require " "TLS/SSL, however the ssl module in Python is not " "available." ) break
[ "def", "__init__", "(", "self", ",", "find_links", ",", "# type: List[str]", "index_urls", ",", "# type: List[str]", "allow_all_prereleases", "=", "False", ",", "# type: bool", "trusted_hosts", "=", "None", ",", "# type: Optional[Iterable[str]]", "session", "=", "None",...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_internal/index.py#L405-L499
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/utils/appdirs.py
python
_get_win_folder_from_registry
(csidl_name)
return directory
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.
[ "This", "is", "a", "fallback", "technique", "at", "best", ".", "I", "m", "not", "sure", "if", "using", "the", "registry", "for", "this", "guarantees", "us", "the", "correct", "answer", "for", "all", "CSIDL_", "*", "names", "." ]
def _get_win_folder_from_registry(csidl_name): """ This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) directory, _type = _winreg.QueryValueEx(key, shell_folder_name) return directory
[ "def", "_get_win_folder_from_registry", "(", "csidl_name", ")", ":", "import", "_winreg", "shell_folder_name", "=", "{", "\"CSIDL_APPDATA\"", ":", "\"AppData\"", ",", "\"CSIDL_COMMON_APPDATA\"", ":", "\"Common AppData\"", ",", "\"CSIDL_LOCAL_APPDATA\"", ":", "\"Local AppDat...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/utils/appdirs.py#L205-L224
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Parser/asdl.py
python
ASDLParser.p_field_3
(self, (type, _, name))
return Field(type, name, opt=True)
field ::= Id ? Id
field ::= Id ? Id
[ "field", "::", "=", "Id", "?", "Id" ]
def p_field_3(self, (type, _, name)): " field ::= Id ? Id " return Field(type, name, opt=True)
[ "def", "p_field_3", "(", "self", ",", "(", "type", ",", "_", ",", "name", ")", ")", ":", "return", "Field", "(", "type", ",", "name", ",", "opt", "=", "True", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Parser/asdl.py#L209-L211
thingsboard/thingsboard-gateway
1d1b1fc2450852dbd56ff137c6bfd49143dc758d
thingsboard_gateway/connectors/snmp/snmp_uplink_converter.py
python
SNMPUplinkConverter.convert
(self, config, data)
return result
[]
def convert(self, config, data): result = { "deviceName": self.__config["deviceName"], "deviceType": self.__config["deviceType"], "attributes": [], "telemetry": [] } try: if isinstance(data, dict): result[config[0]].append({config[1]["key"]: {str(k): str(v) for k, v in data.items()}}) elif isinstance(data, list): if isinstance(data[0], str): result[config[0]].append({config[1]["key"]: ','.join(data)}) elif isinstance(data[0], dict): res = {} for item in data: res.update(**item) result[config[0]].append({config[1]["key"]: {str(k): str(v) for k, v in res.items()}}) elif isinstance(data, str): result[config[0]].append({config[1]["key"]: data}) elif isinstance(data, bytes): result[config[0]].append({config[1]["key"]: data.decode("UTF-8")}) else: result[config[0]].append({config[1]["key"]: data}) log.debug(result) except Exception as e: log.exception(e) return result
[ "def", "convert", "(", "self", ",", "config", ",", "data", ")", ":", "result", "=", "{", "\"deviceName\"", ":", "self", ".", "__config", "[", "\"deviceName\"", "]", ",", "\"deviceType\"", ":", "self", ".", "__config", "[", "\"deviceType\"", "]", ",", "\"...
https://github.com/thingsboard/thingsboard-gateway/blob/1d1b1fc2450852dbd56ff137c6bfd49143dc758d/thingsboard_gateway/connectors/snmp/snmp_uplink_converter.py#L22-L49
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/set/src/core/scapy.py
python
PcapReader.fileno
(self)
return self.f.fileno()
[]
def fileno(self): return self.f.fileno()
[ "def", "fileno", "(", "self", ")", ":", "return", "self", ".", "f", ".", "fileno", "(", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/set/src/core/scapy.py#L10397-L10398
wechatpy/wechatpy
5f693a7e90156786c2540ad3c941d12cdf6d88ef
wechatpy/client/api/invoice.py
python
WeChatInvoice.scan_title
(self, scan_text)
return self._post( "scantitle", data={ "scan_text": scan_text, }, )
根据扫描码,获取用户发票抬头 商户扫用户“我的—个人信息—我的发票抬头”里面的抬头二维码后,通过调用本接口,可以获取用户抬头信息 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1496554912_vfWU0 :param scan_text: 扫码后获取的文本 :return: 用户的发票抬头数据 :rtype: dict
根据扫描码,获取用户发票抬头 商户扫用户“我的—个人信息—我的发票抬头”里面的抬头二维码后,通过调用本接口,可以获取用户抬头信息 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1496554912_vfWU0
[ "根据扫描码,获取用户发票抬头", "商户扫用户“我的—个人信息—我的发票抬头”里面的抬头二维码后,通过调用本接口,可以获取用户抬头信息", "详情请参考", "https", ":", "//", "mp", ".", "weixin", ".", "qq", ".", "com", "/", "wiki?id", "=", "mp1496554912_vfWU0" ]
def scan_title(self, scan_text): """ 根据扫描码,获取用户发票抬头 商户扫用户“我的—个人信息—我的发票抬头”里面的抬头二维码后,通过调用本接口,可以获取用户抬头信息 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1496554912_vfWU0 :param scan_text: 扫码后获取的文本 :return: 用户的发票抬头数据 :rtype: dict """ return self._post( "scantitle", data={ "scan_text": scan_text, }, )
[ "def", "scan_title", "(", "self", ",", "scan_text", ")", ":", "return", "self", ".", "_post", "(", "\"scantitle\"", ",", "data", "=", "{", "\"scan_text\"", ":", "scan_text", ",", "}", ",", ")" ]
https://github.com/wechatpy/wechatpy/blob/5f693a7e90156786c2540ad3c941d12cdf6d88ef/wechatpy/client/api/invoice.py#L458-L474
travisgoodspeed/goodfet
1750cc1e8588af5470385e52fa098ca7364c2863
client/ATMEL_USART.py
python
USART.crStartBreak
(self)
[]
def crStartBreak(self): self.setControlReg(CR_STTBRK)
[ "def", "crStartBreak", "(", "self", ")", ":", "self", ".", "setControlReg", "(", "CR_STTBRK", ")" ]
https://github.com/travisgoodspeed/goodfet/blob/1750cc1e8588af5470385e52fa098ca7364c2863/client/ATMEL_USART.py#L162-L163
openstack/cloudkitty
78da8eac53c56566191aad548f035158877ccfe5
cloudkitty/utils/__init__.py
python
iso2dt
(iso_date)
return trans_dt
iso8601 format to datetime.
iso8601 format to datetime.
[ "iso8601", "format", "to", "datetime", "." ]
def iso2dt(iso_date): """iso8601 format to datetime.""" iso_dt = timeutils.parse_isotime(iso_date) trans_dt = timeutils.normalize_time(iso_dt) return trans_dt
[ "def", "iso2dt", "(", "iso_date", ")", ":", "iso_dt", "=", "timeutils", ".", "parse_isotime", "(", "iso_date", ")", "trans_dt", "=", "timeutils", ".", "normalize_time", "(", "iso_dt", ")", "return", "trans_dt" ]
https://github.com/openstack/cloudkitty/blob/78da8eac53c56566191aad548f035158877ccfe5/cloudkitty/utils/__init__.py#L92-L96
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/ipaddress.py
python
_split_optional_netmask
(address)
return addr
Helper to split the netmask and raise AddressValueError if needed
Helper to split the netmask and raise AddressValueError if needed
[ "Helper", "to", "split", "the", "netmask", "and", "raise", "AddressValueError", "if", "needed" ]
def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = _compat_str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr
[ "def", "_split_optional_netmask", "(", "address", ")", ":", "addr", "=", "_compat_str", "(", "address", ")", ".", "split", "(", "'/'", ")", "if", "len", "(", "addr", ")", ">", "2", ":", "raise", "AddressValueError", "(", "\"Only one '/' permitted in %r\"", "...
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/ipaddress.py#L278-L283
kivy/kivy
fbf561f73ddba9941b1b7e771f86264c6e6eef36
kivy/core/window/__init__.py
python
WindowBase.on_keyboard
(self, key, scancode=None, codepoint=None, modifier=None, **kwargs)
Event called when keyboard is used. .. warning:: Some providers may omit `scancode`, `codepoint` and/or `modifier`.
Event called when keyboard is used.
[ "Event", "called", "when", "keyboard", "is", "used", "." ]
def on_keyboard(self, key, scancode=None, codepoint=None, modifier=None, **kwargs): '''Event called when keyboard is used. .. warning:: Some providers may omit `scancode`, `codepoint` and/or `modifier`. ''' if 'unicode' in kwargs: Logger.warning("The use of the unicode parameter is deprecated, " "and will be removed in future versions. Use " "codepoint instead, which has identical " "semantics.") # Quit if user presses ESC or the typical OSX shortcuts CMD+q or CMD+w # TODO If just CMD+w is pressed, only the window should be closed. is_osx = platform == 'darwin' if WindowBase.on_keyboard.exit_on_escape: if key == 27 or all([is_osx, key in [113, 119], modifier == 1024]): if not self.dispatch('on_request_close', source='keyboard'): stopTouchApp() self.close() return True
[ "def", "on_keyboard", "(", "self", ",", "key", ",", "scancode", "=", "None", ",", "codepoint", "=", "None", ",", "modifier", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'unicode'", "in", "kwargs", ":", "Logger", ".", "warning", "(", "\"The...
https://github.com/kivy/kivy/blob/fbf561f73ddba9941b1b7e771f86264c6e6eef36/kivy/core/window/__init__.py#L1853-L1874
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/solvers/recurr.py
python
rsolve_poly
(coeffs, f, n, **hints)
Given linear recurrence operator `\operatorname{L}` of order `k` with polynomial coefficients and inhomogeneous equation `\operatorname{L} y = f`, where `f` is a polynomial, we seek for all polynomial solutions over field `K` of characteristic zero. The algorithm performs two basic steps: (1) Compute degree `N` of the general polynomial solution. (2) Find all polynomials of degree `N` or less of `\operatorname{L} y = f`. There are two methods for computing the polynomial solutions. If the degree bound is relatively small, i.e. it's smaller than or equal to the order of the recurrence, then naive method of undetermined coefficients is being used. This gives system of algebraic equations with `N+1` unknowns. In the other case, the algorithm performs transformation of the initial equation to an equivalent one, for which the system of algebraic equations has only `r` indeterminates. This method is quite sophisticated (in comparison with the naive one) and was invented together by Abramov, Bronstein and Petkovsek. It is possible to generalize the algorithm implemented here to the case of linear q-difference and differential equations. Lets say that we would like to compute `m`-th Bernoulli polynomial up to a constant. For this we can use `b(n+1) - b(n) = m n^{m-1}` recurrence, which has solution `b(n) = B_m + C`. For example: >>> from sympy import Symbol, rsolve_poly >>> n = Symbol('n', integer=True) >>> rsolve_poly([-1, 1], 4*n**3, n) C0 + n**4 - 2*n**3 + n**2 References ========== .. [1] S. A. Abramov, M. Bronstein and M. Petkovsek, On polynomial solutions of linear operator equations, in: T. Levelt, ed., Proc. ISSAC '95, ACM Press, New York, 1995, 290-296. .. [2] M. Petkovsek, Hypergeometric solutions of linear recurrences with polynomial coefficients, J. Symbolic Computation, 14 (1992), 243-264. .. [3] M. Petkovsek, H. S. Wilf, D. Zeilberger, A = B, 1996.
Given linear recurrence operator `\operatorname{L}` of order `k` with polynomial coefficients and inhomogeneous equation `\operatorname{L} y = f`, where `f` is a polynomial, we seek for all polynomial solutions over field `K` of characteristic zero.
[ "Given", "linear", "recurrence", "operator", "\\", "operatorname", "{", "L", "}", "of", "order", "k", "with", "polynomial", "coefficients", "and", "inhomogeneous", "equation", "\\", "operatorname", "{", "L", "}", "y", "=", "f", "where", "f", "is", "a", "po...
def rsolve_poly(coeffs, f, n, **hints): """ Given linear recurrence operator `\operatorname{L}` of order `k` with polynomial coefficients and inhomogeneous equation `\operatorname{L} y = f`, where `f` is a polynomial, we seek for all polynomial solutions over field `K` of characteristic zero. The algorithm performs two basic steps: (1) Compute degree `N` of the general polynomial solution. (2) Find all polynomials of degree `N` or less of `\operatorname{L} y = f`. There are two methods for computing the polynomial solutions. If the degree bound is relatively small, i.e. it's smaller than or equal to the order of the recurrence, then naive method of undetermined coefficients is being used. This gives system of algebraic equations with `N+1` unknowns. In the other case, the algorithm performs transformation of the initial equation to an equivalent one, for which the system of algebraic equations has only `r` indeterminates. This method is quite sophisticated (in comparison with the naive one) and was invented together by Abramov, Bronstein and Petkovsek. It is possible to generalize the algorithm implemented here to the case of linear q-difference and differential equations. Lets say that we would like to compute `m`-th Bernoulli polynomial up to a constant. For this we can use `b(n+1) - b(n) = m n^{m-1}` recurrence, which has solution `b(n) = B_m + C`. For example: >>> from sympy import Symbol, rsolve_poly >>> n = Symbol('n', integer=True) >>> rsolve_poly([-1, 1], 4*n**3, n) C0 + n**4 - 2*n**3 + n**2 References ========== .. [1] S. A. Abramov, M. Bronstein and M. Petkovsek, On polynomial solutions of linear operator equations, in: T. Levelt, ed., Proc. ISSAC '95, ACM Press, New York, 1995, 290-296. .. [2] M. Petkovsek, Hypergeometric solutions of linear recurrences with polynomial coefficients, J. Symbolic Computation, 14 (1992), 243-264. .. [3] M. Petkovsek, H. S. Wilf, D. Zeilberger, A = B, 1996. """ f = sympify(f) if not f.is_polynomial(n): return None homogeneous = f.is_zero r = len(coeffs) - 1 coeffs = [ Poly(coeff, n) for coeff in coeffs ] polys = [ Poly(0, n) ] * (r + 1) terms = [ (S.Zero, S.NegativeInfinity) ] *(r + 1) for i in xrange(0, r + 1): for j in xrange(i, r + 1): polys[i] += coeffs[j]*binomial(j, i) if not polys[i].is_zero: (exp,), coeff = polys[i].LT() terms[i] = (coeff, exp) d = b = terms[0][1] for i in xrange(1, r + 1): if terms[i][1] > d: d = terms[i][1] if terms[i][1] - i > b: b = terms[i][1] - i d, b = int(d), int(b) x = Dummy('x') degree_poly = S.Zero for i in xrange(0, r + 1): if terms[i][1] - i == b: degree_poly += terms[i][0]*FallingFactorial(x, i) nni_roots = list(roots(degree_poly, x, filter='Z', predicate=lambda r: r >= 0).keys()) if nni_roots: N = [max(nni_roots)] else: N = [] if homogeneous: N += [-b - 1] else: N += [f.as_poly(n).degree() - b, -b - 1] N = int(max(N)) if N < 0: if homogeneous: if hints.get('symbols', False): return (S.Zero, []) else: return S.Zero else: return None if N <= r: C = [] y = E = S.Zero for i in xrange(0, N + 1): C.append(Symbol('C' + str(i))) y += C[i] * n**i for i in xrange(0, r + 1): E += coeffs[i].as_expr()*y.subs(n, n + i) solutions = solve_undetermined_coeffs(E - f, C, n) if solutions is not None: C = [ c for c in C if (c not in solutions) ] result = y.subs(solutions) else: return None # TBD else: A = r U = N + A + b + 1 nni_roots = list(roots(polys[r], filter='Z', predicate=lambda r: r >= 0).keys()) if nni_roots != []: a = max(nni_roots) + 1 else: a = S.Zero def _zero_vector(k): return [S.Zero] * k def _one_vector(k): return [S.One] * k def _delta(p, k): B = S.One D = p.subs(n, a + k) for i in xrange(1, k + 1): B *= -Rational(k - i + 1, i) D += B * p.subs(n, a + k - i) return D alpha = {} for i in xrange(-A, d + 1): I = _one_vector(d + 1) for k in xrange(1, d + 1): I[k] = I[k - 1] * (x + i - k + 1)/k alpha[i] = S.Zero for j in xrange(0, A + 1): for k in xrange(0, d + 1): B = binomial(k, i + j) D = _delta(polys[j].as_expr(), k) alpha[i] += I[k]*B*D V = Matrix(U, A, lambda i, j: int(i == j)) if homogeneous: for i in xrange(A, U): v = _zero_vector(A) for k in xrange(1, A + b + 1): if i - k < 0: break B = alpha[k - A].subs(x, i - k) for j in xrange(0, A): v[j] += B * V[i - k, j] denom = alpha[-A].subs(x, i) for j in xrange(0, A): V[i, j] = -v[j] / denom else: G = _zero_vector(U) for i in xrange(A, U): v = _zero_vector(A) g = S.Zero for k in xrange(1, A + b + 1): if i - k < 0: break B = alpha[k - A].subs(x, i - k) for j in xrange(0, A): v[j] += B * V[i - k, j] g += B * G[i - k] denom = alpha[-A].subs(x, i) for j in xrange(0, A): V[i, j] = -v[j] / denom G[i] = (_delta(f, i - A) - g) / denom P, Q = _one_vector(U), _zero_vector(A) for i in xrange(1, U): P[i] = (P[i - 1] * (n - a - i + 1)/i).expand() for i in xrange(0, A): Q[i] = Add(*[ (v*p).expand() for v, p in zip(V[:, i], P) ]) if not homogeneous: h = Add(*[ (g*p).expand() for g, p in zip(G, P) ]) C = [ Symbol('C' + str(i)) for i in xrange(0, A) ] g = lambda i: Add(*[ c*_delta(q, i) for c, q in zip(C, Q) ]) if homogeneous: E = [ g(i) for i in xrange(N + 1, U) ] else: E = [ g(i) + _delta(h, i) for i in xrange(N + 1, U) ] if E != []: solutions = solve(E, *C) if not solutions: if homogeneous: if hints.get('symbols', False): return (S.Zero, []) else: return S.Zero else: return None else: solutions = {} if homogeneous: result = S.Zero else: result = h for c, q in list(zip(C, Q)): if c in solutions: s = solutions[c]*q C.remove(c) else: s = c*q result += s.expand() if hints.get('symbols', False): return (result, C) else: return result
[ "def", "rsolve_poly", "(", "coeffs", ",", "f", ",", "n", ",", "*", "*", "hints", ")", ":", "f", "=", "sympify", "(", "f", ")", "if", "not", "f", ".", "is_polynomial", "(", "n", ")", ":", "return", "None", "homogeneous", "=", "f", ".", "is_zero", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/solvers/recurr.py#L71-L346
pgq/skytools-legacy
8b7e6c118572a605d28b7a3403c96aeecfd0d272
python/londiste/setup.py
python
LondisteSetup.build_tgargs
(self)
return tgargs
Build trigger args
Build trigger args
[ "Build", "trigger", "args" ]
def build_tgargs(self): """Build trigger args""" tgargs = [] if self.options.trigger_arg: tgargs = self.options.trigger_arg tgflags = self.options.trigger_flags if tgflags: tgargs.append('tgflags='+tgflags) if self.options.no_triggers: tgargs.append('no_triggers') if self.options.merge_all: tgargs.append('merge_all') if self.options.no_merge: tgargs.append('no_merge') if self.options.expect_sync: tgargs.append('expect_sync') return tgargs
[ "def", "build_tgargs", "(", "self", ")", ":", "tgargs", "=", "[", "]", "if", "self", ".", "options", ".", "trigger_arg", ":", "tgargs", "=", "self", ".", "options", ".", "trigger_arg", "tgflags", "=", "self", ".", "options", ".", "trigger_flags", "if", ...
https://github.com/pgq/skytools-legacy/blob/8b7e6c118572a605d28b7a3403c96aeecfd0d272/python/londiste/setup.py#L271-L287
Cadene/tensorflow-model-zoo.torch
990b10ffc22d4c8eacb2a502f20415b4f70c74c2
models/research/object_detection/core/losses.py
python
WeightedSmoothL1LocalizationLoss._compute_loss
(self, prediction_tensor, target_tensor, weights)
return tf.reduce_sum(anchorwise_smooth_l1norm)
Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, code_size] representing the (encoded) predicted locations of objects. target_tensor: A float tensor of shape [batch_size, num_anchors, code_size] representing the regression targets weights: a float tensor of shape [batch_size, num_anchors] Returns: loss: a (scalar) tensor representing the value of the loss function
Compute loss function.
[ "Compute", "loss", "function", "." ]
def _compute_loss(self, prediction_tensor, target_tensor, weights): """Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, code_size] representing the (encoded) predicted locations of objects. target_tensor: A float tensor of shape [batch_size, num_anchors, code_size] representing the regression targets weights: a float tensor of shape [batch_size, num_anchors] Returns: loss: a (scalar) tensor representing the value of the loss function """ diff = prediction_tensor - target_tensor abs_diff = tf.abs(diff) abs_diff_lt_1 = tf.less(abs_diff, 1) anchorwise_smooth_l1norm = tf.reduce_sum( tf.where(abs_diff_lt_1, 0.5 * tf.square(abs_diff), abs_diff - 0.5), 2) * weights if self._anchorwise_output: return anchorwise_smooth_l1norm return tf.reduce_sum(anchorwise_smooth_l1norm)
[ "def", "_compute_loss", "(", "self", ",", "prediction_tensor", ",", "target_tensor", ",", "weights", ")", ":", "diff", "=", "prediction_tensor", "-", "target_tensor", "abs_diff", "=", "tf", ".", "abs", "(", "diff", ")", "abs_diff_lt_1", "=", "tf", ".", "less...
https://github.com/Cadene/tensorflow-model-zoo.torch/blob/990b10ffc22d4c8eacb2a502f20415b4f70c74c2/models/research/object_detection/core/losses.py#L144-L165
owid/covid-19-data
936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92
scripts/scripts/shared.py
python
_sum_aggregate
(df, name, include=None, exclude=None)
return df
[]
def _sum_aggregate(df, name, include=None, exclude=None): df = df.copy() if include: df = df[df["location"].isin(include)] if exclude: df = df[~df["location"].isin(exclude)] df = df.groupby("date").sum().reset_index() df["location"] = name return df
[ "def", "_sum_aggregate", "(", "df", ",", "name", ",", "include", "=", "None", ",", "exclude", "=", "None", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "if", "include", ":", "df", "=", "df", "[", "df", "[", "\"location\"", "]", ".", "isin", ...
https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/scripts/shared.py#L133-L141
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/wasm/binary/writer.py
python
BinaryFileWriter.write_type_definition
(self, type_definition)
Write out a `type` definition entry.
Write out a `type` definition entry.
[ "Write", "out", "a", "type", "definition", "entry", "." ]
def write_type_definition(self, type_definition): """ Write out a `type` definition entry. """ self.write(b"\x60") # form self.write_vu32(len(type_definition.params)) # params for _, paramtype in type_definition.params: self.write_type(paramtype) self.write_vu1(len(type_definition.results)) # returns for rettype in type_definition.results: self.write_type(rettype)
[ "def", "write_type_definition", "(", "self", ",", "type_definition", ")", ":", "self", ".", "write", "(", "b\"\\x60\"", ")", "# form", "self", ".", "write_vu32", "(", "len", "(", "type_definition", ".", "params", ")", ")", "# params", "for", "_", ",", "par...
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/wasm/binary/writer.py#L228-L236
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/contrib/gis/gdal/geomtype.py
python
OGRGeomType.__ne__
(self, other)
return not (self == other)
[]
def __ne__(self, other): return not (self == other)
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "(", "self", "==", "other", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/contrib/gis/gdal/geomtype.py#L71-L72
HypothesisWorks/hypothesis
d1bfc4acc86899caa7a40f892322e1a69fbf36f4
hypothesis-python/src/hypothesis/core.py
python
seed
(seed: Hashable)
return accept
seed: Start the test execution from a specific seed. May be any hashable object. No exact meaning for seed is provided other than that for a fixed seed value Hypothesis will try the same actions (insofar as it can given external sources of non- determinism. e.g. timing and hash randomization). Overrides the derandomize setting, which is designed to enable deterministic builds rather than reproducing observed failures.
seed: Start the test execution from a specific seed.
[ "seed", ":", "Start", "the", "test", "execution", "from", "a", "specific", "seed", "." ]
def seed(seed: Hashable) -> Callable[[TestFunc], TestFunc]: """seed: Start the test execution from a specific seed. May be any hashable object. No exact meaning for seed is provided other than that for a fixed seed value Hypothesis will try the same actions (insofar as it can given external sources of non- determinism. e.g. timing and hash randomization). Overrides the derandomize setting, which is designed to enable deterministic builds rather than reproducing observed failures. """ def accept(test): test._hypothesis_internal_use_seed = seed current_settings = getattr(test, "_hypothesis_internal_use_settings", None) test._hypothesis_internal_use_settings = Settings( current_settings, database=None ) return test return accept
[ "def", "seed", "(", "seed", ":", "Hashable", ")", "->", "Callable", "[", "[", "TestFunc", "]", ",", "TestFunc", "]", ":", "def", "accept", "(", "test", ")", ":", "test", ".", "_hypothesis_internal_use_seed", "=", "seed", "current_settings", "=", "getattr",...
https://github.com/HypothesisWorks/hypothesis/blob/d1bfc4acc86899caa7a40f892322e1a69fbf36f4/hypothesis-python/src/hypothesis/core.py#L144-L165
postlund/pyatv
4ed1f5539f37d86d80272663d1f2ea34a6c41ec4
pyatv/protocols/dmap/__init__.py
python
DmapAudio.volume_up
(self)
Increase volume by one step.
Increase volume by one step.
[ "Increase", "volume", "by", "one", "step", "." ]
async def volume_up(self) -> None: """Increase volume by one step.""" await self.apple_tv.ctrl_int_cmd("volumeup")
[ "async", "def", "volume_up", "(", "self", ")", "->", "None", ":", "await", "self", ".", "apple_tv", ".", "ctrl_int_cmd", "(", "\"volumeup\"", ")" ]
https://github.com/postlund/pyatv/blob/4ed1f5539f37d86d80272663d1f2ea34a6c41ec4/pyatv/protocols/dmap/__init__.py#L562-L564
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/bs4/builder/_html5lib.py
python
Element.getNameTuple
(self)
[]
def getNameTuple(self): if self.namespace == None: return namespaces["html"], self.name else: return self.namespace, self.name
[ "def", "getNameTuple", "(", "self", ")", ":", "if", "self", ".", "namespace", "==", "None", ":", "return", "namespaces", "[", "\"html\"", "]", ",", "self", ".", "name", "else", ":", "return", "self", ".", "namespace", ",", "self", ".", "name" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/bs4/builder/_html5lib.py#L411-L415
kennethreitz-archive/requests3
69eb662703b40db58fdc6c095d0fe130c56649bb
requests3/http_models.py
python
Request.prepare
(self)
return p
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.
[ "Constructs", "a", ":", "class", ":", "PreparedRequest", "<PreparedRequest", ">", "for", "transmission", "and", "returns", "it", "." ]
def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p
[ "def", "prepare", "(", "self", ")", ":", "p", "=", "PreparedRequest", "(", ")", "p", ".", "prepare", "(", "method", "=", "self", ".", "method", ",", "url", "=", "self", ".", "url", ",", "headers", "=", "self", ".", "headers", ",", "files", "=", "...
https://github.com/kennethreitz-archive/requests3/blob/69eb662703b40db58fdc6c095d0fe130c56649bb/requests3/http_models.py#L309-L324
broadinstitute/viral-ngs
e144969e4c57060d53f38a4c3a270e8227feace1
assembly.py
python
vcf_to_seqs
(vcfIter, chrlens, samples, min_dp=0, major_cutoff=0.5, min_dp_ratio=0.0)
Take a VCF iterator and produce an iterator of chromosome x sample full sequences.
Take a VCF iterator and produce an iterator of chromosome x sample full sequences.
[ "Take", "a", "VCF", "iterator", "and", "produce", "an", "iterator", "of", "chromosome", "x", "sample", "full", "sequences", "." ]
def vcf_to_seqs(vcfIter, chrlens, samples, min_dp=0, major_cutoff=0.5, min_dp_ratio=0.0): ''' Take a VCF iterator and produce an iterator of chromosome x sample full sequences.''' seqs = {} cur_c = None for vcfrow in vcfIter: try: for c, start, stop, s, alleles in vcfrow_parse_and_call_snps( vcfrow, samples, min_dp=min_dp, major_cutoff=major_cutoff, min_dp_ratio=min_dp_ratio ): # changing chromosome? if c != cur_c: if cur_c is not None: # dump the previous chromosome before starting a new one for s in samples: seqs[s].replay_deletions() # because of the order of VCF rows with indels yield seqs[s].emit() # prepare base sequences for this chromosome cur_c = c for s in samples: name = len(samples) > 1 and ("%s-%s" % (c, s)) or c seqs[s] = MutableSequence(name, 1, chrlens[c]) # modify sequence for this chromosome/sample/position if len(alleles) == 1: # call a single allele seqs[s].replace(start, stop, alleles[0]) elif all(len(a) == 1 for a in alleles): # call an ambiguous SNP seqs[s].replace(start, stop, alleles_to_ambiguity(alleles)) else: # mix of indels with no clear winner... force the most popular one seqs[s].replace(start, stop, alleles[0]) except: log.exception("Exception occurred while parsing VCF file. Row: '%s'", vcfrow) raise # at the end, dump the last chromosome if cur_c is not None: for s in samples: seqs[s].replay_deletions() # because of the order of VCF rows with indels yield seqs[s].emit()
[ "def", "vcf_to_seqs", "(", "vcfIter", ",", "chrlens", ",", "samples", ",", "min_dp", "=", "0", ",", "major_cutoff", "=", "0.5", ",", "min_dp_ratio", "=", "0.0", ")", ":", "seqs", "=", "{", "}", "cur_c", "=", "None", "for", "vcfrow", "in", "vcfIter", ...
https://github.com/broadinstitute/viral-ngs/blob/e144969e4c57060d53f38a4c3a270e8227feace1/assembly.py#L1437-L1480
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/encodings/utf_8_sig.py
python
StreamReader.decode
(self, input, errors='strict')
return codecs.utf_8_decode(input, errors)
[]
def decode(self, input, errors='strict'): if len(input) < 3: if codecs.BOM_UTF8.startswith(input): # not enough data to decide if this is a BOM # => try again on the next call return ("", 0) elif input[:3] == codecs.BOM_UTF8: self.decode = codecs.utf_8_decode (output, consumed) = codecs.utf_8_decode(input[3:],errors) return (output, consumed+3) # (else) no BOM present self.decode = codecs.utf_8_decode return codecs.utf_8_decode(input, errors)
[ "def", "decode", "(", "self", ",", "input", ",", "errors", "=", "'strict'", ")", ":", "if", "len", "(", "input", ")", "<", "3", ":", "if", "codecs", ".", "BOM_UTF8", ".", "startswith", "(", "input", ")", ":", "# not enough data to decide if this is a BOM",...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/encodings/utf_8_sig.py#L105-L117
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_pt_objects.py
python
XLMWithLMHeadModel.forward
(self, *args, **kwargs)
[]
def forward(self, *args, **kwargs): requires_backends(self, ["torch"])
[ "def", "forward", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"torch\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L5338-L5339
ray-project/ray
703c1610348615dcb8c2d141a0c46675084660f5
python/ray/cluster_utils.py
python
Cluster.list_all_nodes
(self)
return nodes
Lists all nodes. TODO(rliaw): What is the desired behavior if a head node dies before worker nodes die? Returns: List of all nodes, including the head node.
Lists all nodes.
[ "Lists", "all", "nodes", "." ]
def list_all_nodes(self): """Lists all nodes. TODO(rliaw): What is the desired behavior if a head node dies before worker nodes die? Returns: List of all nodes, including the head node. """ nodes = list(self.worker_nodes) if self.head_node: nodes = [self.head_node] + nodes return nodes
[ "def", "list_all_nodes", "(", "self", ")", ":", "nodes", "=", "list", "(", "self", ".", "worker_nodes", ")", "if", "self", ".", "head_node", ":", "nodes", "=", "[", "self", ".", "head_node", "]", "+", "nodes", "return", "nodes" ]
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/python/ray/cluster_utils.py#L312-L324
pyqtgraph/pyqtgraph
ac3887abfca4e529aac44f022f8e40556a2587b0
pyqtgraph/parametertree/parameterTypes/file.py
python
_set_filepicker_kwargs
(fileDlg, **kwargs)
Applies a dict of enum/flag kwarg opts to a file dialog
Applies a dict of enum/flag kwarg opts to a file dialog
[ "Applies", "a", "dict", "of", "enum", "/", "flag", "kwarg", "opts", "to", "a", "file", "dialog" ]
def _set_filepicker_kwargs(fileDlg, **kwargs): """Applies a dict of enum/flag kwarg opts to a file dialog""" NO_MATCH = object() for kk, vv in kwargs.items(): # Convert string or list representations into true flags # 'fileMode' -> 'FileMode' formattedName = kk[0].upper() + kk[1:] # Edge case: "Options" has enum "Option" if formattedName == 'Options': enumCls = fileDlg.Option else: enumCls = getattr(fileDlg, formattedName, NO_MATCH) setFunc = getattr(fileDlg, f'set{formattedName}', NO_MATCH) if enumCls is NO_MATCH or setFunc is NO_MATCH: continue if enumCls is fileDlg.Option: builder = fileDlg.Option(0) # This is the only flag enum, all others can only take one value if isinstance(vv, str): vv = [vv] for flag in vv: curVal = getattr(enumCls, flag) builder |= curVal # Some Qt implementations turn into ints by this point outEnum = enumCls(builder) else: outEnum = getattr(enumCls, vv) setFunc(outEnum)
[ "def", "_set_filepicker_kwargs", "(", "fileDlg", ",", "*", "*", "kwargs", ")", ":", "NO_MATCH", "=", "object", "(", ")", "for", "kk", ",", "vv", "in", "kwargs", ".", "items", "(", ")", ":", "# Convert string or list representations into true flags", "# 'fileMode...
https://github.com/pyqtgraph/pyqtgraph/blob/ac3887abfca4e529aac44f022f8e40556a2587b0/pyqtgraph/parametertree/parameterTypes/file.py#L9-L36
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/topi/broadcast.py
python
greater
(lhs, rhs)
return _cpp.greater(lhs, rhs)
Compute (lhs>rhs) with auto-broadcasting Parameters ---------- lhs : tvm.te.Tensor or Expr The left operand rhs : tvm.te.Tensor or Expr The right operand Returns ------- ret : tvm.te.Tensor or Expr Returns Expr if both operands are Expr. Otherwise returns Tensor.
Compute (lhs>rhs) with auto-broadcasting
[ "Compute", "(", "lhs", ">", "rhs", ")", "with", "auto", "-", "broadcasting" ]
def greater(lhs, rhs): """Compute (lhs>rhs) with auto-broadcasting Parameters ---------- lhs : tvm.te.Tensor or Expr The left operand rhs : tvm.te.Tensor or Expr The right operand Returns ------- ret : tvm.te.Tensor or Expr Returns Expr if both operands are Expr. Otherwise returns Tensor. """ return _cpp.greater(lhs, rhs)
[ "def", "greater", "(", "lhs", ",", "rhs", ")", ":", "return", "_cpp", ".", "greater", "(", "lhs", ",", "rhs", ")" ]
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/topi/broadcast.py#L271-L287
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/core/computation/engines.py
python
AbstractEngine._evaluate
(self)
Return an evaluated expression. Parameters ---------- env : Scope The local and global environment in which to evaluate an expression. Notes ----- Must be implemented by subclasses.
Return an evaluated expression.
[ "Return", "an", "evaluated", "expression", "." ]
def _evaluate(self): """ Return an evaluated expression. Parameters ---------- env : Scope The local and global environment in which to evaluate an expression. Notes ----- Must be implemented by subclasses. """ pass
[ "def", "_evaluate", "(", "self", ")", ":", "pass" ]
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/core/computation/engines.py#L90-L104
debian-calibre/calibre
020fc81d3936a64b2ac51459ecb796666ab6a051
src/calibre/ebooks/rtf2xml/paragraph_def.py
python
ParagraphDef.__write_para_def_beg
(self)
Requires: nothing Returns: nothing Logic: Print out the beginning of the pargraph definition tag, and the markers that let me know when I have reached this tag. (These markers are used for later parsing.)
Requires: nothing Returns: nothing Logic: Print out the beginning of the pargraph definition tag, and the markers that let me know when I have reached this tag. (These markers are used for later parsing.)
[ "Requires", ":", "nothing", "Returns", ":", "nothing", "Logic", ":", "Print", "out", "the", "beginning", "of", "the", "pargraph", "definition", "tag", "and", "the", "markers", "that", "let", "me", "know", "when", "I", "have", "reached", "this", "tag", ".",...
def __write_para_def_beg(self): """ Requires: nothing Returns: nothing Logic: Print out the beginning of the pargraph definition tag, and the markers that let me know when I have reached this tag. (These markers are used for later parsing.) """ self.__get_num_of_style() table = self.__att_val_dict.get('in-table') if table: # del self.__att_val_dict['in-table'] self.__write_obj.write('mi<mk<in-table__\n') else: self.__write_obj.write('mi<mk<not-in-tbl\n') left_indent = self.__att_val_dict.get('left-indent') if left_indent: self.__write_obj.write('mi<mk<left_inden<%s\n' % left_indent) is_list = self.__att_val_dict.get('list-id') if is_list: self.__write_obj.write('mi<mk<list-id___<%s\n' % is_list) else: self.__write_obj.write('mi<mk<no-list___\n') self.__write_obj.write('mi<mk<style-name<%s\n' % self.__att_val_dict['name']) self.__write_obj.write(self.__start_marker) self.__write_obj.write('mi<tg<open-att__<paragraph-definition') self.__write_obj.write('<name>%s' % self.__att_val_dict['name']) self.__write_obj.write('<style-number>%s' % self.__att_val_dict['style-num']) tabs_list = ['tabs-left', 'tabs-right', 'tabs-decimal', 'tabs-center', 'tabs-bar', 'tabs'] """ for tab_item in tabs_list: if self.__att_val_dict[tab_item] != '': the_value = self.__att_val_dict[tab_item] the_value = the_value[:-1] self.__write_obj.write('<%s>%s' % (tab_item, the_value)) """ if self.__att_val_dict['tabs'] != '': the_value = self.__att_val_dict['tabs'] # the_value = the_value[:-1] self.__write_obj.write('<%s>%s' % ('tabs', the_value)) keys = sorted(self.__att_val_dict) exclude = frozenset(['name', 'style-num', 'in-table'] + tabs_list) for key in keys: if key not in exclude: self.__write_obj.write('<%s>%s' % (key, self.__att_val_dict[key])) self.__write_obj.write('\n') self.__write_obj.write(self.__start2_marker) if 'font-style' in keys: face = self.__att_val_dict['font-style'] self.__write_obj.write('mi<mk<font______<%s\n' % face) if 'caps' in keys: value = self.__att_val_dict['caps'] self.__write_obj.write('mi<mk<caps______<%s\n' % value)
[ "def", "__write_para_def_beg", "(", "self", ")", ":", "self", ".", "__get_num_of_style", "(", ")", "table", "=", "self", ".", "__att_val_dict", ".", "get", "(", "'in-table'", ")", "if", "table", ":", "# del self.__att_val_dict['in-table']", "self", ".", "__write...
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/ebooks/rtf2xml/paragraph_def.py#L647-L703
nucleic/enaml
65c2a2a2d765e88f2e1103046680571894bb41ed
enaml/core/enaml_ast.py
python
ASTVisitor.default_visit
(self, node, *args, **kwargs)
The default node visitor method. This method is invoked when no named visitor method is found for a given node. This default behavior raises an exception for the missing handler. Subclasses may reimplement this method for custom default behavior.
The default node visitor method.
[ "The", "default", "node", "visitor", "method", "." ]
def default_visit(self, node, *args, **kwargs): """ The default node visitor method. This method is invoked when no named visitor method is found for a given node. This default behavior raises an exception for the missing handler. Subclasses may reimplement this method for custom default behavior. """ msg = "no visitor found for node of type `%s`" raise TypeError(msg % type(node).__name__)
[ "def", "default_visit", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "\"no visitor found for node of type `%s`\"", "raise", "TypeError", "(", "msg", "%", "type", "(", "node", ")", ".", "__name__", ")" ]
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/core/enaml_ast.py#L364-L374
LinkedInAttic/indextank-service
880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e
storefront/boto/ec2/connection.py
python
EC2Connection.get_all_reserved_instances
(self, reserved_instances_id=None)
return self.get_list('DescribeReservedInstances', params, [('item', ReservedInstance)])
Describes Reserved Instance offerings that are available for purchase. :type reserved_instance_ids: list :param reserved_instance_ids: A list of the reserved instance ids that will be returned. If not provided, all reserved instances will be returned. :rtype: list :return: A list of :class:`boto.ec2.reservedinstance.ReservedInstance`
Describes Reserved Instance offerings that are available for purchase.
[ "Describes", "Reserved", "Instance", "offerings", "that", "are", "available", "for", "purchase", "." ]
def get_all_reserved_instances(self, reserved_instances_id=None): """ Describes Reserved Instance offerings that are available for purchase. :type reserved_instance_ids: list :param reserved_instance_ids: A list of the reserved instance ids that will be returned. If not provided, all reserved instances will be returned. :rtype: list :return: A list of :class:`boto.ec2.reservedinstance.ReservedInstance` """ params = {} if reserved_instances_id: self.build_list_params(params, reserved_instances_id, 'ReservedInstancesId') return self.get_list('DescribeReservedInstances', params, [('item', ReservedInstance)])
[ "def", "get_all_reserved_instances", "(", "self", ",", "reserved_instances_id", "=", "None", ")", ":", "params", "=", "{", "}", "if", "reserved_instances_id", ":", "self", ".", "build_list_params", "(", "params", ",", "reserved_instances_id", ",", "'ReservedInstance...
https://github.com/LinkedInAttic/indextank-service/blob/880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e/storefront/boto/ec2/connection.py#L1451-L1466
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/urllib/request.py
python
HTTPPasswordMgrWithDefaultRealm.find_user_password
(self, realm, authuri)
return HTTPPasswordMgr.find_user_password(self, None, authuri)
[]
def find_user_password(self, realm, authuri): user, password = HTTPPasswordMgr.find_user_password(self, realm, authuri) if user is not None: return user, password return HTTPPasswordMgr.find_user_password(self, None, authuri)
[ "def", "find_user_password", "(", "self", ",", "realm", ",", "authuri", ")", ":", "user", ",", "password", "=", "HTTPPasswordMgr", ".", "find_user_password", "(", "self", ",", "realm", ",", "authuri", ")", "if", "user", "is", "not", "None", ":", "return", ...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/urllib/request.py#L831-L836
openstack/octavia
27e5b27d31c695ba72fb6750de2bdafd76e0d7d9
octavia/api/v2/controllers/quotas.py
python
QuotasController.put
(self, project_id, quotas)
return self._convert_db_to_type(db_quotas, quota_types.QuotaResponse)
Update any or all quotas for a project.
Update any or all quotas for a project.
[ "Update", "any", "or", "all", "quotas", "for", "a", "project", "." ]
def put(self, project_id, quotas): """Update any or all quotas for a project.""" context = pecan_request.context.get('octavia_context') if not project_id: raise exceptions.MissingAPIProjectID() self._auth_validate_action(context, project_id, constants.RBAC_PUT) quotas_dict = quotas.to_dict() self.repositories.quotas.update(context.session, project_id, **quotas_dict) db_quotas = self._get_db_quotas(context.session, project_id) return self._convert_db_to_type(db_quotas, quota_types.QuotaResponse)
[ "def", "put", "(", "self", ",", "project_id", ",", "quotas", ")", ":", "context", "=", "pecan_request", ".", "context", ".", "get", "(", "'octavia_context'", ")", "if", "not", "project_id", ":", "raise", "exceptions", ".", "MissingAPIProjectID", "(", ")", ...
https://github.com/openstack/octavia/blob/27e5b27d31c695ba72fb6750de2bdafd76e0d7d9/octavia/api/v2/controllers/quotas.py#L65-L78
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
docs/developer/.scripts/33_render_status.py
python
render_latest_version_progress
()
return lines
[]
def render_latest_version_progress(): valid_checks = sorted(get_testable_checks()) total_checks = len(valid_checks) supported_checks = 0 lines = ['## New version support', '', None, '', '??? check "Completed"'] for check in valid_checks: skip_check = False with open(get_tox_file(check)) as tox_file: for line in tox_file: if line.startswith('[testenv:latest]'): supported_checks += 1 status = 'X' break elif line.startswith('# SKIP-LATEST-VERSION-CHECK'): skip_check = True break else: status = ' ' if skip_check: total_checks -= 1 continue lines.append(f' - [{status}] {check}') percent = supported_checks / total_checks * 100 formatted_percent = f'{percent:.2f}' lines[2] = f'[={formatted_percent}% "{formatted_percent}%"]' lines[4] = f'??? check "Completed {supported_checks}/{total_checks}"' return lines
[ "def", "render_latest_version_progress", "(", ")", ":", "valid_checks", "=", "sorted", "(", "get_testable_checks", "(", ")", ")", "total_checks", "=", "len", "(", "valid_checks", ")", "supported_checks", "=", "0", "lines", "=", "[", "'## New version support'", ","...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/docs/developer/.scripts/33_render_status.py#L193-L225
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/compute/drivers/azure_arm.py
python
AzureNodeDriver.ex_get_volume
(self, id)
return self._to_volume(r.object)
Fetch information about a volume. :param id: The complete resource path to the volume resource. :type id: ``str`` :return: The StorageVolume object :rtype: :class:`.StorageVolume`
Fetch information about a volume.
[ "Fetch", "information", "about", "a", "volume", "." ]
def ex_get_volume(self, id): """ Fetch information about a volume. :param id: The complete resource path to the volume resource. :type id: ``str`` :return: The StorageVolume object :rtype: :class:`.StorageVolume` """ r = self.connection.request(id, params={"api-version": RESOURCE_API_VERSION}) return self._to_volume(r.object)
[ "def", "ex_get_volume", "(", "self", ",", "id", ")", ":", "r", "=", "self", ".", "connection", ".", "request", "(", "id", ",", "params", "=", "{", "\"api-version\"", ":", "RESOURCE_API_VERSION", "}", ")", "return", "self", ".", "_to_volume", "(", "r", ...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/azure_arm.py#L1779-L1791
traveller59/second.pytorch
3aba19c9688274f75ebb5e576f65cfe54773c021
torchplus/train/fastai_optim.py
python
split_bn_bias
(layer_groups)
return split_groups
Split the layers in `layer_groups` into batchnorm (`bn_types`) and non-batchnorm groups.
Split the layers in `layer_groups` into batchnorm (`bn_types`) and non-batchnorm groups.
[ "Split", "the", "layers", "in", "layer_groups", "into", "batchnorm", "(", "bn_types", ")", "and", "non", "-", "batchnorm", "groups", "." ]
def split_bn_bias(layer_groups): "Split the layers in `layer_groups` into batchnorm (`bn_types`) and non-batchnorm groups." split_groups = [] for l in layer_groups: l1, l2 = [], [] for c in l.children(): if isinstance(c, bn_types): l2.append(c) else: l1.append(c) split_groups += [nn.Sequential(*l1), nn.Sequential(*l2)] return split_groups
[ "def", "split_bn_bias", "(", "layer_groups", ")", ":", "split_groups", "=", "[", "]", "for", "l", "in", "layer_groups", ":", "l1", ",", "l2", "=", "[", "]", ",", "[", "]", "for", "c", "in", "l", ".", "children", "(", ")", ":", "if", "isinstance", ...
https://github.com/traveller59/second.pytorch/blob/3aba19c9688274f75ebb5e576f65cfe54773c021/torchplus/train/fastai_optim.py#L14-L23
modflowpy/flopy
eecd1ad193c5972093c9712e5c4b7a83284f0688
flopy/mfusg/mfusgwel.py
python
MfUsgWel._get_kper_data
(kper, first, stress_period_data)
return itmp, kper_data
Gets boundary condition stress period data for a given stress period. Parameters: ---------- kper: int stress period (base 0) first : int First stress period for which stress period data is defined stress_period_data : Numpy recarray or int or None Flopy boundary condition stress_period_data object (with a "data" attribute that is keyed on kper) Returns ------- itmp : int Number of boundary conditions for stress period kper kper_data : Numpy recarray Boundary condition data for stress period kper
Gets boundary condition stress period data for a given stress period.
[ "Gets", "boundary", "condition", "stress", "period", "data", "for", "a", "given", "stress", "period", "." ]
def _get_kper_data(kper, first, stress_period_data): """ Gets boundary condition stress period data for a given stress period. Parameters: ---------- kper: int stress period (base 0) first : int First stress period for which stress period data is defined stress_period_data : Numpy recarray or int or None Flopy boundary condition stress_period_data object (with a "data" attribute that is keyed on kper) Returns ------- itmp : int Number of boundary conditions for stress period kper kper_data : Numpy recarray Boundary condition data for stress period kper """ kpers = list(stress_period_data.data.keys()) # Fill missing early kpers with 0 kper_data = None if kper < first: itmp = 0 elif kper in kpers: kper_data = deepcopy(stress_period_data.data[kper]) kper_vtype = stress_period_data.vtype[kper] if kper_vtype == np.recarray: itmp = kper_data.shape[0] lnames = [name.lower() for name in kper_data.dtype.names] for idx in ["k", "i", "j", "node"]: if idx in lnames: kper_data[idx] += 1 elif (kper_vtype == int) or (kper_vtype is None): itmp = kper_data # Fill late missing kpers with -1 else: itmp = -1 return itmp, kper_data
[ "def", "_get_kper_data", "(", "kper", ",", "first", ",", "stress_period_data", ")", ":", "kpers", "=", "list", "(", "stress_period_data", ".", "data", ".", "keys", "(", ")", ")", "# Fill missing early kpers with 0", "kper_data", "=", "None", "if", "kper", "<",...
https://github.com/modflowpy/flopy/blob/eecd1ad193c5972093c9712e5c4b7a83284f0688/flopy/mfusg/mfusgwel.py#L319-L359
facebookresearch/hgnn
2a22fdb479996c2318f85ad36d2750a383011773
gnn/RiemannianGNN.py
python
RiemannianGNN.forward
(self, node_repr, adj_list, weight, mask)
return node_repr
Args: node_repr: [node_num, embed_size] node_repr is in Euclidean space. If node_repr is in hyperbolic space, invoke log_map_zero first. adj_list: [node_num, max_neighbor] adjacency list weight: [node_num, max_neighbor] weights of the adjacency list mask: [node_num, 1] 1 denote real node, 0 padded node Return: [node_num, embed_size] in hyperbolic space
Args: node_repr: [node_num, embed_size] node_repr is in Euclidean space. If node_repr is in hyperbolic space, invoke log_map_zero first. adj_list: [node_num, max_neighbor] adjacency list weight: [node_num, max_neighbor] weights of the adjacency list mask: [node_num, 1] 1 denote real node, 0 padded node Return: [node_num, embed_size] in hyperbolic space
[ "Args", ":", "node_repr", ":", "[", "node_num", "embed_size", "]", "node_repr", "is", "in", "Euclidean", "space", ".", "If", "node_repr", "is", "in", "hyperbolic", "space", "invoke", "log_map_zero", "first", ".", "adj_list", ":", "[", "node_num", "max_neighbor...
def forward(self, node_repr, adj_list, weight, mask): """ Args: node_repr: [node_num, embed_size] node_repr is in Euclidean space. If node_repr is in hyperbolic space, invoke log_map_zero first. adj_list: [node_num, max_neighbor] adjacency list weight: [node_num, max_neighbor] weights of the adjacency list mask: [node_num, 1] 1 denote real node, 0 padded node Return: [node_num, embed_size] in hyperbolic space """ # split the adjacency list and weights based on edge types adj_list, weight = self.split_input(adj_list, weight) # gnn layers for step in range(self.args.gnn_layer): node_repr = self.manifold.log_map_zero(node_repr) * mask if step > 0 else node_repr * mask combined_msg = self.get_combined_msg(step, node_repr, adj_list, weight, mask) combined_msg = self.dropout(combined_msg) * mask node_repr = self.manifold.exp_map_zero(combined_msg) * mask node_repr = self.apply_activation(node_repr) * mask return node_repr
[ "def", "forward", "(", "self", ",", "node_repr", ",", "adj_list", ",", "weight", ",", "mask", ")", ":", "# split the adjacency list and weights based on edge types", "adj_list", ",", "weight", "=", "self", ".", "split_input", "(", "adj_list", ",", "weight", ")", ...
https://github.com/facebookresearch/hgnn/blob/2a22fdb479996c2318f85ad36d2750a383011773/gnn/RiemannianGNN.py#L156-L177