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
HazyResearch/fonduer
c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd
src/fonduer/utils/utils_udf.py
python
get_sparse_matrix
( session: Session, key_table: Table, cand_lists: Union[Sequence[Candidate], Iterable[Sequence[Candidate]]], key: Optional[str] = None, )
return result
Load sparse matrix of GoldLabels for each candidate_class.
Load sparse matrix of GoldLabels for each candidate_class.
[ "Load", "sparse", "matrix", "of", "GoldLabels", "for", "each", "candidate_class", "." ]
def get_sparse_matrix( session: Session, key_table: Table, cand_lists: Union[Sequence[Candidate], Iterable[Sequence[Candidate]]], key: Optional[str] = None, ) -> List[csr_matrix]: """Load sparse matrix of GoldLabels for each candidate_class.""" result = [] cand_lists = cand_lists if isinstance(cand_lists, (list, tuple)) else [cand_lists] for cand_list in cand_lists: if len(cand_list) == 0: raise ValueError("cand_lists contain empty cand_list.") # Keys are used as a global index if key: key_names = [key] else: # Get all keys all_keys = get_sparse_matrix_keys(session, key_table) # Filter only keys that are used by this cand_list key_names = [k.name for k in all_keys] annotations: List[Dict[str, Any]] = [] for cand in cand_list: annotation_mixins: List[AnnotationMixin] = _get_cand_values(cand, key_table) if annotation_mixins: annotations.append( { "keys": annotation_mixins[0].keys, "values": annotation_mixins[0].values, } ) else: annotations.append({"keys": [], "values": []}) result.append(_convert_mappings_to_matrix(annotations, key_names)) return result
[ "def", "get_sparse_matrix", "(", "session", ":", "Session", ",", "key_table", ":", "Table", ",", "cand_lists", ":", "Union", "[", "Sequence", "[", "Candidate", "]", ",", "Iterable", "[", "Sequence", "[", "Candidate", "]", "]", "]", ",", "key", ":", "Opti...
https://github.com/HazyResearch/fonduer/blob/c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd/src/fonduer/utils/utils_udf.py#L125-L161
runawayhorse001/LearningApacheSpark
67f3879dce17553195f094f5728b94a01badcf24
pyspark/sql/dataframe.py
python
DataFrame.approxQuantile
(self, col, probabilities, relativeError)
return jaq_list[0] if isStr else jaq_list
Calculates the approximate quantiles of numerical columns of a DataFrame. The result of this algorithm has the following deterministic bound: If the DataFrame has N elements and if we request the quantile at probability `p` up to error `err`, then the algorithm will return a sample `x` from the DataFrame so that the *exact* rank of `x` is close to (p * N). More precisely, floor((p - err) * N) <= rank(x) <= ceil((p + err) * N). This method implements a variation of the Greenwald-Khanna algorithm (with some speed optimizations). The algorithm was first present in [[http://dx.doi.org/10.1145/375663.375670 Space-efficient Online Computation of Quantile Summaries]] by Greenwald and Khanna. Note that null values will be ignored in numerical columns before calculation. For columns only containing null values, an empty list is returned. :param col: str, list. Can be a single column name, or a list of names for multiple columns. :param probabilities: a list of quantile probabilities Each number must belong to [0, 1]. For example 0 is the minimum, 0.5 is the median, 1 is the maximum. :param relativeError: The relative target precision to achieve (>= 0). If set to zero, the exact quantiles are computed, which could be very expensive. Note that values greater than 1 are accepted but give the same result as 1. :return: the approximate quantiles at the given probabilities. If the input `col` is a string, the output is a list of floats. If the input `col` is a list or tuple of strings, the output is also a list, but each element in it is a list of floats, i.e., the output is a list of list of floats. .. versionchanged:: 2.2 Added support for multiple columns.
Calculates the approximate quantiles of numerical columns of a DataFrame.
[ "Calculates", "the", "approximate", "quantiles", "of", "numerical", "columns", "of", "a", "DataFrame", "." ]
def approxQuantile(self, col, probabilities, relativeError): """ Calculates the approximate quantiles of numerical columns of a DataFrame. The result of this algorithm has the following deterministic bound: If the DataFrame has N elements and if we request the quantile at probability `p` up to error `err`, then the algorithm will return a sample `x` from the DataFrame so that the *exact* rank of `x` is close to (p * N). More precisely, floor((p - err) * N) <= rank(x) <= ceil((p + err) * N). This method implements a variation of the Greenwald-Khanna algorithm (with some speed optimizations). The algorithm was first present in [[http://dx.doi.org/10.1145/375663.375670 Space-efficient Online Computation of Quantile Summaries]] by Greenwald and Khanna. Note that null values will be ignored in numerical columns before calculation. For columns only containing null values, an empty list is returned. :param col: str, list. Can be a single column name, or a list of names for multiple columns. :param probabilities: a list of quantile probabilities Each number must belong to [0, 1]. For example 0 is the minimum, 0.5 is the median, 1 is the maximum. :param relativeError: The relative target precision to achieve (>= 0). If set to zero, the exact quantiles are computed, which could be very expensive. Note that values greater than 1 are accepted but give the same result as 1. :return: the approximate quantiles at the given probabilities. If the input `col` is a string, the output is a list of floats. If the input `col` is a list or tuple of strings, the output is also a list, but each element in it is a list of floats, i.e., the output is a list of list of floats. .. versionchanged:: 2.2 Added support for multiple columns. """ if not isinstance(col, (basestring, list, tuple)): raise ValueError("col should be a string, list or tuple, but got %r" % type(col)) isStr = isinstance(col, basestring) if isinstance(col, tuple): col = list(col) elif isStr: col = [col] for c in col: if not isinstance(c, basestring): raise ValueError("columns should be strings, but got %r" % type(c)) col = _to_list(self._sc, col) if not isinstance(probabilities, (list, tuple)): raise ValueError("probabilities should be a list or tuple") if isinstance(probabilities, tuple): probabilities = list(probabilities) for p in probabilities: if not isinstance(p, (float, int, long)) or p < 0 or p > 1: raise ValueError("probabilities should be numerical (float, int, long) in [0,1].") probabilities = _to_list(self._sc, probabilities) if not isinstance(relativeError, (float, int, long)) or relativeError < 0: raise ValueError("relativeError should be numerical (float, int, long) >= 0.") relativeError = float(relativeError) jaq = self._jdf.stat().approxQuantile(col, probabilities, relativeError) jaq_list = [list(j) for j in jaq] return jaq_list[0] if isStr else jaq_list
[ "def", "approxQuantile", "(", "self", ",", "col", ",", "probabilities", ",", "relativeError", ")", ":", "if", "not", "isinstance", "(", "col", ",", "(", "basestring", ",", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"col should be a ...
https://github.com/runawayhorse001/LearningApacheSpark/blob/67f3879dce17553195f094f5728b94a01badcf24/pyspark/sql/dataframe.py#L1815-L1886
WeblateOrg/weblate
8126f3dda9d24f2846b755955132a8b8410866c8
weblate/trans/views/edit.py
python
get_other_units
(unit)
return result
Returns other units to show while translating.
Returns other units to show while translating.
[ "Returns", "other", "units", "to", "show", "while", "translating", "." ]
def get_other_units(unit): """Returns other units to show while translating.""" result = { "total": 0, "skipped": False, "same": [], "matching": [], "context": [], "source": [], } allow_merge = False untranslated = False translation = unit.translation component = translation.component propagation = component.allow_translation_propagation same = None if unit.source and unit.context: match = Q(source=unit.source) & Q(context=unit.context) if component.has_template(): query = Q(source=unit.source) | Q(context=unit.context) else: query = Q(source=unit.source) elif unit.source: match = Q(source=unit.source) & Q(context="") query = Q(source=unit.source) elif unit.context: match = Q(context=unit.context) query = Q(context=unit.context) else: return result units = ( Unit.objects.filter( query, translation__component__project=component.project, translation__language=translation.language, ) .annotate( matches_current=Case( When(condition=match, then=1), default=0, output_field=IntegerField() ) ) .order_by("-matches_current") ) units_count = units.count() # Is it only this unit? if units_count == 1: return result result["total"] = units_count result["skipped"] = units_count > 20 for item in units[:20]: item.allow_merge = item.differently_translated = ( item.translated and item.target != unit.target ) item.is_propagated = ( propagation and item.translation.component.allow_translation_propagation and item.translation.plural_id == translation.plural_id and item.source == unit.source and item.context == unit.context ) untranslated |= not item.translated allow_merge |= item.allow_merge if item.pk == unit.pk: same = item result["same"].append(item) elif item.source == unit.source and item.context == unit.context: result["matching"].append(item) elif item.source == unit.source: result["source"].append(item) elif item.context == unit.context: result["context"].append(item) # Slightly different logic to allow applying current translation to # the propagated strings if same is not None: same.allow_merge = ( (untranslated or allow_merge) and same.translated and propagation ) allow_merge |= same.allow_merge result["total"] = sum(len(result[x]) for x in ("matching", "source", "context")) result["allow_merge"] = allow_merge return result
[ "def", "get_other_units", "(", "unit", ")", ":", "result", "=", "{", "\"total\"", ":", "0", ",", "\"skipped\"", ":", "False", ",", "\"same\"", ":", "[", "]", ",", "\"matching\"", ":", "[", "]", ",", "\"context\"", ":", "[", "]", ",", "\"source\"", ":...
https://github.com/WeblateOrg/weblate/blob/8126f3dda9d24f2846b755955132a8b8410866c8/weblate/trans/views/edit.py#L98-L188
PythonOT/POT
be0ed1dcd0b65ec804e454f1a2d3c0d227c0ddbe
ot/da.py
python
BaseTransport.inverse_transform
(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128)
r"""Transports target samples :math:`\mathbf{X_t}` onto source samples :math:`\mathbf{X_s}` Parameters ---------- Xs : array-like, shape (n_source_samples, n_features) The source input samples. ys : array-like, shape (n_source_samples,) The source class labels Xt : array-like, shape (n_target_samples, n_features) The target input samples. yt : array-like, shape (n_target_samples,) The target class labels. If some target samples are unlabelled, fill the :math:`\mathbf{y_t}`'s elements with -1. Warning: Note that, due to this convention -1 cannot be used as a class label batch_size : int, optional (default=128) The batch size for out of sample inverse transform Returns ------- transp_Xt : array-like, shape (n_source_samples, n_features) The transported target samples.
r"""Transports target samples :math:`\mathbf{X_t}` onto source samples :math:`\mathbf{X_s}`
[ "r", "Transports", "target", "samples", ":", "math", ":", "\\", "mathbf", "{", "X_t", "}", "onto", "source", "samples", ":", "math", ":", "\\", "mathbf", "{", "X_s", "}" ]
def inverse_transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128): r"""Transports target samples :math:`\mathbf{X_t}` onto source samples :math:`\mathbf{X_s}` Parameters ---------- Xs : array-like, shape (n_source_samples, n_features) The source input samples. ys : array-like, shape (n_source_samples,) The source class labels Xt : array-like, shape (n_target_samples, n_features) The target input samples. yt : array-like, shape (n_target_samples,) The target class labels. If some target samples are unlabelled, fill the :math:`\mathbf{y_t}`'s elements with -1. Warning: Note that, due to this convention -1 cannot be used as a class label batch_size : int, optional (default=128) The batch size for out of sample inverse transform Returns ------- transp_Xt : array-like, shape (n_source_samples, n_features) The transported target samples. """ # check the necessary inputs parameters are here if check_params(Xt=Xt): if np.array_equal(self.xt_, Xt): # perform standard barycentric mapping transp_ = self.coupling_.T / np.sum(self.coupling_, 0)[:, None] # set nans to 0 transp_[~ np.isfinite(transp_)] = 0 # compute transported samples transp_Xt = np.dot(transp_, self.xs_) else: # perform out of sample mapping indices = np.arange(Xt.shape[0]) batch_ind = [ indices[i:i + batch_size] for i in range(0, len(indices), batch_size)] transp_Xt = [] for bi in batch_ind: D0 = dist(Xt[bi], self.xt_) idx = np.argmin(D0, axis=1) # transport the target samples transp_ = self.coupling_.T / np.sum( self.coupling_, 0)[:, None] transp_[~ np.isfinite(transp_)] = 0 transp_Xt_ = np.dot(transp_, self.xs_) # define the transported points transp_Xt_ = transp_Xt_[idx, :] + Xt[bi] - self.xt_[idx, :] transp_Xt.append(transp_Xt_) transp_Xt = np.concatenate(transp_Xt, axis=0) return transp_Xt
[ "def", "inverse_transform", "(", "self", ",", "Xs", "=", "None", ",", "ys", "=", "None", ",", "Xt", "=", "None", ",", "yt", "=", "None", ",", "batch_size", "=", "128", ")", ":", "# check the necessary inputs parameters are here", "if", "check_params", "(", ...
https://github.com/PythonOT/POT/blob/be0ed1dcd0b65ec804e454f1a2d3c0d227c0ddbe/ot/da.py#L1153-L1218
wagtail/django-modelcluster
a5d00f7a817d1baf45198347040b84d2bdd2ea5b
modelcluster/forms.py
python
ClusterForm.is_valid
(self)
return form_is_valid and formsets_are_valid
[]
def is_valid(self): form_is_valid = super(ClusterForm, self).is_valid() formsets_are_valid = all(formset.is_valid() for formset in self._posted_formsets) return form_is_valid and formsets_are_valid
[ "def", "is_valid", "(", "self", ")", ":", "form_is_valid", "=", "super", "(", "ClusterForm", ",", "self", ")", ".", "is_valid", "(", ")", "formsets_are_valid", "=", "all", "(", "formset", ".", "is_valid", "(", ")", "for", "formset", "in", "self", ".", ...
https://github.com/wagtail/django-modelcluster/blob/a5d00f7a817d1baf45198347040b84d2bdd2ea5b/modelcluster/forms.py#L317-L320
sunpy/sunpy
528579df0a4c938c133bd08971ba75c131b189a7
sunpy/map/mapbase.py
python
GenericMap.dtype
(self)
return self.data.dtype
The `numpy.dtype` of the array of the map.
The `numpy.dtype` of the array of the map.
[ "The", "numpy", ".", "dtype", "of", "the", "array", "of", "the", "map", "." ]
def dtype(self): """ The `numpy.dtype` of the array of the map. """ return self.data.dtype
[ "def", "dtype", "(", "self", ")", ":", "return", "self", ".", "data", ".", "dtype" ]
https://github.com/sunpy/sunpy/blob/528579df0a4c938c133bd08971ba75c131b189a7/sunpy/map/mapbase.py#L648-L652
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
plugins/ipconsole/ipython_view.py
python
IterableIPShell.generatePrompt
(self, is_continuation)
return prompt
Generate prompt depending on is_continuation value @param is_continuation @type is_continuation: boolean @return: The prompt string representation @rtype: string
Generate prompt depending on is_continuation value
[ "Generate", "prompt", "depending", "on", "is_continuation", "value" ]
def generatePrompt(self, is_continuation): """ Generate prompt depending on is_continuation value @param is_continuation @type is_continuation: boolean @return: The prompt string representation @rtype: string """ if IPYTHON_VERSION >= 5: # HACK return '... ' if is_continuation else '>>> ' if is_continuation: prompt = self.IP.prompt_manager.render('in2') else: prompt = self.IP.prompt_manager.render('in') return prompt
[ "def", "generatePrompt", "(", "self", ",", "is_continuation", ")", ":", "if", "IPYTHON_VERSION", ">=", "5", ":", "# HACK", "return", "'... '", "if", "is_continuation", "else", "'>>> '", "if", "is_continuation", ":", "prompt", "=", "self", ".", "IP", ".", "pr...
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/plugins/ipconsole/ipython_view.py#L248-L266
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_adm_router.py
python
Yedit.remove_entry
(data, key, index=None, value=None, sep='.')
remove data at location key
remove data at location key
[ "remove", "data", "at", "location", "key" ]
def remove_entry(data, key, index=None, value=None, sep='.'): ''' remove data at location key ''' if key == '' and isinstance(data, dict): if value is not None: data.pop(value) elif index is not None: raise YeditException("remove_entry for a dictionary does not have an index {}".format(index)) else: data.clear() return True elif key == '' and isinstance(data, list): ind = None if value is not None: try: ind = data.index(value) except ValueError: return False elif index is not None: ind = index else: del data[:] if ind is not None: data.pop(ind) return True if not (key and Yedit.valid_key(key, sep)) and \ isinstance(data, (list, dict)): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes[:-1]: if dict_key and isinstance(data, dict): data = data.get(dict_key) elif (arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1): data = data[int(arr_ind)] else: return None # process last index for remove # expected list entry if key_indexes[-1][0]: if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501 del data[int(key_indexes[-1][0])] return True # expected dict entry elif key_indexes[-1][1]: if isinstance(data, dict): del data[key_indexes[-1][1]] return True
[ "def", "remove_entry", "(", "data", ",", "key", ",", "index", "=", "None", ",", "value", "=", "None", ",", "sep", "=", "'.'", ")", ":", "if", "key", "==", "''", "and", "isinstance", "(", "data", ",", "dict", ")", ":", "if", "value", "is", "not", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_adm_router.py#L340-L394
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/baredoc.py
python
_get_func_aliases
(tree)
return fun_aliases
Get __func_alias__ dict for mapping function names
Get __func_alias__ dict for mapping function names
[ "Get", "__func_alias__", "dict", "for", "mapping", "function", "names" ]
def _get_func_aliases(tree) -> Dict: """ Get __func_alias__ dict for mapping function names """ fun_aliases = {} assignments = [node for node in tree.body if isinstance(node, ast.Assign)] for assign in assignments: try: if assign.targets[0].id == "__func_alias__": for key, value in itertools.zip_longest( assign.value.keys, assign.value.values ): fun_aliases.update({key.s: value.s}) except AttributeError: pass return fun_aliases
[ "def", "_get_func_aliases", "(", "tree", ")", "->", "Dict", ":", "fun_aliases", "=", "{", "}", "assignments", "=", "[", "node", "for", "node", "in", "tree", ".", "body", "if", "isinstance", "(", "node", ",", "ast", ".", "Assign", ")", "]", "for", "as...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/baredoc.py#L39-L54
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/uuid.py
python
getnode
()
Get the hardware address as a 48-bit positive integer. The first time this runs, it may launch a separate program, which could be quite slow. If all attempts to obtain the hardware address fail, we choose a random 48-bit number with its eighth bit set to 1 as recommended in RFC 4122.
Get the hardware address as a 48-bit positive integer.
[ "Get", "the", "hardware", "address", "as", "a", "48", "-", "bit", "positive", "integer", "." ]
def getnode(): """Get the hardware address as a 48-bit positive integer. The first time this runs, it may launch a separate program, which could be quite slow. If all attempts to obtain the hardware address fail, we choose a random 48-bit number with its eighth bit set to 1 as recommended in RFC 4122. """ global _node if _node is not None: return _node import sys if sys.platform == 'win32': getters = _NODE_GETTERS_WIN32 else: getters = _NODE_GETTERS_UNIX for getter in getters + [_random_getnode]: try: _node = getter() except: continue if (_node is not None) and (0 <= _node < (1 << 48)): return _node assert False, '_random_getnode() returned invalid value: {}'.format(_node)
[ "def", "getnode", "(", ")", ":", "global", "_node", "if", "_node", "is", "not", "None", ":", "return", "_node", "import", "sys", "if", "sys", ".", "platform", "==", "'win32'", ":", "getters", "=", "_NODE_GETTERS_WIN32", "else", ":", "getters", "=", "_NOD...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/uuid.py#L533-L559
swcarpentry/python-novice-inflammation
06bb720afaf558edc2ecdded3cab4cbe7839a554
fig/optimize_svg.py
python
detect_optimizers
()
return available_optimizers
Detect available SVG optimizers. Currently checks: - svgcleaner - svgo - scour
Detect available SVG optimizers. Currently checks: - svgcleaner - svgo - scour
[ "Detect", "available", "SVG", "optimizers", ".", "Currently", "checks", ":", "-", "svgcleaner", "-", "svgo", "-", "scour" ]
def detect_optimizers(): """ Detect available SVG optimizers. Currently checks: - svgcleaner - svgo - scour """ available_optimizers = [] # Check if we have svgcleaner command = ["svgcleaner", "--version"] process = subprocess.run(command, capture_output=True) if not process.stderr: available_optimizers.append('svgcleaner') output = process.stdout.decode("ascii").split() if __name__ == '__main__': print("Found 'svgcleaner' version", output[1]) # Check if we have svgo command = ["svgo", "--version"] process = subprocess.run(command, capture_output=True) if not process.stderr: available_optimizers.append('svgo') output = process.stdout.decode("ascii").split() if __name__ == '__main__': print("Found 'svgo' version", output[0]) # Check if we have scour try: from scour import scour except ImportError: pass else: available_optimizers.append('scour') if __name__ == '__main__': print("Found 'scour' version", scour.__version__) return available_optimizers
[ "def", "detect_optimizers", "(", ")", ":", "available_optimizers", "=", "[", "]", "# Check if we have svgcleaner", "command", "=", "[", "\"svgcleaner\"", ",", "\"--version\"", "]", "process", "=", "subprocess", ".", "run", "(", "command", ",", "capture_output", "=...
https://github.com/swcarpentry/python-novice-inflammation/blob/06bb720afaf558edc2ecdded3cab4cbe7839a554/fig/optimize_svg.py#L13-L51
explosion/spaCy
a784b12eff48df9281b184cb7005e66bbd2e3aca
spacy/lang/ja/__init__.py
python
try_sudachi_import
(split_mode="A")
SudachiPy is required for Japanese support, so check for it. It it's not available blow up and explain how to fix it. split_mode should be one of these values: "A", "B", "C", None->"A".
SudachiPy is required for Japanese support, so check for it. It it's not available blow up and explain how to fix it. split_mode should be one of these values: "A", "B", "C", None->"A".
[ "SudachiPy", "is", "required", "for", "Japanese", "support", "so", "check", "for", "it", ".", "It", "it", "s", "not", "available", "blow", "up", "and", "explain", "how", "to", "fix", "it", ".", "split_mode", "should", "be", "one", "of", "these", "values"...
def try_sudachi_import(split_mode="A"): """SudachiPy is required for Japanese support, so check for it. It it's not available blow up and explain how to fix it. split_mode should be one of these values: "A", "B", "C", None->"A".""" try: from sudachipy import dictionary, tokenizer split_mode = { None: tokenizer.Tokenizer.SplitMode.A, "A": tokenizer.Tokenizer.SplitMode.A, "B": tokenizer.Tokenizer.SplitMode.B, "C": tokenizer.Tokenizer.SplitMode.C, }[split_mode] tok = dictionary.Dictionary().create(mode=split_mode) return tok except ImportError: raise ImportError( "Japanese support requires SudachiPy and SudachiDict-core " "(https://github.com/WorksApplications/SudachiPy). " "Install with `pip install sudachipy sudachidict_core` or " "install spaCy with `pip install spacy[ja]`." ) from None
[ "def", "try_sudachi_import", "(", "split_mode", "=", "\"A\"", ")", ":", "try", ":", "from", "sudachipy", "import", "dictionary", ",", "tokenizer", "split_mode", "=", "{", "None", ":", "tokenizer", ".", "Tokenizer", ".", "SplitMode", ".", "A", ",", "\"A\"", ...
https://github.com/explosion/spaCy/blob/a784b12eff48df9281b184cb7005e66bbd2e3aca/spacy/lang/ja/__init__.py#L231-L252
bigaidream-projects/drmad
a4bb6010595d956f29c5a42a095bab76a60b29eb
gpu_ver/refcode/models/layers/activations.py
python
relu
(x)
return output
[]
def relu(x): output = T.maximum(0., x) return output
[ "def", "relu", "(", "x", ")", ":", "output", "=", "T", ".", "maximum", "(", "0.", ",", "x", ")", "return", "output" ]
https://github.com/bigaidream-projects/drmad/blob/a4bb6010595d956f29c5a42a095bab76a60b29eb/gpu_ver/refcode/models/layers/activations.py#L10-L12
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.2/django/contrib/gis/admin/options.py
python
GeoModelAdmin._media
(self)
return media
Injects OpenLayers JavaScript into the admin.
Injects OpenLayers JavaScript into the admin.
[ "Injects", "OpenLayers", "JavaScript", "into", "the", "admin", "." ]
def _media(self): "Injects OpenLayers JavaScript into the admin." media = super(GeoModelAdmin, self)._media() media.add_js([self.openlayers_url]) media.add_js(self.extra_js) return media
[ "def", "_media", "(", "self", ")", ":", "media", "=", "super", "(", "GeoModelAdmin", ",", "self", ")", ".", "_media", "(", ")", "media", ".", "add_js", "(", "[", "self", ".", "openlayers_url", "]", ")", "media", ".", "add_js", "(", "self", ".", "ex...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/contrib/gis/admin/options.py#L43-L48
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/compiler/ast.py
python
If.__repr__
(self)
return "If(%s, %s)" % (repr(self.tests), repr(self.else_))
[]
def __repr__(self): return "If(%s, %s)" % (repr(self.tests), repr(self.else_))
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"If(%s, %s)\"", "%", "(", "repr", "(", "self", ".", "tests", ")", ",", "repr", "(", "self", ".", "else_", ")", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/compiler/ast.py#L710-L711
datacenter/acitoolkit
629b84887dd0f0183b81efc8adb16817f985541a
acitoolkit/acifakeapic.py
python
FakeSession.has_events
(self, url)
return False
Check if there are events for a particular URL. Used internally by the class and instance subscriptions. :param url: URL string belonging to subscription :returns: True or False. True if an event exists for this subscription.
Check if there are events for a particular URL. Used internally by the class and instance subscriptions.
[ "Check", "if", "there", "are", "events", "for", "a", "particular", "URL", ".", "Used", "internally", "by", "the", "class", "and", "instance", "subscriptions", "." ]
def has_events(self, url): """ Check if there are events for a particular URL. Used internally by the class and instance subscriptions. :param url: URL string belonging to subscription :returns: True or False. True if an event exists for this subscription. """ return False
[ "def", "has_events", "(", "self", ",", "url", ")", ":", "return", "False" ]
https://github.com/datacenter/acitoolkit/blob/629b84887dd0f0183b81efc8adb16817f985541a/acitoolkit/acifakeapic.py#L320-L328
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/dependencies/cmake.py
python
CMakeDependency._cached_listdir
(path: str)
[]
def _cached_listdir(path: str) -> T.Tuple[T.Tuple[str, str], ...]: try: return tuple((x, str(x).lower()) for x in os.listdir(path)) except OSError: return tuple()
[ "def", "_cached_listdir", "(", "path", ":", "str", ")", "->", "T", ".", "Tuple", "[", "T", ".", "Tuple", "[", "str", ",", "str", "]", ",", "...", "]", ":", "try", ":", "return", "tuple", "(", "(", "x", ",", "str", "(", "x", ")", ".", "lower",...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/dependencies/cmake.py#L246-L250
nerevu/riko
4d27102b605b8b4050ba566d5e0895d8d5f8b09a
riko/modules/rename.py
python
async_pipe
(*args, **kwargs)
return async_parser(*args, **kwargs)
A processor module that asynchronously renames or copies fields in an item. Args: item (dict): The entry to process kwargs (dict): The keyword arguments passed to the wrapper Kwargs: conf (dict): The pipe configuration. Must contain the key 'rule'. rule (dict): can be either a dict or list of dicts. Must contain the key 'field'. field (str): The item attribute to rename newval (str): The new item attribute name (default: None). If blank, the field will be deleted. copy (bool): Copy the item attribute instead of renaming it (default: False) Returns: Deferred: twisted.internet.defer.Deferred item with renamed content Examples: >>> from riko.bado import react >>> from riko.bado.mock import FakeReactor >>> >>> def run(reactor): ... callback = lambda x: print(next(x)['greeting'] == 'hello world') ... conf = {'rule': {'field': 'content', 'newval': 'greeting'}} ... d = async_pipe({'content': 'hello world'}, conf=conf) ... return d.addCallbacks(callback, logger.error) >>> >>> try: ... react(run, _reactor=FakeReactor()) ... except SystemExit: ... pass ... True
A processor module that asynchronously renames or copies fields in an item.
[ "A", "processor", "module", "that", "asynchronously", "renames", "or", "copies", "fields", "in", "an", "item", "." ]
def async_pipe(*args, **kwargs): """A processor module that asynchronously renames or copies fields in an item. Args: item (dict): The entry to process kwargs (dict): The keyword arguments passed to the wrapper Kwargs: conf (dict): The pipe configuration. Must contain the key 'rule'. rule (dict): can be either a dict or list of dicts. Must contain the key 'field'. field (str): The item attribute to rename newval (str): The new item attribute name (default: None). If blank, the field will be deleted. copy (bool): Copy the item attribute instead of renaming it (default: False) Returns: Deferred: twisted.internet.defer.Deferred item with renamed content Examples: >>> from riko.bado import react >>> from riko.bado.mock import FakeReactor >>> >>> def run(reactor): ... callback = lambda x: print(next(x)['greeting'] == 'hello world') ... conf = {'rule': {'field': 'content', 'newval': 'greeting'}} ... d = async_pipe({'content': 'hello world'}, conf=conf) ... return d.addCallbacks(callback, logger.error) >>> >>> try: ... react(run, _reactor=FakeReactor()) ... except SystemExit: ... pass ... True """ return async_parser(*args, **kwargs)
[ "def", "async_pipe", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "async_parser", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/nerevu/riko/blob/4d27102b605b8b4050ba566d5e0895d8d5f8b09a/riko/modules/rename.py#L127-L168
AndreaCensi/contracts
bf6dac0a2867214d66f560257c773ba30d4a3136
src/contracts/utils.py
python
raise_desc
(etype, msg, args_first=False, **kwargs)
Example: raise_desc(ValueError, "I don't know", a=a, b=b)
Example: raise_desc(ValueError, "I don't know", a=a, b=b)
[ "Example", ":", "raise_desc", "(", "ValueError", "I", "don", "t", "know", "a", "=", "a", "b", "=", "b", ")" ]
def raise_desc(etype, msg, args_first=False, **kwargs): """ Example: raise_desc(ValueError, "I don't know", a=a, b=b) """ assert isinstance(msg, six.string_types), type(msg) s1 = msg if kwargs: s2 = format_obs(kwargs) else: s2 = "" if args_first: s = s2 + "\n" + s1 else: s = s1 + "\n" + s2 raise etype(s)
[ "def", "raise_desc", "(", "etype", ",", "msg", ",", "args_first", "=", "False", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "msg", ",", "six", ".", "string_types", ")", ",", "type", "(", "msg", ")", "s1", "=", "msg", "if", "kwar...
https://github.com/AndreaCensi/contracts/blob/bf6dac0a2867214d66f560257c773ba30d4a3136/src/contracts/utils.py#L213-L231
PyHDI/veriloggen
2382d200deabf59cfcfd741f5eba371010aaf2bb
veriloggen/core/vtypes.py
python
Pointer._type_check_var
(self, var)
[]
def _type_check_var(self, var): if not isinstance(var, (_Variable, Scope, Pointer)): raise TypeError( 'var of Pointer must be Variable, not %s' % str(type(var)))
[ "def", "_type_check_var", "(", "self", ",", "var", ")", ":", "if", "not", "isinstance", "(", "var", ",", "(", "_Variable", ",", "Scope", ",", "Pointer", ")", ")", ":", "raise", "TypeError", "(", "'var of Pointer must be Variable, not %s'", "%", "str", "(", ...
https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/core/vtypes.py#L1582-L1585
ctxis/CAPE
dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82
utils/rooter.py
python
init_rttable
(rt_table, interface)
Initialise routing table for this interface using routes from main table.
Initialise routing table for this interface using routes from main table.
[ "Initialise", "routing", "table", "for", "this", "interface", "using", "routes", "from", "main", "table", "." ]
def init_rttable(rt_table, interface): """Initialise routing table for this interface using routes from main table.""" if rt_table in ["local", "main", "default"]: return stdout, _ = run(settings.ip, "route", "list", "dev", interface) for line in stdout.split("\n"): args = ["route", "add"] + [x for x in line.split(" ") if x] args += ["dev", interface, "table", rt_table] run(settings.ip, *args)
[ "def", "init_rttable", "(", "rt_table", ",", "interface", ")", ":", "if", "rt_table", "in", "[", "\"local\"", ",", "\"main\"", ",", "\"default\"", "]", ":", "return", "stdout", ",", "_", "=", "run", "(", "settings", ".", "ip", ",", "\"route\"", ",", "\...
https://github.com/ctxis/CAPE/blob/dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82/utils/rooter.py#L85-L95
presslabs/gitfs
12886ec5b9c7e103bfcab0cd37a8333873382fae
gitfs/utils/args.py
python
Args.check_args
(self, args)
return args
[]
def check_args(self, args): # check allow_other and allow_root if args.allow_other: args.allow_root = False else: args.allow_root = True # check log_level if args.debug: args.log_level = "debug" # setup logging if args.log != "syslog": if args.log in ("-", "/dev/stdout"): handler = StreamHandler(sys.stdout) else: handler = TimedRotatingFileHandler(args.log, when="midnight") handler.setFormatter( Formatter( fmt="%(asctime)s %(threadName)s: " "%(message)s", datefmt="%B-%d-%Y %H:%M:%S", ) ) else: if sys.platform == "darwin": handler = SysLogHandler(address="/var/run/syslog") else: handler = SysLogHandler(address="/dev/log") logger_fmt = ( "GitFS on {mount_point} [%(process)d]: %(threadName)s: " "%(message)s".format(mount_point=args.mount_point) ) handler.setFormatter(Formatter(fmt=logger_fmt)) if args.sentry_dsn != "": from raven.conf import setup_logging from raven.handlers.logging import SentryHandler sentry_handler = SentryHandler( args.sentry_dsn, tags={ "owner": args.user, "remote": args.remote_url, "mountpoint": args.mount_point, }, ) sentry_handler.setLevel("ERROR") setup_logging(sentry_handler) log.addHandler(sentry_handler) handler.setLevel(args.log_level.upper()) log.setLevel(args.log_level.upper()) log.addHandler(handler) # set cache size lru_cache.maxsize = args.cache_size # return absolute repository's path args.repo_path = os.path.abspath(args.repo_path) return args
[ "def", "check_args", "(", "self", ",", "args", ")", ":", "# check allow_other and allow_root", "if", "args", ".", "allow_other", ":", "args", ".", "allow_root", "=", "False", "else", ":", "args", ".", "allow_root", "=", "True", "# check log_level", "if", "args...
https://github.com/presslabs/gitfs/blob/12886ec5b9c7e103bfcab0cd37a8333873382fae/gitfs/utils/args.py#L78-L138
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/ipaddress.py
python
_BaseV6._parse_hextet
(self, hextet_str)
return int(hextet_str, 16)
Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF].
Convert an IPv6 hextet string into an integer.
[ "Convert", "an", "IPv6", "hextet", "string", "into", "an", "integer", "." ]
def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16)
[ "def", "_parse_hextet", "(", "self", ",", "hextet_str", ")", ":", "# Whitelist the characters, since int() allows a lot of bizarre stuff.", "if", "not", "self", ".", "_HEX_DIGITS", ".", "issuperset", "(", "hextet_str", ")", ":", "raise", "ValueError", "(", "\"Only hex d...
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/ipaddress.py#L1633-L1656
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-50/fabmetheus_utilities/settings.py
python
getSelectedRadioPlugin
( names, radioPlugins )
return radioPlugin[0]
Get the selected radio button if it exists, None otherwise.
Get the selected radio button if it exists, None otherwise.
[ "Get", "the", "selected", "radio", "button", "if", "it", "exists", "None", "otherwise", "." ]
def getSelectedRadioPlugin( names, radioPlugins ): "Get the selected radio button if it exists, None otherwise." for radioPlugin in radioPlugins: if radioPlugin.value: return radioPlugin for name in names: for radioPlugin in radioPlugins: if radioPlugin.name == name: radioPlugin.value = True return radioPlugin print('this should never happen, no getSelectedRadioPlugin in settings') print(names) return radioPlugin[0]
[ "def", "getSelectedRadioPlugin", "(", "names", ",", "radioPlugins", ")", ":", "for", "radioPlugin", "in", "radioPlugins", ":", "if", "radioPlugin", ".", "value", ":", "return", "radioPlugin", "for", "name", "in", "names", ":", "for", "radioPlugin", "in", "radi...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/fabmetheus_utilities/settings.py#L343-L355
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/smtplib.py
python
SMTP.docmd
(self, cmd, args="")
return self.getreply()
Send a command, and return its response code.
Send a command, and return its response code.
[ "Send", "a", "command", "and", "return", "its", "response", "code", "." ]
def docmd(self, cmd, args=""): """Send a command, and return its response code.""" self.putcmd(cmd, args) return self.getreply()
[ "def", "docmd", "(", "self", ",", "cmd", ",", "args", "=", "\"\"", ")", ":", "self", ".", "putcmd", "(", "cmd", ",", "args", ")", "return", "self", ".", "getreply", "(", ")" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/smtplib.py#L422-L425
AwesomeTTS/awesometts-anki-addon
c7c2c94479b610b9767ec44cdbb825002bc0c2b7
awesometts/service/base.py
python
Service.path_workaround
(self, text)
return False
If running on Windows and the given text cannot be represented purely with ASCII characters, returns a path to a temporary text file that may be used to feed a service binary. Returns False otherwise.
If running on Windows and the given text cannot be represented purely with ASCII characters, returns a path to a temporary text file that may be used to feed a service binary.
[ "If", "running", "on", "Windows", "and", "the", "given", "text", "cannot", "be", "represented", "purely", "with", "ASCII", "characters", "returns", "a", "path", "to", "a", "temporary", "text", "file", "that", "may", "be", "used", "to", "feed", "a", "servic...
def path_workaround(self, text): """ If running on Windows and the given text cannot be represented purely with ASCII characters, returns a path to a temporary text file that may be used to feed a service binary. Returns False otherwise. """ if self.IS_WINDOWS: try: text.encode('ascii') except UnicodeError: return self.path_input(text) return False
[ "def", "path_workaround", "(", "self", ",", "text", ")", ":", "if", "self", ".", "IS_WINDOWS", ":", "try", ":", "text", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeError", ":", "return", "self", ".", "path_input", "(", "text", ")", "return", ...
https://github.com/AwesomeTTS/awesometts-anki-addon/blob/c7c2c94479b610b9767ec44cdbb825002bc0c2b7/awesometts/service/base.py#L729-L745
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tileset_generation/minecraft.py
python
Model._dequeue
(self)
Pop the top function from the internal queue and call it.
Pop the top function from the internal queue and call it.
[ "Pop", "the", "top", "function", "from", "the", "internal", "queue", "and", "call", "it", "." ]
def _dequeue(self): """ Pop the top function from the internal queue and call it. """ func, args = self.queue.popleft() func(*args)
[ "def", "_dequeue", "(", "self", ")", ":", "func", ",", "args", "=", "self", ".", "queue", ".", "popleft", "(", ")", "func", "(", "*", "args", ")" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tileset_generation/minecraft.py#L379-L384
gkrizek/bash-lambda-layer
703b0ade8174022d44779d823172ab7ac33a5505
bin/botocore/utils.py
python
parse_to_aware_datetime
(value)
return datetime_obj
Converted the passed in value to a datetime object with tzinfo. This function can be used to normalize all timestamp inputs. This function accepts a number of different types of inputs, but will always return a datetime.datetime object with time zone information. The input param ``value`` can be one of several types: * A datetime object (both naive and aware) * An integer representing the epoch time (can also be a string of the integer, i.e '0', instead of 0). The epoch time is considered to be UTC. * An iso8601 formatted timestamp. This does not need to be a complete timestamp, it can contain just the date portion without the time component. The returned value will be a datetime object that will have tzinfo. If no timezone info was provided in the input value, then UTC is assumed, not local time.
Converted the passed in value to a datetime object with tzinfo.
[ "Converted", "the", "passed", "in", "value", "to", "a", "datetime", "object", "with", "tzinfo", "." ]
def parse_to_aware_datetime(value): """Converted the passed in value to a datetime object with tzinfo. This function can be used to normalize all timestamp inputs. This function accepts a number of different types of inputs, but will always return a datetime.datetime object with time zone information. The input param ``value`` can be one of several types: * A datetime object (both naive and aware) * An integer representing the epoch time (can also be a string of the integer, i.e '0', instead of 0). The epoch time is considered to be UTC. * An iso8601 formatted timestamp. This does not need to be a complete timestamp, it can contain just the date portion without the time component. The returned value will be a datetime object that will have tzinfo. If no timezone info was provided in the input value, then UTC is assumed, not local time. """ # This is a general purpose method that handles several cases of # converting the provided value to a string timestamp suitable to be # serialized to an http request. It can handle: # 1) A datetime.datetime object. if isinstance(value, datetime.datetime): datetime_obj = value else: # 2) A string object that's formatted as a timestamp. # We document this as being an iso8601 timestamp, although # parse_timestamp is a bit more flexible. datetime_obj = parse_timestamp(value) if datetime_obj.tzinfo is None: # I think a case would be made that if no time zone is provided, # we should use the local time. However, to restore backwards # compat, the previous behavior was to assume UTC, which is # what we're going to do here. datetime_obj = datetime_obj.replace(tzinfo=tzutc()) else: datetime_obj = datetime_obj.astimezone(tzutc()) return datetime_obj
[ "def", "parse_to_aware_datetime", "(", "value", ")", ":", "# This is a general purpose method that handles several cases of", "# converting the provided value to a string timestamp suitable to be", "# serialized to an http request. It can handle:", "# 1) A datetime.datetime object.", "if", "is...
https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/botocore/utils.py#L572-L614
CLUEbenchmark/CLUE
5bd39732734afecb490cf18a5212e692dbf2c007
baselines/models/roberta_wwm_large_ext/create_pretraining_data.py
python
write_instance_to_example_files
(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files)
Create TF example files from `TrainingInstance`s.
Create TF example files from `TrainingInstance`s.
[ "Create", "TF", "example", "files", "from", "TrainingInstance", "s", "." ]
def write_instance_to_example_files(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files): """Create TF example files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append(tf.python_io.TFRecordWriter(output_file)) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) input_mask = [1] * len(input_ids) segment_ids = list(instance.segment_ids) assert len(input_ids) <= max_seq_length while len(input_ids) < max_seq_length: input_ids.append(0) input_mask.append(0) segment_ids.append(0) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels) masked_lm_weights = [1.0] * len(masked_lm_ids) while len(masked_lm_positions) < max_predictions_per_seq: masked_lm_positions.append(0) masked_lm_ids.append(0) masked_lm_weights.append(0.0) next_sentence_label = 1 if instance.is_random_next else 0 features = collections.OrderedDict() features["input_ids"] = create_int_feature(input_ids) features["input_mask"] = create_int_feature(input_mask) features["segment_ids"] = create_int_feature(segment_ids) features["masked_lm_positions"] = create_int_feature(masked_lm_positions) features["masked_lm_ids"] = create_int_feature(masked_lm_ids) features["masked_lm_weights"] = create_float_feature(masked_lm_weights) features["next_sentence_labels"] = create_int_feature([next_sentence_label]) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) writers[writer_index].write(tf_example.SerializeToString()) writer_index = (writer_index + 1) % len(writers) total_written += 1 if inst_index < 20: tf.logging.info("*** Example ***") tf.logging.info("tokens: %s" % " ".join( [tokenization.printable_text(x) for x in instance.tokens])) for feature_name in features.keys(): feature = features[feature_name] values = [] if feature.int64_list.value: values = feature.int64_list.value elif feature.float_list.value: values = feature.float_list.value tf.logging.info( "%s: %s" % (feature_name, " ".join([str(x) for x in values]))) for writer in writers: writer.close() tf.logging.info("Wrote %d total instances", total_written)
[ "def", "write_instance_to_example_files", "(", "instances", ",", "tokenizer", ",", "max_seq_length", ",", "max_predictions_per_seq", ",", "output_files", ")", ":", "writers", "=", "[", "]", "for", "output_file", "in", "output_files", ":", "writers", ".", "append", ...
https://github.com/CLUEbenchmark/CLUE/blob/5bd39732734afecb490cf18a5212e692dbf2c007/baselines/models/roberta_wwm_large_ext/create_pretraining_data.py#L96-L166
IntelAI/models
1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c
models/object_detection/pytorch/ssd-resnet34/training/cpu/coco.py
python
COCO.annToRLE
(self, ann)
return rle
Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array)
Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array)
[ "Convert", "annotation", "which", "can", "be", "polygons", "uncompressed", "RLE", "to", "RLE", ".", ":", "return", ":", "binary", "mask", "(", "numpy", "2D", "array", ")" ]
def annToRLE(self, ann): """ Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array) """ t = self.imgs[ann['image_id']] h, w = t['height'], t['width'] segm = ann['segmentation'] if type(segm) == list: # polygon -- a single object might consist of multiple parts # we merge all parts into one mask rle code rles = maskUtils.frPyObjects(segm, h, w) rle = maskUtils.merge(rles) elif type(segm['counts']) == list: # uncompressed RLE rle = maskUtils.frPyObjects(segm, h, w) else: # rle rle = ann['segmentation'] return rle
[ "def", "annToRLE", "(", "self", ",", "ann", ")", ":", "t", "=", "self", ".", "imgs", "[", "ann", "[", "'image_id'", "]", "]", "h", ",", "w", "=", "t", "[", "'height'", "]", ",", "t", "[", "'width'", "]", "segm", "=", "ann", "[", "'segmentation'...
https://github.com/IntelAI/models/blob/1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c/models/object_detection/pytorch/ssd-resnet34/training/cpu/coco.py#L406-L425
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/utils/platform_.py
python
Platform.editor
(self)
return self._editor()
Returns the system default text editor.
Returns the system default text editor.
[ "Returns", "the", "system", "default", "text", "editor", "." ]
def editor(self): """Returns the system default text editor.""" return self._editor()
[ "def", "editor", "(", "self", ")", ":", "return", "self", ".", "_editor", "(", ")" ]
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/utils/platform_.py#L83-L85
MyDuerOS/DuerOS-Python-Client
71b3482f00cfb11b6d6d8a33065cb33e05ba339e
sdk/interface/audio_player.py
python
AudioPlayer.__init__
(self, dueros, player)
类初始化 :param dueros:DuerOS核心模块实例 :param player: 播放器实例(平台相关)
类初始化 :param dueros:DuerOS核心模块实例 :param player: 播放器实例(平台相关)
[ "类初始化", ":", "param", "dueros", ":", "DuerOS核心模块实例", ":", "param", "player", ":", "播放器实例(平台相关)" ]
def __init__(self, dueros, player): ''' 类初始化 :param dueros:DuerOS核心模块实例 :param player: 播放器实例(平台相关) ''' self.namespace = 'ai.dueros.device_interface.audio_player' self.dueros = dueros self.token = '' self.state = 'IDLE' self.player = player self.player.add_callback('eos', self.__playback_finished) self.player.add_callback('error', self.__playback_failed)
[ "def", "__init__", "(", "self", ",", "dueros", ",", "player", ")", ":", "self", ".", "namespace", "=", "'ai.dueros.device_interface.audio_player'", "self", ".", "dueros", "=", "dueros", "self", ".", "token", "=", "''", "self", ".", "state", "=", "'IDLE'", ...
https://github.com/MyDuerOS/DuerOS-Python-Client/blob/71b3482f00cfb11b6d6d8a33065cb33e05ba339e/sdk/interface/audio_player.py#L19-L32
Amulet-Team/Amulet-Map-Editor
e99619ba6aab855173b9f7c203455944ab97f89a
versioneer.py
python
run_command
(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None)
return stdout, p.returncode
Call the given command(s).
Call the given command(s).
[ "Call", "the", "given", "command", "(", "s", ")", "." ]
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen( [c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), ) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode
[ "def", "run_command", "(", "commands", ",", "args", ",", "cwd", "=", "None", ",", "verbose", "=", "False", ",", "hide_stderr", "=", "False", ",", "env", "=", "None", ")", ":", "assert", "isinstance", "(", "commands", ",", "list", ")", "p", "=", "None...
https://github.com/Amulet-Team/Amulet-Map-Editor/blob/e99619ba6aab855173b9f7c203455944ab97f89a/versioneer.py#L391-L427
carbonblack/cbapi-python
24d677ffd99aee911c2c76ecb5528e4e9320c7cc
src/cbapi/response/models.py
python
SensorPaginatedQuery.where
(self, new_query)
return nq
[]
def where(self, new_query): if self._query: raise ApiError("Cannot have multiple 'where' clauses") nq = self._clone() field, value = new_query.split(':', 1) nq._query = {} nq._query[field] = value nq._full_init = False for k, v in iteritems(nq._query): if k not in SensorQuery.valid_field_names: nq._query = {} raise ValueError("Field name must be one of: {0:s}".format(", ".join(SensorQuery.valid_field_names))) return nq
[ "def", "where", "(", "self", ",", "new_query", ")", ":", "if", "self", ".", "_query", ":", "raise", "ApiError", "(", "\"Cannot have multiple 'where' clauses\"", ")", "nq", "=", "self", ".", "_clone", "(", ")", "field", ",", "value", "=", "new_query", ".", ...
https://github.com/carbonblack/cbapi-python/blob/24d677ffd99aee911c2c76ecb5528e4e9320c7cc/src/cbapi/response/models.py#L549-L564
bayespy/bayespy
0e6e6130c888a4295cc9421d61d4ad27b2960ebb
bayespy/inference/vmp/transformations.py
python
RotateGaussianARD.bound
(self, R, logdet=None, inv=None, Q=None)
return self._compute_bound(R, logdet=logdet, inv=inv, Q=Q, gradient=True)
[]
def bound(self, R, logdet=None, inv=None, Q=None): return self._compute_bound(R, logdet=logdet, inv=inv, Q=Q, gradient=True)
[ "def", "bound", "(", "self", ",", "R", ",", "logdet", "=", "None", ",", "inv", "=", "None", ",", "Q", "=", "None", ")", ":", "return", "self", ".", "_compute_bound", "(", "R", ",", "logdet", "=", "logdet", ",", "inv", "=", "inv", ",", "Q", "=",...
https://github.com/bayespy/bayespy/blob/0e6e6130c888a4295cc9421d61d4ad27b2960ebb/bayespy/inference/vmp/transformations.py#L1095-L1100
scanny/python-pptx
71d1ca0b2b3b9178d64cdab565e8503a25a54e0b
pptx/oxml/shapes/groupshape.py
python
CT_GroupShape.add_freeform_sp
(self, x, y, cx, cy)
return sp
Append a new freeform `p:sp` with specified position and size.
Append a new freeform `p:sp` with specified position and size.
[ "Append", "a", "new", "freeform", "p", ":", "sp", "with", "specified", "position", "and", "size", "." ]
def add_freeform_sp(self, x, y, cx, cy): """Append a new freeform `p:sp` with specified position and size.""" shape_id = self._next_shape_id name = "Freeform %d" % (shape_id - 1,) sp = CT_Shape.new_freeform_sp(shape_id, name, x, y, cx, cy) self.insert_element_before(sp, "p:extLst") return sp
[ "def", "add_freeform_sp", "(", "self", ",", "x", ",", "y", ",", "cx", ",", "cy", ")", ":", "shape_id", "=", "self", ".", "_next_shape_id", "name", "=", "\"Freeform %d\"", "%", "(", "shape_id", "-", "1", ",", ")", "sp", "=", "CT_Shape", ".", "new_free...
https://github.com/scanny/python-pptx/blob/71d1ca0b2b3b9178d64cdab565e8503a25a54e0b/pptx/oxml/shapes/groupshape.py#L56-L62
IdentityPython/pysaml2
6badb32d212257bd83ffcc816f9b625f68281b47
src/saml2/__init__.py
python
SamlBase.loadd
(self, ava, base64encode=False)
return self
Sets attributes, children, extension elements and extension attributes of this element instance depending on what is in the given dictionary. If there are already values on properties those will be overwritten. If the keys in the dictionary does not correspond to known attributes/children/.. they are ignored. :param ava: The dictionary :param base64encode: Whether the values on attributes or texts on children shoule be base64encoded. :return: The instance
Sets attributes, children, extension elements and extension attributes of this element instance depending on what is in the given dictionary. If there are already values on properties those will be overwritten. If the keys in the dictionary does not correspond to known attributes/children/.. they are ignored.
[ "Sets", "attributes", "children", "extension", "elements", "and", "extension", "attributes", "of", "this", "element", "instance", "depending", "on", "what", "is", "in", "the", "given", "dictionary", ".", "If", "there", "are", "already", "values", "on", "properti...
def loadd(self, ava, base64encode=False): """ Sets attributes, children, extension elements and extension attributes of this element instance depending on what is in the given dictionary. If there are already values on properties those will be overwritten. If the keys in the dictionary does not correspond to known attributes/children/.. they are ignored. :param ava: The dictionary :param base64encode: Whether the values on attributes or texts on children shoule be base64encoded. :return: The instance """ for prop, _typ, _req in self.c_attributes.values(): if prop in ava: value = ava[prop] if isinstance(value, (bool, int)): setattr(self, prop, str(value)) else: setattr(self, prop, value) if "text" in ava: self.set_text(ava["text"], base64encode) for prop, klassdef in self.c_children.values(): # print("## %s, %s" % (prop, klassdef)) if prop in ava: # print("### %s" % ava[prop]) # means there can be a list of values if isinstance(klassdef, list): make_vals(ava[prop], klassdef[0], self, prop, base64encode=base64encode) else: cis = make_vals(ava[prop], klassdef, self, prop, True, base64encode) setattr(self, prop, cis) if "extension_elements" in ava: for item in ava["extension_elements"]: self.extension_elements.append(ExtensionElement( item["tag"]).loadd(item)) if "extension_attributes" in ava: for key, val in ava["extension_attributes"].items(): self.extension_attributes[key] = val return self
[ "def", "loadd", "(", "self", ",", "ava", ",", "base64encode", "=", "False", ")", ":", "for", "prop", ",", "_typ", ",", "_req", "in", "self", ".", "c_attributes", ".", "values", "(", ")", ":", "if", "prop", "in", "ava", ":", "value", "=", "ava", "...
https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/__init__.py#L777-L824
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/histogram/marker/_pattern.py
python
Pattern.solidity
(self)
return self["solidity"]
Sets the solidity of the pattern fill. Solidity is roughly the fraction of the area filled by the pattern. Solidity of 0 shows only the background color without pattern and solidty of 1 shows only the foreground color without pattern. The 'solidity' property is a number and may be specified as: - An int or float in the interval [0, 1] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray
Sets the solidity of the pattern fill. Solidity is roughly the fraction of the area filled by the pattern. Solidity of 0 shows only the background color without pattern and solidty of 1 shows only the foreground color without pattern. The 'solidity' property is a number and may be specified as: - An int or float in the interval [0, 1] - A tuple, list, or one-dimensional numpy array of the above
[ "Sets", "the", "solidity", "of", "the", "pattern", "fill", ".", "Solidity", "is", "roughly", "the", "fraction", "of", "the", "area", "filled", "by", "the", "pattern", ".", "Solidity", "of", "0", "shows", "only", "the", "background", "color", "without", "pa...
def solidity(self): """ Sets the solidity of the pattern fill. Solidity is roughly the fraction of the area filled by the pattern. Solidity of 0 shows only the background color without pattern and solidty of 1 shows only the foreground color without pattern. The 'solidity' property is a number and may be specified as: - An int or float in the interval [0, 1] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["solidity"]
[ "def", "solidity", "(", "self", ")", ":", "return", "self", "[", "\"solidity\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/histogram/marker/_pattern.py#L323-L338
idanr1986/cuckoo-droid
1350274639473d3d2b0ac740cae133ca53ab7444
analyzer/android/lib/api/androguard/dvm.py
python
TypeList.get_string
(self)
return ' '.join(i.get_string() for i in self.list)
Return the concatenation of all strings :rtype: string
Return the concatenation of all strings
[ "Return", "the", "concatenation", "of", "all", "strings" ]
def get_string(self) : """ Return the concatenation of all strings :rtype: string """ return ' '.join(i.get_string() for i in self.list)
[ "def", "get_string", "(", "self", ")", ":", "return", "' '", ".", "join", "(", "i", ".", "get_string", "(", ")", "for", "i", "in", "self", ".", "list", ")" ]
https://github.com/idanr1986/cuckoo-droid/blob/1350274639473d3d2b0ac740cae133ca53ab7444/analyzer/android/lib/api/androguard/dvm.py#L1095-L1101
fsspec/gcsfs
fd67c7d1b6ca9db83a0deadd1557470c37b0836a
gcsfs/dask_link.py
python
register
()
Backward compatibility
Backward compatibility
[ "Backward", "compatibility" ]
def register(): """ Backward compatibility """ pass
[ "def", "register", "(", ")", ":", "pass" ]
https://github.com/fsspec/gcsfs/blob/fd67c7d1b6ca9db83a0deadd1557470c37b0836a/gcsfs/dask_link.py#L1-L5
openstack/swift
b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100
swift/obj/diskfile.py
python
BaseDiskFileWriter.put
(self, metadata)
Finalize writing the file on disk. :param metadata: dictionary of metadata to be associated with the object
Finalize writing the file on disk.
[ "Finalize", "writing", "the", "file", "on", "disk", "." ]
def put(self, metadata): """ Finalize writing the file on disk. :param metadata: dictionary of metadata to be associated with the object """ raise NotImplementedError
[ "def", "put", "(", "self", ",", "metadata", ")", ":", "raise", "NotImplementedError" ]
https://github.com/openstack/swift/blob/b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100/swift/obj/diskfile.py#L1951-L1958
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/cards/bdf_sets.py
python
USET1.raw_fields
(self)
return list_fields
gets the "raw" card without any processing as a list for printing
gets the "raw" card without any processing as a list for printing
[ "gets", "the", "raw", "card", "without", "any", "processing", "as", "a", "list", "for", "printing" ]
def raw_fields(self): """gets the "raw" card without any processing as a list for printing""" list_fields = ['USET1', self.name, self.components] + collapse_thru(self.node_ids) return list_fields
[ "def", "raw_fields", "(", "self", ")", ":", "list_fields", "=", "[", "'USET1'", ",", "self", ".", "name", ",", "self", ".", "components", "]", "+", "collapse_thru", "(", "self", ".", "node_ids", ")", "return", "list_fields" ]
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/bdf_sets.py#L2182-L2185
phantomcyber/playbooks
9e850ecc44cb98c5dde53784744213a1ed5799bd
azure_new_user_census.py
python
save_user_artifacts
(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs)
return
[]
def save_user_artifacts(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs): phantom.debug('save_user_artifacts() called') #phantom.debug('Action: {0} {1}'.format(action['name'], ('SUCCEEDED' if success else 'FAILED'))) id_value = container.get('id', None) # collect data for 'save_user_artifacts' call filtered_results_data_1 = phantom.collect2(container=container, datapath=["filtered-data:match_users:condition_1:list_users_ms_graph:action_result.data.*.userPrincipalName", "filtered-data:match_users:condition_1:list_users_ms_graph:action_result.data.*.id", "filtered-data:match_users:condition_1:list_users_ms_graph:action_result.parameter.context.artifact_id"]) parameters = [] # build parameters list for 'save_user_artifacts' call for filtered_results_item_1 in filtered_results_data_1: if filtered_results_item_1[1]: parameters.append({ 'name': "New Azure User", 'label': "user", 'cef_name': "userPrincipalName", 'contains': "azure user principal name", 'cef_value': filtered_results_item_1[0], 'container_id': id_value, 'cef_dictionary': "", 'run_automation': False, 'source_data_identifier': filtered_results_item_1[1], # context (artifact id) is added to associate results with the artifact 'context': {'artifact_id': filtered_results_item_1[2]}, }) phantom.act(action="add artifact", parameters=parameters, assets=['phantom'], name="save_user_artifacts") return
[ "def", "save_user_artifacts", "(", "action", "=", "None", ",", "success", "=", "None", ",", "container", "=", "None", ",", "results", "=", "None", ",", "handle", "=", "None", ",", "filtered_artifacts", "=", "None", ",", "filtered_results", "=", "None", ","...
https://github.com/phantomcyber/playbooks/blob/9e850ecc44cb98c5dde53784744213a1ed5799bd/azure_new_user_census.py#L231-L262
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
pyrevitlib/pyrevit/versionmgr/updater.py
python
update_pyrevit
()
Update pyrevit and its extension repositories.
Update pyrevit and its extension repositories.
[ "Update", "pyrevit", "and", "its", "extension", "repositories", "." ]
def update_pyrevit(): """Update pyrevit and its extension repositories.""" if _check_connection(): third_party_updated = False pyrevit_updated = False pyrevit_has_coreupdates = has_core_updates() thirdparty_repos = get_thirdparty_ext_repos() logger.debug('List of thirdparty repos to be updated: %s', thirdparty_repos) # update third-party extensions first, one by one for repo_info in thirdparty_repos: logger.debug('Updating repo: %s', repo_info.directory) try: upped_repo_info = update_repo(repo_info) logger.info(':inbox_tray: Successfully updated: %s to %s', upped_repo_info.name, upped_repo_info.last_commit_hash[:7]) third_party_updated = True except Exception: logger.info('Can not update repo: %s (Run in debug to see why)', repo_info.name) # now update pyrevit repo and reload pyrevit_repo = versionmgr.get_pyrevit_repo() if pyrevit_repo: if not pyrevit_has_coreupdates: logger.debug('Updating pyrevit repo: %s', pyrevit_repo.directory) try: upped_pyrevit_repo_info = update_repo(pyrevit_repo) logger.info(':inbox_tray: Successfully updated: %s to %s', upped_pyrevit_repo_info.name, upped_pyrevit_repo_info.last_commit_hash[:7]) pyrevit_updated = True except Exception as err: logger.info('Can not update pyrevit repo ' '(Run in debug to see why) | %s', err) # perform upgrade tasks logger.info('Upgrading settings...') upgrade.upgrade_existing_pyrevit() if not pyrevit_has_coreupdates: if third_party_updated or pyrevit_updated: # now reload pyrevit from pyrevit.loader import sessionmgr sessionmgr.reload_pyrevit() else: logger.info('pyRevit and extensions seem to be up-to-date.') else: from pyrevit import script output = script.get_output() output.print_html(COREUPDATE_MESSAGE) logger.debug('Core updates. Skippin update and reload.') else: logger.warning('No internet access detected. Skipping update.')
[ "def", "update_pyrevit", "(", ")", ":", "if", "_check_connection", "(", ")", ":", "third_party_updated", "=", "False", "pyrevit_updated", "=", "False", "pyrevit_has_coreupdates", "=", "has_core_updates", "(", ")", "thirdparty_repos", "=", "get_thirdparty_ext_repos", "...
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/pyrevitlib/pyrevit/versionmgr/updater.py#L212-L267
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/ONE「一个」/workflow/workflow.py
python
Workflow.cachefile
(self, filename)
return os.path.join(self.cachedir, filename)
Return full path to ``filename`` within your workflow's :attr:`cache directory <Workflow.cachedir>`. :param filename: basename of file :type filename: ``unicode`` :returns: full path to file within cache directory :rtype: ``unicode``
Return full path to ``filename`` within your workflow's :attr:`cache directory <Workflow.cachedir>`.
[ "Return", "full", "path", "to", "filename", "within", "your", "workflow", "s", ":", "attr", ":", "cache", "directory", "<Workflow", ".", "cachedir", ">", "." ]
def cachefile(self, filename): """Return full path to ``filename`` within your workflow's :attr:`cache directory <Workflow.cachedir>`. :param filename: basename of file :type filename: ``unicode`` :returns: full path to file within cache directory :rtype: ``unicode`` """ return os.path.join(self.cachedir, filename)
[ "def", "cachefile", "(", "self", ",", "filename", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "cachedir", ",", "filename", ")" ]
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/ONE「一个」/workflow/workflow.py#L1423-L1434
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
research/object_detection/models/faster_rcnn_resnet_v1_feature_extractor.py
python
FasterRCNNResnet50FeatureExtractor.__init__
(self, is_training, first_stage_features_stride, batch_norm_trainable=False, reuse_weights=None, weight_decay=0.0, activation_fn=tf.nn.relu)
Constructor. Args: is_training: See base class. first_stage_features_stride: See base class. batch_norm_trainable: See base class. reuse_weights: See base class. weight_decay: See base class. activation_fn: See base class. Raises: ValueError: If `first_stage_features_stride` is not 8 or 16, or if `architecture` is not supported.
Constructor.
[ "Constructor", "." ]
def __init__(self, is_training, first_stage_features_stride, batch_norm_trainable=False, reuse_weights=None, weight_decay=0.0, activation_fn=tf.nn.relu): """Constructor. Args: is_training: See base class. first_stage_features_stride: See base class. batch_norm_trainable: See base class. reuse_weights: See base class. weight_decay: See base class. activation_fn: See base class. Raises: ValueError: If `first_stage_features_stride` is not 8 or 16, or if `architecture` is not supported. """ super(FasterRCNNResnet50FeatureExtractor, self).__init__('resnet_v1_50', resnet_v1.resnet_v1_50, is_training, first_stage_features_stride, batch_norm_trainable, reuse_weights, weight_decay, activation_fn)
[ "def", "__init__", "(", "self", ",", "is_training", ",", "first_stage_features_stride", ",", "batch_norm_trainable", "=", "False", ",", "reuse_weights", "=", "None", ",", "weight_decay", "=", "0.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ")",...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/object_detection/models/faster_rcnn_resnet_v1_feature_extractor.py#L184-L208
Scalsol/mega.pytorch
a6aa6e0537b82d70da94228100a51e6a53d98f82
mega_core/layers/dcn/deform_conv_func.py
python
ModulatedDeformConvFunction.forward
( ctx, input, offset, mask, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1 )
return output
[]
def forward( ctx, input, offset, mask, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1 ): ctx.stride = stride ctx.padding = padding ctx.dilation = dilation ctx.groups = groups ctx.deformable_groups = deformable_groups ctx.with_bias = bias is not None if not ctx.with_bias: bias = input.new_empty(1) # fake tensor if not input.is_cuda: raise NotImplementedError if weight.requires_grad or mask.requires_grad or offset.requires_grad \ or input.requires_grad: ctx.save_for_backward(input, offset, mask, weight, bias) output = input.new_empty( ModulatedDeformConvFunction._infer_shape(ctx, input, weight)) ctx._bufs = [input.new_empty(0), input.new_empty(0)] _C.modulated_deform_conv_forward( input, weight, bias, ctx._bufs[0], offset, mask, output, ctx._bufs[1], weight.shape[2], weight.shape[3], ctx.stride, ctx.stride, ctx.padding, ctx.padding, ctx.dilation, ctx.dilation, ctx.groups, ctx.deformable_groups, ctx.with_bias ) return output
[ "def", "forward", "(", "ctx", ",", "input", ",", "offset", ",", "mask", ",", "weight", ",", "bias", "=", "None", ",", "stride", "=", "1", ",", "padding", "=", "0", ",", "dilation", "=", "1", ",", "groups", "=", "1", ",", "deformable_groups", "=", ...
https://github.com/Scalsol/mega.pytorch/blob/a6aa6e0537b82d70da94228100a51e6a53d98f82/mega_core/layers/dcn/deform_conv_func.py#L153-L203
lykoss/lykos
7859cb530b66e782b3cc32f0d7d60d1c55d4fef5
src/hooks.py
python
mode_change
(cli, rawnick, chan, mode, *targets)
Update the channel and user modes whenever a mode change occurs. Ordering and meaning of arguments for a MODE change: 0 - The IRCClient instance (like everywhere else) 1 - The raw nick of the mode setter/actor 2 - The channel (target) of the mode change 3 - The mode changes * - The targets of the modes (if any) This takes care of properly updating all relevant users and the channel modes to make sure we remain internally consistent.
Update the channel and user modes whenever a mode change occurs.
[ "Update", "the", "channel", "and", "user", "modes", "whenever", "a", "mode", "change", "occurs", "." ]
def mode_change(cli, rawnick, chan, mode, *targets): """Update the channel and user modes whenever a mode change occurs. Ordering and meaning of arguments for a MODE change: 0 - The IRCClient instance (like everywhere else) 1 - The raw nick of the mode setter/actor 2 - The channel (target) of the mode change 3 - The mode changes * - The targets of the modes (if any) This takes care of properly updating all relevant users and the channel modes to make sure we remain internally consistent. """ if chan == users.Bot.nick: # we only see user modes set to ourselves users.Bot.modes.update(mode) return if "!" not in rawnick: # Only sync modes if a server changed modes because # 1) human ops probably know better # 2) other bots might start a fight over modes # 3) recursion; we see our own mode changes. evt = Event("sync_modes", {}) evt.dispatch() return actor = users.get(rawnick, allow_none=True) target = channels.add(chan, cli) target.queue("mode_change", {"mode": mode, "targets": targets}, (actor, target))
[ "def", "mode_change", "(", "cli", ",", "rawnick", ",", "chan", ",", "mode", ",", "*", "targets", ")", ":", "if", "chan", "==", "users", ".", "Bot", ".", "nick", ":", "# we only see user modes set to ourselves", "users", ".", "Bot", ".", "modes", ".", "up...
https://github.com/lykoss/lykos/blob/7859cb530b66e782b3cc32f0d7d60d1c55d4fef5/src/hooks.py#L424-L455
IBM/lale
b4d6829c143a4735b06083a0e6c70d2cca244162
lale/type_checking.py
python
validate_schema
(lhs: Any, super_schema: JSON_TYPE)
Validate that lhs is an instance of or a subschema of super_schema. Parameters ---------- lhs: value Left-hand side of instance or subschema check. super_schema: JSON schema Right-hand side of instance or subschema check. Raises ------ jsonschema.ValidationError The lhs was an invalid value for super_schema. SubschemaError The lhs had a schema that was not a subschema of super_schema.
Validate that lhs is an instance of or a subschema of super_schema.
[ "Validate", "that", "lhs", "is", "an", "instance", "of", "or", "a", "subschema", "of", "super_schema", "." ]
def validate_schema(lhs: Any, super_schema: JSON_TYPE): """Validate that lhs is an instance of or a subschema of super_schema. Parameters ---------- lhs: value Left-hand side of instance or subschema check. super_schema: JSON schema Right-hand side of instance or subschema check. Raises ------ jsonschema.ValidationError The lhs was an invalid value for super_schema. SubschemaError The lhs had a schema that was not a subschema of super_schema. """ from lale.settings import disable_data_schema_validation if disable_data_schema_validation: return True # If schema validation is disabled, always return as valid sub_schema: Optional[JSON_TYPE] import lale.datasets.data_schemas try: sub_schema = lale.datasets.data_schemas.to_schema(lhs) except ValueError: sub_schema = None if sub_schema is None: validate_schema_directly(lhs, super_schema) else: _validate_subschema(sub_schema, super_schema)
[ "def", "validate_schema", "(", "lhs", ":", "Any", ",", "super_schema", ":", "JSON_TYPE", ")", ":", "from", "lale", ".", "settings", "import", "disable_data_schema_validation", "if", "disable_data_schema_validation", ":", "return", "True", "# If schema validation is disa...
https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/type_checking.py#L257-L290
klmitch/turnstile
8fe9a359b45e505d3192ab193ecf9be177ab1a17
turnstile/limits.py
python
Limit.decode
(self, key)
return key.params
Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ValueError will be raised if this is not the case.
Given a bucket key, compute the parameters used to compute that key.
[ "Given", "a", "bucket", "key", "compute", "the", "parameters", "used", "to", "compute", "that", "key", "." ]
def decode(self, key): """ Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ValueError will be raised if this is not the case. """ # Parse the bucket key key = BucketKey.decode(key) # Make sure the uuids match if key.uuid != self.uuid: raise ValueError("%s is not a bucket corresponding to this limit" % key) return key.params
[ "def", "decode", "(", "self", ",", "key", ")", ":", "# Parse the bucket key", "key", "=", "BucketKey", ".", "decode", "(", "key", ")", "# Make sure the uuids match", "if", "key", ".", "uuid", "!=", "self", ".", "uuid", ":", "raise", "ValueError", "(", "\"%...
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L815-L835
pm4py/pm4py-core
7807b09a088b02199cd0149d724d0e28793971bf
pm4py/algo/decision_mining/algorithm.py
python
get_decision_tree
(log: EventLog, net: PetriNet, initial_marking: Marking, final_marking: Marking, decision_point=None, attributes=None, parameters: Optional[Dict[Union[str, Parameters], Any]] = None)
return dt, list(X.columns.values.tolist()), targets
Gets a decision tree classifier on a specific point of the model Parameters -------------- log Event log net Petri net initial_marking Initial marking final_marking Final marking decision_point Point of the process in which a decision happens: - if not specified, the method crashes, but provides a list of possible decision points - if specified, the method goes on and produce the decision tree attributes Attributes of the log. If not specified, then an automatic attribute selection is performed. parameters Parameters of the algorithm Returns --------------- clf Decision tree feature_names The names of the features classes The classes
Gets a decision tree classifier on a specific point of the model
[ "Gets", "a", "decision", "tree", "classifier", "on", "a", "specific", "point", "of", "the", "model" ]
def get_decision_tree(log: EventLog, net: PetriNet, initial_marking: Marking, final_marking: Marking, decision_point=None, attributes=None, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> Any: """ Gets a decision tree classifier on a specific point of the model Parameters -------------- log Event log net Petri net initial_marking Initial marking final_marking Final marking decision_point Point of the process in which a decision happens: - if not specified, the method crashes, but provides a list of possible decision points - if specified, the method goes on and produce the decision tree attributes Attributes of the log. If not specified, then an automatic attribute selection is performed. parameters Parameters of the algorithm Returns --------------- clf Decision tree feature_names The names of the features classes The classes """ from sklearn import tree if parameters is None: parameters = {} log = log_converter.apply(log, parameters=parameters) X, y, targets = apply(log, net, initial_marking, final_marking, decision_point=decision_point, attributes=attributes, parameters=parameters) dt = tree.DecisionTreeClassifier() dt = dt.fit(X, y) return dt, list(X.columns.values.tolist()), targets
[ "def", "get_decision_tree", "(", "log", ":", "EventLog", ",", "net", ":", "PetriNet", ",", "initial_marking", ":", "Marking", ",", "final_marking", ":", "Marking", ",", "decision_point", "=", "None", ",", "attributes", "=", "None", ",", "parameters", ":", "O...
https://github.com/pm4py/pm4py-core/blob/7807b09a088b02199cd0149d724d0e28793971bf/pm4py/algo/decision_mining/algorithm.py#L90-L134
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/lib-tk/Tkinter.py
python
Misc.configure
(self, cnf=None, **kw)
return self._configure('configure', cnf, kw)
Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys.
Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys.
[ "Configure", "resources", "of", "a", "widget", ".", "The", "values", "for", "resources", "are", "specified", "as", "keyword", "arguments", ".", "To", "get", "an", "overview", "about", "the", "allowed", "keyword", "arguments", "call", "the", "method", "keys", ...
def configure(self, cnf=None, **kw): """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys. """ return self._configure('configure', cnf, kw)
[ "def", "configure", "(", "self", ",", "cnf", "=", "None", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "_configure", "(", "'configure'", ",", "cnf", ",", "kw", ")" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/lib-tk/Tkinter.py#L1326-L1333
django/django
0a17666045de6739ae1c2ac695041823d5f827f7
django/contrib/sessions/backends/base.py
python
SessionBase._validate_session_key
(self, key)
return key and len(key) >= 8
Key must be truthy and at least 8 characters long. 8 characters is an arbitrary lower bound for some minimal key security.
Key must be truthy and at least 8 characters long. 8 characters is an arbitrary lower bound for some minimal key security.
[ "Key", "must", "be", "truthy", "and", "at", "least", "8", "characters", "long", ".", "8", "characters", "is", "an", "arbitrary", "lower", "bound", "for", "some", "minimal", "key", "security", "." ]
def _validate_session_key(self, key): """ Key must be truthy and at least 8 characters long. 8 characters is an arbitrary lower bound for some minimal key security. """ return key and len(key) >= 8
[ "def", "_validate_session_key", "(", "self", ",", "key", ")", ":", "return", "key", "and", "len", "(", "key", ")", ">=", "8" ]
https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/contrib/sessions/backends/base.py#L151-L156
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/site-packages/pip/_internal/utils/compat.py
python
str_to_display
(data, desc=None)
return decoded_data
For display or logging purposes, convert a bytes object (or text) to text (e.g. unicode in Python 2) safe for output. :param desc: An optional phrase describing the input data, for use in the log message if a warning is logged. Defaults to "Bytes object". This function should never error out and so can take a best effort approach. It is okay to be lossy if needed since the return value is just for display. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors.
For display or logging purposes, convert a bytes object (or text) to text (e.g. unicode in Python 2) safe for output.
[ "For", "display", "or", "logging", "purposes", "convert", "a", "bytes", "object", "(", "or", "text", ")", "to", "text", "(", "e", ".", "g", ".", "unicode", "in", "Python", "2", ")", "safe", "for", "output", "." ]
def str_to_display(data, desc=None): # type: (Union[bytes, Text], Optional[str]) -> Text """ For display or logging purposes, convert a bytes object (or text) to text (e.g. unicode in Python 2) safe for output. :param desc: An optional phrase describing the input data, for use in the log message if a warning is logged. Defaults to "Bytes object". This function should never error out and so can take a best effort approach. It is okay to be lossy if needed since the return value is just for display. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. """ if isinstance(data, text_type): return data # Otherwise, data is a bytes object (str in Python 2). # First, get the encoding we assume. This is the preferred # encoding for the locale, unless that is not found, or # it is ASCII, in which case assume UTF-8 encoding = locale.getpreferredencoding() if (not encoding) or codecs.lookup(encoding).name == "ascii": encoding = "utf-8" # Now try to decode the data - if we fail, warn the user and # decode with replacement. try: decoded_data = data.decode(encoding) except UnicodeDecodeError: if desc is None: desc = 'Bytes object' msg_format = '{} does not appear to be encoded as %s'.format(desc) logger.warning(msg_format, encoding) decoded_data = data.decode(encoding, errors=backslashreplace_decode) # Make sure we can print the output, by encoding it to the output # encoding with replacement of unencodable characters, and then # decoding again. # We use stderr's encoding because it's less likely to be # redirected and if we don't find an encoding we skip this # step (on the assumption that output is wrapped by something # that won't fail). # The double getattr is to deal with the possibility that we're # being called in a situation where sys.__stderr__ doesn't exist, # or doesn't have an encoding attribute. Neither of these cases # should occur in normal pip use, but there's no harm in checking # in case people use pip in (unsupported) unusual situations. output_encoding = getattr(getattr(sys, "__stderr__", None), "encoding", None) if output_encoding: output_encoded = decoded_data.encode( output_encoding, errors="backslashreplace" ) decoded_data = output_encoded.decode(output_encoding) return decoded_data
[ "def", "str_to_display", "(", "data", ",", "desc", "=", "None", ")", ":", "# type: (Union[bytes, Text], Optional[str]) -> Text", "if", "isinstance", "(", "data", ",", "text_type", ")", ":", "return", "data", "# Otherwise, data is a bytes object (str in Python 2).", "# Fir...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/site-packages/pip/_internal/utils/compat.py#L86-L149
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/segformer/modeling_segformer.py
python
SegformerDecodeHead.__init__
(self, config)
[]
def __init__(self, config): super().__init__(config) # linear layers which will unify the channel dimension of each of the encoder blocks to the same config.decoder_hidden_size mlps = [] for i in range(config.num_encoder_blocks): mlp = SegformerMLP(config, input_dim=config.hidden_sizes[i]) mlps.append(mlp) self.linear_c = nn.ModuleList(mlps) # the following 3 layers implement the ConvModule of the original implementation self.linear_fuse = nn.Conv2d( in_channels=config.decoder_hidden_size * config.num_encoder_blocks, out_channels=config.decoder_hidden_size, kernel_size=1, bias=False, ) self.batch_norm = nn.BatchNorm2d(config.decoder_hidden_size) self.activation = nn.ReLU() self.dropout = nn.Dropout(config.classifier_dropout_prob) self.classifier = nn.Conv2d(config.decoder_hidden_size, config.num_labels, kernel_size=1)
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "super", "(", ")", ".", "__init__", "(", "config", ")", "# linear layers which will unify the channel dimension of each of the encoder blocks to the same config.decoder_hidden_size", "mlps", "=", "[", "]", "for", "i...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/segformer/modeling_segformer.py#L644-L664
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/pip/_vendor/pyparsing.py
python
ParseResults.get
(self, key, defaultValue=None)
Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified. Similar to C{dict.get()}. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None
Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified.
[ "Returns", "named", "result", "matching", "the", "given", "key", "or", "if", "there", "is", "no", "such", "name", "then", "returns", "the", "given", "C", "{", "defaultValue", "}", "or", "C", "{", "None", "}", "if", "no", "C", "{", "defaultValue", "}", ...
def get(self, key, defaultValue=None): """ Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified. Similar to C{dict.get()}. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None """ if key in self: return self[key] else: return defaultValue
[ "def", "get", "(", "self", ",", "key", ",", "defaultValue", "=", "None", ")", ":", "if", "key", "in", "self", ":", "return", "self", "[", "key", "]", "else", ":", "return", "defaultValue" ]
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/pyparsing.py#L540-L560
pytorch/fairseq
1575f30dd0a9f7b3c499db0b4767aa4e9f79056c
fairseq/token_generation_constraints.py
python
ConstraintNode.token_counts
(self)
return token_counts
Returns a counter of the number of times each token is used in a constraint.
Returns a counter of the number of times each token is used in a constraint.
[ "Returns", "a", "counter", "of", "the", "number", "of", "times", "each", "token", "is", "used", "in", "a", "constraint", "." ]
def token_counts(self) -> Counter: """Returns a counter of the number of times each token is used in a constraint. """ token_counts = Counter() kids = list(self.children.values()) while len(kids) > 0: kid = kids.pop() token_counts[kid.id] += kid.num_constraints kids += list(kid.children.values()) return token_counts
[ "def", "token_counts", "(", "self", ")", "->", "Counter", ":", "token_counts", "=", "Counter", "(", ")", "kids", "=", "list", "(", "self", ".", "children", ".", "values", "(", ")", ")", "while", "len", "(", "kids", ")", ">", "0", ":", "kid", "=", ...
https://github.com/pytorch/fairseq/blob/1575f30dd0a9f7b3c499db0b4767aa4e9f79056c/fairseq/token_generation_constraints.py#L164-L175
mrjoes/tornadio2
c251c65b2f6921feafc72e39ece647cfe05e9909
tornadio2/sessioncontainer.py
python
SessionBase.on_delete
(self, forced)
Triggered when object was expired or deleted.
Triggered when object was expired or deleted.
[ "Triggered", "when", "object", "was", "expired", "or", "deleted", "." ]
def on_delete(self, forced): """Triggered when object was expired or deleted.""" pass
[ "def", "on_delete", "(", "self", ",", "forced", ")", ":", "pass" ]
https://github.com/mrjoes/tornadio2/blob/c251c65b2f6921feafc72e39ece647cfe05e9909/tornadio2/sessioncontainer.py#L70-L72
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_call_router_without_checks.py
python
ApiCallRouterWithoutChecks.DeleteCronJob
(self, args, context=None)
return api_cron.ApiDeleteCronJobHandler()
[]
def DeleteCronJob(self, args, context=None): return api_cron.ApiDeleteCronJobHandler()
[ "def", "DeleteCronJob", "(", "self", ",", "args", ",", "context", "=", "None", ")", ":", "return", "api_cron", ".", "ApiDeleteCronJobHandler", "(", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_call_router_without_checks.py#L300-L301
Answers4AWS/graffiti-monkey
2411924190c2a909b886dc374573c0f79093fed0
graffiti_monkey/core.py
python
GraffitiMonkey.propagate_tags
(self)
Propagates tags by copying them from EC2 instance to EBS volume, and then to snapshot
Propagates tags by copying them from EC2 instance to EBS volume, and then to snapshot
[ "Propagates", "tags", "by", "copying", "them", "from", "EC2", "instance", "to", "EBS", "volume", "and", "then", "to", "snapshot" ]
def propagate_tags(self): ''' Propagates tags by copying them from EC2 instance to EBS volume, and then to snapshot ''' volumes = [] if not self._novolumes: volumes = self.tag_volumes() volumes = { v.id: v for v in volumes } if not self._nosnapshots: self.tag_snapshots(volumes)
[ "def", "propagate_tags", "(", "self", ")", ":", "volumes", "=", "[", "]", "if", "not", "self", ".", "_novolumes", ":", "volumes", "=", "self", ".", "tag_volumes", "(", ")", "volumes", "=", "{", "v", ".", "id", ":", "v", "for", "v", "in", "volumes",...
https://github.com/Answers4AWS/graffiti-monkey/blob/2411924190c2a909b886dc374573c0f79093fed0/graffiti_monkey/core.py#L86-L97
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
pypy/tool/bench/htmlreport.py
python
Page.__init__
(self, perftable=None)
perftable is of type PerfTable
perftable is of type PerfTable
[ "perftable", "is", "of", "type", "PerfTable" ]
def __init__(self, perftable=None): """perftable is of type PerfTable""" self.perftable = perftable
[ "def", "__init__", "(", "self", ",", "perftable", "=", "None", ")", ":", "self", ".", "perftable", "=", "perftable" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/tool/bench/htmlreport.py#L26-L28
mrlesmithjr/Ansible
d44f0dc0d942bdf3bf7334b307e6048f0ee16e36
roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/urllib3/packages/ordered_dict.py
python
OrderedDict.pop
(self, key, default=__marker)
return default
od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
[ "od", ".", "pop", "(", "k", "[", "d", "]", ")", "-", ">", "v", "remove", "specified", "key", "and", "return", "the", "corresponding", "value", ".", "If", "key", "is", "not", "found", "d", "is", "returned", "if", "given", "otherwise", "KeyError", "is"...
def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] return result if default is self.__marker: raise KeyError(key) return default
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "__marker", ")", ":", "if", "key", "in", "self", ":", "result", "=", "self", "[", "key", "]", "del", "self", "[", "key", "]", "return", "result", "if", "default", "is", "self", ".", "__m...
https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/urllib3/packages/ordered_dict.py#L177-L188
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/python-openid-2.2.5/openid/consumer/consumer.py
python
SuccessResponse.getSignedNS
(self, ns_uri)
return msg_args
Get signed arguments from the response message. Return a dict of all arguments in the specified namespace. If any of the arguments are not signed, return None.
Get signed arguments from the response message. Return a dict of all arguments in the specified namespace. If any of the arguments are not signed, return None.
[ "Get", "signed", "arguments", "from", "the", "response", "message", ".", "Return", "a", "dict", "of", "all", "arguments", "in", "the", "specified", "namespace", ".", "If", "any", "of", "the", "arguments", "are", "not", "signed", "return", "None", "." ]
def getSignedNS(self, ns_uri): """Get signed arguments from the response message. Return a dict of all arguments in the specified namespace. If any of the arguments are not signed, return None. """ msg_args = self.message.getArgs(ns_uri) for key in msg_args.iterkeys(): if not self.isSigned(ns_uri, key): oidutil.log("SuccessResponse.getSignedNS: (%s, %s) not signed." % (ns_uri, key)) return None return msg_args
[ "def", "getSignedNS", "(", "self", ",", "ns_uri", ")", ":", "msg_args", "=", "self", ".", "message", ".", "getArgs", "(", "ns_uri", ")", "for", "key", "in", "msg_args", ".", "iterkeys", "(", ")", ":", "if", "not", "self", ".", "isSigned", "(", "ns_ur...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/python-openid-2.2.5/openid/consumer/consumer.py#L1773-L1786
cournape/Bento
37de23d784407a7c98a4a15770ffc570d5f32d70
bento/compat/inspect.py
python
isfunction
(object)
return isinstance(object, types.FunctionType)
Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined func_code code object containing compiled function bytecode func_defaults tuple of any default values for arguments func_doc (same as __doc__) func_globals global namespace in which this function was defined func_name (same as __name__)
Return true if the object is a user-defined function.
[ "Return", "true", "if", "the", "object", "is", "a", "user", "-", "defined", "function", "." ]
def isfunction(object): """Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined func_code code object containing compiled function bytecode func_defaults tuple of any default values for arguments func_doc (same as __doc__) func_globals global namespace in which this function was defined func_name (same as __name__)""" return isinstance(object, types.FunctionType)
[ "def", "isfunction", "(", "object", ")", ":", "return", "isinstance", "(", "object", ",", "types", ".", "FunctionType", ")" ]
https://github.com/cournape/Bento/blob/37de23d784407a7c98a4a15770ffc570d5f32d70/bento/compat/inspect.py#L49-L60
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/solvers/diophantine.py
python
is_solution_quad
(var, coeff, u, v)
return _mexpand(Subs(eq, (x, y), (u, v)).doit()) == 0
Check whether `(u, v)` is solution to the quadratic binary diophantine equation with the variable list ``var`` and coefficient dictionary ``coeff``. Not intended for use by normal users.
Check whether `(u, v)` is solution to the quadratic binary diophantine equation with the variable list ``var`` and coefficient dictionary ``coeff``.
[ "Check", "whether", "(", "u", "v", ")", "is", "solution", "to", "the", "quadratic", "binary", "diophantine", "equation", "with", "the", "variable", "list", "var", "and", "coefficient", "dictionary", "coeff", "." ]
def is_solution_quad(var, coeff, u, v): """ Check whether `(u, v)` is solution to the quadratic binary diophantine equation with the variable list ``var`` and coefficient dictionary ``coeff``. Not intended for use by normal users. """ x, y = var[:2] eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[Integer(1)] return _mexpand(Subs(eq, (x, y), (u, v)).doit()) == 0
[ "def", "is_solution_quad", "(", "var", ",", "coeff", ",", "u", ",", "v", ")", ":", "x", ",", "y", "=", "var", "[", ":", "2", "]", "eq", "=", "x", "**", "2", "*", "coeff", "[", "x", "**", "2", "]", "+", "x", "*", "y", "*", "coeff", "[", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/solvers/diophantine.py#L776-L788
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/src/gdata/books/service.py
python
BookService.edit_annotation
(self, item)
return self.Put(data=item, uri=item.GetEditLink().href, converter=books.Book.FromString)
Send an edited item, a books.Book instance, to the user's annotation feed. Note that whereas extra annotations in add_annotations, minus ratings which are immutable once set, are simply added to the item in the annotation feed, if an annotation has been removed from the item, sending an edit request will remove that annotation. This should not happen with add_annotation.
Send an edited item, a books.Book instance, to the user's annotation feed. Note that whereas extra annotations in add_annotations, minus ratings which are immutable once set, are simply added to the item in the annotation feed, if an annotation has been removed from the item, sending an edit request will remove that annotation. This should not happen with add_annotation.
[ "Send", "an", "edited", "item", "a", "books", ".", "Book", "instance", "to", "the", "user", "s", "annotation", "feed", ".", "Note", "that", "whereas", "extra", "annotations", "in", "add_annotations", "minus", "ratings", "which", "are", "immutable", "once", "...
def edit_annotation(self, item): """ Send an edited item, a books.Book instance, to the user's annotation feed. Note that whereas extra annotations in add_annotations, minus ratings which are immutable once set, are simply added to the item in the annotation feed, if an annotation has been removed from the item, sending an edit request will remove that annotation. This should not happen with add_annotation. """ return self.Put(data=item, uri=item.GetEditLink().href, converter=books.Book.FromString)
[ "def", "edit_annotation", "(", "self", ",", "item", ")", ":", "return", "self", ".", "Put", "(", "data", "=", "item", ",", "uri", "=", "item", ".", "GetEditLink", "(", ")", ".", "href", ",", "converter", "=", "books", ".", "Book", ".", "FromString", ...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/src/gdata/books/service.py#L215-L226
ahmetcemturan/SFACT
7576e29ba72b33e5058049b77b7b558875542747
fabmetheus_utilities/fabmetheus_tools/interpret_plugins/slc.py
python
SLCCarving.readFile
( self, fileName )
Read SLC and store the layers.
Read SLC and store the layers.
[ "Read", "SLC", "and", "store", "the", "layers", "." ]
def readFile( self, fileName ): "Read SLC and store the layers." self.fileName = fileName pslcfile = open( fileName, 'rb') readHeader( pslcfile ) pslcfile.read( 256 ) #Go past the 256 byte 3D Reserved Section. self.readTableEntry( pslcfile ) self.processContourLayers( pslcfile ) pslcfile.close() self.cornerMaximum = Vector3(-987654321.0, -987654321.0, self.maximumZ) self.cornerMinimum = Vector3(987654321.0, 987654321.0, self.minimumZ) for loopLayer in self.loopLayers: for loop in loopLayer.loops: for point in loop: pointVector3 = Vector3(point.real, point.imag, loopLayer.z) self.cornerMaximum.maximize(pointVector3) self.cornerMinimum.minimize(pointVector3) halfLayerThickness = 0.5 * self.layerHeight self.cornerMaximum.z += halfLayerThickness self.cornerMinimum.z -= halfLayerThickness
[ "def", "readFile", "(", "self", ",", "fileName", ")", ":", "self", ".", "fileName", "=", "fileName", "pslcfile", "=", "open", "(", "fileName", ",", "'rb'", ")", "readHeader", "(", "pslcfile", ")", "pslcfile", ".", "read", "(", "256", ")", "#Go past the 2...
https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/fabmetheus_utilities/fabmetheus_tools/interpret_plugins/slc.py#L138-L157
welliamcao/VManagePlatform
24c0abed03d420348f9cb048a36211380fbfdf8f
VManagePlatform/utils/vMConUtils.py
python
VMInstance.cleanInterfaceBandwidth
(self,instance,port)
清除流量限制
清除流量限制
[ "清除流量限制" ]
def cleanInterfaceBandwidth(self,instance,port): '''清除流量限制''' domXml = instance.XMLDesc(0) root = ElementTree.fromstring(domXml) try: for dev in root.findall('.//devices/'): if dev.tag == 'interface': for iter in dev: if iter.get('dev') == port: for iter in dev: if iter.tag == 'bandwidth':dev.remove(iter) domXml = ElementTree.tostring(root) except Exception,e: return {"status":"faild",'data':e} if self.defineXML(domXml):return {"status":"success",'data':None}
[ "def", "cleanInterfaceBandwidth", "(", "self", ",", "instance", ",", "port", ")", ":", "domXml", "=", "instance", ".", "XMLDesc", "(", "0", ")", "root", "=", "ElementTree", ".", "fromstring", "(", "domXml", ")", "try", ":", "for", "dev", "in", "root", ...
https://github.com/welliamcao/VManagePlatform/blob/24c0abed03d420348f9cb048a36211380fbfdf8f/VManagePlatform/utils/vMConUtils.py#L1604-L1618
dcramer/django-sphinx
0071d1cae5390d0ec8c669786ca3c7275abb6410
djangosphinx/utils/config.py
python
generate_source_for_model
(model_class, index=None, sphinx_params={})
return t.render(c)
Generates a source configmration for a model.
Generates a source configmration for a model.
[ "Generates", "a", "source", "configmration", "for", "a", "model", "." ]
def generate_source_for_model(model_class, index=None, sphinx_params={}): """Generates a source configmration for a model.""" t = _get_template('source.conf') def _the_tuple(f): return (f.__class__, f.column, getattr(f.rel, 'to', None), f.choices) valid_fields = [_the_tuple(f) for f in model_class._meta.fields if _is_sourcable_field(f)] table = model_class._meta.db_table if index is None: index = table params = get_source_context([table], index, valid_fields) params.update({ 'table_name': table, 'primary_key': model_class._meta.pk.column, }) params.update(sphinx_params) c = Context(params) return t.render(c)
[ "def", "generate_source_for_model", "(", "model_class", ",", "index", "=", "None", ",", "sphinx_params", "=", "{", "}", ")", ":", "t", "=", "_get_template", "(", "'source.conf'", ")", "def", "_the_tuple", "(", "f", ")", ":", "return", "(", "f", ".", "__c...
https://github.com/dcramer/django-sphinx/blob/0071d1cae5390d0ec8c669786ca3c7275abb6410/djangosphinx/utils/config.py#L118-L141
IBM/lale
b4d6829c143a4735b06083a0e6c70d2cca244162
lale/lib/aif360/util.py
python
_SymmetricDisparateImpact.__init__
(self, favorable_labels, protected_attributes, unfavorable_labels)
[]
def __init__(self, favorable_labels, protected_attributes, unfavorable_labels): self.disparate_impact_scorer = disparate_impact( favorable_labels, protected_attributes, unfavorable_labels )
[ "def", "__init__", "(", "self", ",", "favorable_labels", ",", "protected_attributes", ",", "unfavorable_labels", ")", ":", "self", ".", "disparate_impact_scorer", "=", "disparate_impact", "(", "favorable_labels", ",", "protected_attributes", ",", "unfavorable_labels", "...
https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/lib/aif360/util.py#L824-L827
interpretml/interpret-community
84d86b7514fd9812f1497329bf1c4c9fc864370e
python/interpret_community/common/base_explainer.py
python
LocalExplainer.__init__
(self, *args, **kwargs)
Initialize the LocalExplainer.
Initialize the LocalExplainer.
[ "Initialize", "the", "LocalExplainer", "." ]
def __init__(self, *args, **kwargs): """Initialize the LocalExplainer.""" super(LocalExplainer, self).__init__(*args, **kwargs) self._logger.debug('Initializing LocalExplainer')
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "LocalExplainer", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_logger", ".", "debug", "(", "'I...
https://github.com/interpretml/interpret-community/blob/84d86b7514fd9812f1497329bf1c4c9fc864370e/python/interpret_community/common/base_explainer.py#L44-L47
google/jax
bebe9845a873b3203f8050395255f173ba3bbb71
jax/_src/numpy/lax_numpy.py
python
_IndexUpdateRef.min
(self, values, indices_are_sorted=False, unique_indices=False, mode=None)
return scatter._scatter_update(self.array, self.index, values, lax.scatter_min, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode)
Pure equivalent of ``x[idx] = minimum(x[idx], y)``. Returns the value of ``x`` that would result from the NumPy-style :mod:indexed assignment <numpy.doc.indexing>` ``x[idx] = minimum(x[idx], y)``. See :mod:`jax.ops` for details.
Pure equivalent of ``x[idx] = minimum(x[idx], y)``.
[ "Pure", "equivalent", "of", "x", "[", "idx", "]", "=", "minimum", "(", "x", "[", "idx", "]", "y", ")", "." ]
def min(self, values, indices_are_sorted=False, unique_indices=False, mode=None): """Pure equivalent of ``x[idx] = minimum(x[idx], y)``. Returns the value of ``x`` that would result from the NumPy-style :mod:indexed assignment <numpy.doc.indexing>` ``x[idx] = minimum(x[idx], y)``. See :mod:`jax.ops` for details. """ return scatter._scatter_update(self.array, self.index, values, lax.scatter_min, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode)
[ "def", "min", "(", "self", ",", "values", ",", "indices_are_sorted", "=", "False", ",", "unique_indices", "=", "False", ",", "mode", "=", "None", ")", ":", "return", "scatter", ".", "_scatter_update", "(", "self", ".", "array", ",", "self", ".", "index",...
https://github.com/google/jax/blob/bebe9845a873b3203f8050395255f173ba3bbb71/jax/_src/numpy/lax_numpy.py#L7015-L7028
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/compute/drivers/upcloud.py
python
UpcloudDriver.list_nodes
(self)
return self._to_nodes(servers)
List nodes :return: List of node objects :rtype: ``list`` of :class:`Node`
List nodes
[ "List", "nodes" ]
def list_nodes(self): """ List nodes :return: List of node objects :rtype: ``list`` of :class:`Node` """ servers = [] for nid in self._node_ids(): response = self.connection.request("1.2/server/{0}".format(nid)) servers.append(response.object["server"]) return self._to_nodes(servers)
[ "def", "list_nodes", "(", "self", ")", ":", "servers", "=", "[", "]", "for", "nid", "in", "self", ".", "_node_ids", "(", ")", ":", "response", "=", "self", ".", "connection", ".", "request", "(", "\"1.2/server/{0}\"", ".", "format", "(", "nid", ")", ...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/upcloud.py#L200-L211
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/pprint.py
python
PrettyPrinter.format
(self, object, context, maxlevels, level)
return _safe_repr(object, context, maxlevels, level)
Format object for a specific context, returning a string and flags indicating whether the representation is 'readable' and whether the object represents a recursive construct.
Format object for a specific context, returning a string and flags indicating whether the representation is 'readable' and whether the object represents a recursive construct.
[ "Format", "object", "for", "a", "specific", "context", "returning", "a", "string", "and", "flags", "indicating", "whether", "the", "representation", "is", "readable", "and", "whether", "the", "object", "represents", "a", "recursive", "construct", "." ]
def format(self, object, context, maxlevels, level): """Format object for a specific context, returning a string and flags indicating whether the representation is 'readable' and whether the object represents a recursive construct. """ return _safe_repr(object, context, maxlevels, level)
[ "def", "format", "(", "self", ",", "object", ",", "context", ",", "maxlevels", ",", "level", ")", ":", "return", "_safe_repr", "(", "object", ",", "context", ",", "maxlevels", ",", "level", ")" ]
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/pprint.py#L237-L242
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_scale.py
python
Utils.filter_versions
(stdout)
return version_dict
filter the oc version output
filter the oc version output
[ "filter", "the", "oc", "version", "output" ]
def filter_versions(stdout): ''' filter the oc version output ''' version_dict = {} version_search = ['oc', 'openshift', 'kubernetes'] for line in stdout.strip().split('\n'): for term in version_search: if not line: continue if line.startswith(term): version_dict[term] = line.split()[-1] # horrible hack to get openshift version in Openshift 3.2 # By default "oc version in 3.2 does not return an "openshift" version if "openshift" not in version_dict: version_dict["openshift"] = version_dict["oc"] return version_dict
[ "def", "filter_versions", "(", "stdout", ")", ":", "version_dict", "=", "{", "}", "version_search", "=", "[", "'oc'", ",", "'openshift'", ",", "'kubernetes'", "]", "for", "line", "in", "stdout", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_scale.py#L1272-L1290
saltstack/halite
1eacc7e3f51b670573aecb8980661e0c5dbfa0f4
halite/bottle.py
python
ConfigDict.load_config
(self, filename)
return self
Load values from an *.ini style config file. If the config file contains sections, their names are used as namespaces for the values within. The two special sections ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix).
Load values from an *.ini style config file.
[ "Load", "values", "from", "an", "*", ".", "ini", "style", "config", "file", "." ]
def load_config(self, filename): ''' Load values from an *.ini style config file. If the config file contains sections, their names are used as namespaces for the values within. The two special sections ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix). ''' conf = ConfigParser() conf.read(filename) for section in conf.sections(): for key, value in conf.items(section): if section not in ('DEFAULT', 'bottle'): key = section + '.' + key self[key] = value return self
[ "def", "load_config", "(", "self", ",", "filename", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "filename", ")", "for", "section", "in", "conf", ".", "sections", "(", ")", ":", "for", "key", ",", "value", "in", "conf", ...
https://github.com/saltstack/halite/blob/1eacc7e3f51b670573aecb8980661e0c5dbfa0f4/halite/bottle.py#L2005-L2019
nschloe/quadpy
c4c076d8ddfa968486a2443a95e2fb3780dcde0f
src/quadpy/c2/_franke.py
python
franke_7
()
return rabinowitz_richter_1()
[]
def franke_7(): # DUP Noted as a duplicate in the original article return rabinowitz_richter_1()
[ "def", "franke_7", "(", ")", ":", "# DUP Noted as a duplicate in the original article", "return", "rabinowitz_richter_1", "(", ")" ]
https://github.com/nschloe/quadpy/blob/c4c076d8ddfa968486a2443a95e2fb3780dcde0f/src/quadpy/c2/_franke.py#L177-L179
Ha0Tang/AttentionGAN
68a478a944bb45d288d67f99fe110ddf087fd84d
models/attention_gan1_model.py
python
CycleGAN1Model.__init__
(self, opt)
Initialize the CycleGAN class. Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
Initialize the CycleGAN class. Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
[ "Initialize", "the", "CycleGAN", "class", ".", "Parameters", ":", "opt", "(", "Option", "class", ")", "--", "stores", "all", "the", "experiment", "flags", ";", "needs", "to", "be", "a", "subclass", "of", "BaseOptions" ]
def __init__(self, opt): """Initialize the CycleGAN class. Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseModel.__init__(self, opt) # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses> self.loss_names = ['D_A', 'G_A', 'cycle_A', 'idt_A', 'D_B', 'G_B', 'cycle_B', 'idt_B'] # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals> visual_names_A = ['real_A', 'fake_B', 'rec_A', 'o1_b', 'o2_b', 'o3_b', 'o4_b', 'o5_b', 'o6_b', 'o7_b', 'o8_b', 'o9_b', 'o10_b', 'a1_b', 'a2_b', 'a3_b', 'a4_b', 'a5_b', 'a6_b', 'a7_b', 'a8_b', 'a9_b', 'a10_b', 'i1_b', 'i2_b', 'i3_b', 'i4_b', 'i5_b', 'i6_b', 'i7_b', 'i8_b', 'i9_b', 'rec_A_o1', 'rec_A_o2', 'rec_A_o3', 'rec_A_o4', 'rec_A_o5', 'rec_A_o6', 'rec_A_o7', 'rec_A_o8', 'rec_A_o9', 'rec_A_o10', 'rec_A_a1', 'rec_A_a2', 'rec_A_a3', 'rec_A_a4', 'rec_A_a5', 'rec_A_a6', 'rec_A_a7', 'rec_A_a8', 'rec_A_a9', 'rec_A_a10', 'rec_A_i1', 'rec_A_i2', 'rec_A_i3', 'rec_A_i4', 'rec_A_i5', 'rec_A_i6', 'rec_A_i7', 'rec_A_i8', 'rec_A_i9'] visual_names_B = ['real_B', 'fake_A', 'rec_B', 'o1_a', 'o2_a', 'o3_a', 'o4_a', 'o5_a', 'o6_a', 'o7_a', 'o8_a', 'o9_a', 'o10_a', 'a1_a', 'a2_a', 'a3_a', 'a4_a', 'a5_a', 'a6_a', 'a7_a', 'a8_a', 'a9_a', 'a10_a', 'i1_a', 'i2_a', 'i3_a', 'i4_a', 'i5_a', 'i6_a', 'i7_a', 'i8_a', 'i9_a'] if self.isTrain and self.opt.lambda_identity > 0.0: # if identity loss is used, we also visualize idt_B=G_A(B) ad idt_A=G_A(B) visual_names_A.append('idt_B') visual_names_B.append('idt_A') self.visual_names = visual_names_A + visual_names_B # combine visualizations for A and B # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>. if self.isTrain: self.model_names = ['G_A', 'G_B', 'D_A', 'D_B'] else: # during test time, only load Gs self.model_names = ['G_A', 'G_B'] # define networks (both Generators and discriminators) # The naming is different from those used in the paper. # Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X) self.netG_A = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, 'our', opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids) self.netG_B = networks.define_G(opt.output_nc, opt.input_nc, opt.ngf, 'our', opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids) if self.isTrain: # define discriminators self.netD_A = networks.define_D(opt.output_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids) self.netD_B = networks.define_D(opt.input_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids) if self.isTrain: if opt.lambda_identity > 0.0: # only works when input and output images have the same number of channels assert(opt.input_nc == opt.output_nc) self.fake_A_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images self.fake_B_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images # define loss functions self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device) # define GAN loss. self.criterionCycle = torch.nn.L1Loss() self.criterionIdt = torch.nn.L1Loss() # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>. self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A.parameters(), self.netG_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999)) self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_A.parameters(), self.netD_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999)) self.optimizers.append(self.optimizer_G) self.optimizers.append(self.optimizer_D)
[ "def", "__init__", "(", "self", ",", "opt", ")", ":", "BaseModel", ".", "__init__", "(", "self", ",", "opt", ")", "# specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>", "self", ".", "loss_names", "=", "[", ...
https://github.com/Ha0Tang/AttentionGAN/blob/68a478a944bb45d288d67f99fe110ddf087fd84d/models/attention_gan1_model.py#L42-L97
YaoZeyuan/ZhihuHelp_archived
a0e4a7acd4512452022ce088fff2adc6f8d30195
src/lib/oauth/zhihu_oauth/client.py
python
ZhihuClient.is_login
(self)
return self._token is not None
:return: 是否已登录。但其实只是检查内部的 token 是否是 None。 :rtype: bool
:return: 是否已登录。但其实只是检查内部的 token 是否是 None。 :rtype: bool
[ ":", "return", ":", "是否已登录。但其实只是检查内部的", "token", "是否是", "None。", ":", "rtype", ":", "bool" ]
def is_login(self): """ :return: 是否已登录。但其实只是检查内部的 token 是否是 None。 :rtype: bool """ return self._token is not None
[ "def", "is_login", "(", "self", ")", ":", "return", "self", ".", "_token", "is", "not", "None" ]
https://github.com/YaoZeyuan/ZhihuHelp_archived/blob/a0e4a7acd4512452022ce088fff2adc6f8d30195/src/lib/oauth/zhihu_oauth/client.py#L265-L270
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/genesis.py
python
bootstrap
( platform, root, img_format="dir", fs_format="ext2", fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, )
Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static
Create an image for a specific platform.
[ "Create", "an", "image", "for", "a", "specific", "platform", "." ]
def bootstrap( platform, root, img_format="dir", fs_format="ext2", fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): """ Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static """ if img_format not in ("dir", "sparse"): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == "dir": # We can just use the root as the root if not __salt__["file.directory_exists"](root): try: __salt__["file.mkdir"](root) except Exception as exc: # pylint: disable=broad-except return {"Error": salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == "sparse": if not img_size: raise SaltInvocationError("An img_size must be specified for a sparse file") if not mount_dir: mount_dir = "/opt/salt-genesis.{}".format(uuid.uuid4()) __salt__["file.mkdir"](mount_dir, "root", "root", "755") __salt__["cmd.run"](("fallocate", "-l", img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__["cmd.run"]("losetup -f") log.debug("First loop device is %s", loop1) __salt__["cmd.run"]("losetup {} {}".format(loop1, root)) loop2 = __salt__["cmd.run"]("losetup -f") log.debug("Second loop device is %s", loop2) start = str(2048 * 2048) __salt__["cmd.run"]("losetup -o {} {} {}".format(start, loop2, loop1)) __salt__["mount.mount"](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ("rpm", "yum"): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == "deb": _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == "pacman": _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != "dir": blkinfo = __salt__["disk.blkid"](loop2) __salt__["file.replace"]( "{}/boot/grub/grub.cfg".format(mount_dir), "ad4103fa-d940-47ca-8506-301d8071d467", # This seems to be the default blkinfo[loop2]["UUID"], ) __salt__["mount.umount"](root) __salt__["cmd.run"]("losetup -d {}".format(loop2)) __salt__["cmd.run"]("losetup -d {}".format(loop1)) __salt__["file.rmdir"](mount_dir)
[ "def", "bootstrap", "(", "platform", ",", "root", ",", "img_format", "=", "\"dir\"", ",", "fs_format", "=", "\"ext2\"", ",", "fs_opts", "=", "None", ",", "arch", "=", "None", ",", "flavor", "=", "None", ",", "repo_url", "=", "None", ",", "static_qemu", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/genesis.py#L43-L216
Nexmo/nexmo-python
e4da747457c95c0dd3dfbcd86b0b0257042d01d5
src/nexmo/_internal.py
python
ApplicationV2.list_applications
(self, page_size=None, page=None)
return self._api_server.get( "/v2/applications", params=params, headers={"content-type": "application/json"}, )
List all applications for your account. Results are paged, so each page will need to be requested to see all applications. :param int page_size: The number of items in the page to be returned :param int page: The page number of the page to be returned.
List all applications for your account.
[ "List", "all", "applications", "for", "your", "account", "." ]
def list_applications(self, page_size=None, page=None): """ List all applications for your account. Results are paged, so each page will need to be requested to see all applications. :param int page_size: The number of items in the page to be returned :param int page: The page number of the page to be returned. """ params = _filter_none_values({"page_size": page_size, "page": page}) return self._api_server.get( "/v2/applications", params=params, headers={"content-type": "application/json"}, )
[ "def", "list_applications", "(", "self", ",", "page_size", "=", "None", ",", "page", "=", "None", ")", ":", "params", "=", "_filter_none_values", "(", "{", "\"page_size\"", ":", "page_size", ",", "\"page\"", ":", "page", "}", ")", "return", "self", ".", ...
https://github.com/Nexmo/nexmo-python/blob/e4da747457c95c0dd3dfbcd86b0b0257042d01d5/src/nexmo/_internal.py#L141-L156
novoid/Memacs
cc5b89a1da011a1ef08550e4da06c01881995b77
memacs/lib/orgproperty.py
python
OrgProperties.get_value_delete_but_add_for_hashing
(self, key)
return ret
see method name ;)
see method name ;)
[ "see", "method", "name", ";", ")" ]
def get_value_delete_but_add_for_hashing(self, key): """ see method name ;) """ ret = self.get_value(key) self.delete(key) self.add_data_for_hashing(ret) return ret
[ "def", "get_value_delete_but_add_for_hashing", "(", "self", ",", "key", ")", ":", "ret", "=", "self", ".", "get_value", "(", "key", ")", "self", ".", "delete", "(", "key", ")", "self", ".", "add_data_for_hashing", "(", "ret", ")", "return", "ret" ]
https://github.com/novoid/Memacs/blob/cc5b89a1da011a1ef08550e4da06c01881995b77/memacs/lib/orgproperty.py#L130-L137
ScottfreeLLC/AlphaPy
e6419cc811c2a3abc1ad522a85a888c8ef386056
alphapy/portfolio.py
python
update_portfolio
(p, pos, trade)
return p
r"""Update the portfolio positions. Parameters ---------- p : alphapy.Portfolio Portfolio holding the position. pos : alphapy.Position Position to update. trade : alphapy.Trade Trade for updating the position and portfolio. Returns ------- p : alphapy.Portfolio Portfolio with the revised position.
r"""Update the portfolio positions.
[ "r", "Update", "the", "portfolio", "positions", "." ]
def update_portfolio(p, pos, trade): r"""Update the portfolio positions. Parameters ---------- p : alphapy.Portfolio Portfolio holding the position. pos : alphapy.Position Position to update. trade : alphapy.Trade Trade for updating the position and portfolio. Returns ------- p : alphapy.Portfolio Portfolio with the revised position. """ # update position ppq = abs(pos.quantity) pos = update_position(pos, trade) cpq = abs(pos.quantity) npq = cpq - ppq # update portfolio p.date = trade.tdate multiplier = pos.multiplier cv = trade.price * multiplier * npq p.cash -= cv return p
[ "def", "update_portfolio", "(", "p", ",", "pos", ",", "trade", ")", ":", "# update position", "ppq", "=", "abs", "(", "pos", ".", "quantity", ")", "pos", "=", "update_position", "(", "pos", ",", "trade", ")", "cpq", "=", "abs", "(", "pos", ".", "quan...
https://github.com/ScottfreeLLC/AlphaPy/blob/e6419cc811c2a3abc1ad522a85a888c8ef386056/alphapy/portfolio.py#L599-L627
suavecode/SUAVE
4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5
trunk/SUAVE/Methods/Aerodynamics/AVL/create_avl_datastructure.py
python
populate_body_sections
(avl_body,suave_body)
return avl_body
Creates sections of body geometry and populates the AVL body data structure Assumptions: None Source: None Inputs: avl_wing.symmetric [boolean] avl_body.widths.maximum [meters] avl_body.heights.maximum [meters] suave_body.fineness.nose [meters] suave_body.fineness.tail [meters] avl_body.lengths.total [meters] avl_body.lengths.nose [meters] avl_body.lengths.tail [meters] Outputs: avl_body - aircraft body in AVL format [data stucture] Properties Used: N/A
Creates sections of body geometry and populates the AVL body data structure
[ "Creates", "sections", "of", "body", "geometry", "and", "populates", "the", "AVL", "body", "data", "structure" ]
def populate_body_sections(avl_body,suave_body): """ Creates sections of body geometry and populates the AVL body data structure Assumptions: None Source: None Inputs: avl_wing.symmetric [boolean] avl_body.widths.maximum [meters] avl_body.heights.maximum [meters] suave_body.fineness.nose [meters] suave_body.fineness.tail [meters] avl_body.lengths.total [meters] avl_body.lengths.nose [meters] avl_body.lengths.tail [meters] Outputs: avl_body - aircraft body in AVL format [data stucture] Properties Used: N/A """ symm = avl_body.symmetric semispan_h = avl_body.widths.maximum * 0.5 * (2 - symm) semispan_v = avl_body.heights.maximum * 0.5 origin = suave_body.origin[0] # Compute the curvature of the nose/tail given fineness ratio. Curvature is derived from general quadratic equation # This method relates the fineness ratio to the quadratic curve formula via a spline fit interpolation vec1 = [2 , 1.5, 1.2 , 1] vec2 = [1 ,1.57 , 3.2, 8] x = np.linspace(0,1,4) fuselage_nose_curvature = np.interp(np.interp(suave_body.fineness.nose,vec2,x), x , vec1) fuselage_tail_curvature = np.interp(np.interp(suave_body.fineness.tail,vec2,x), x , vec1) # Horizontal Sections of Fuselage if semispan_h != 0.0: width_array = np.linspace(-semispan_h, semispan_h, num=11,endpoint=True) for section_width in width_array: fuselage_h_section = Section() fuselage_h_section_cabin_length = avl_body.lengths.total - (avl_body.lengths.nose + avl_body.lengths.tail) fuselage_h_section_nose_length = ((1 - ((abs(section_width/semispan_h))**fuselage_nose_curvature ))**(1/fuselage_nose_curvature))*avl_body.lengths.nose fuselage_h_section_tail_length = ((1 - ((abs(section_width/semispan_h))**fuselage_tail_curvature ))**(1/fuselage_tail_curvature))*avl_body.lengths.tail fuselage_h_section_nose_origin = avl_body.lengths.nose - fuselage_h_section_nose_length fuselage_h_section.tag = 'fuselage_horizontal_section_at_' + str(section_width) + '_m' fuselage_h_section.origin = [ origin[0] + fuselage_h_section_nose_origin , origin[1] + section_width, origin[2]] fuselage_h_section.chord = fuselage_h_section_cabin_length + fuselage_h_section_nose_length + fuselage_h_section_tail_length avl_body.append_section(fuselage_h_section,'horizontal') # Vertical Sections of Fuselage if semispan_v != 0: height_array = np.linspace(-semispan_v, semispan_v, num=11,endpoint=True) for section_height in height_array : fuselage_v_section = Section() fuselage_v_section_cabin_length = avl_body.lengths.total - (avl_body.lengths.nose + avl_body.lengths.tail) fuselage_v_section_nose_length = ((1 - ((abs(section_height/semispan_v))**fuselage_nose_curvature ))**(1/fuselage_nose_curvature))*avl_body.lengths.nose fuselage_v_section_tail_length = ((1 - ((abs(section_height/semispan_v))**fuselage_tail_curvature ))**(1/fuselage_tail_curvature))*avl_body.lengths.tail fuselage_v_section_nose_origin = avl_body.lengths.nose - fuselage_v_section_nose_length fuselage_v_section.tag = 'fuselage_vertical_top_section_at_' + str(section_height) + '_m' fuselage_v_section.origin = [ origin[0] + fuselage_v_section_nose_origin, origin[1], origin[2] + section_height ] fuselage_v_section.chord = fuselage_v_section_cabin_length + fuselage_v_section_nose_length + fuselage_v_section_tail_length avl_body.append_section(fuselage_v_section,'vertical') return avl_body
[ "def", "populate_body_sections", "(", "avl_body", ",", "suave_body", ")", ":", "symm", "=", "avl_body", ".", "symmetric", "semispan_h", "=", "avl_body", ".", "widths", ".", "maximum", "*", "0.5", "*", "(", "2", "-", "symm", ")", "semispan_v", "=", "avl_bod...
https://github.com/suavecode/SUAVE/blob/4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5/trunk/SUAVE/Methods/Aerodynamics/AVL/create_avl_datastructure.py#L409-L477
steveKapturowski/tensorflow-rl
6dc58da69bad0349a646cfc94ea9c5d1eada8351
environments/emulator.py
python
Emulator.get_initial_state
(self)
return np.copy(self.screen_images_processed)
Get the initial state
Get the initial state
[ "Get", "the", "initial", "state" ]
def get_initial_state(self): """ Get the initial state """ self.new_game() for step in xrange(NR_IMAGES): reward, new_screen_image_rgb = self.action_repeat(0) self.screen_images_processed[:, :, step] = self.process_frame_pool() self.show_screen(new_screen_image_rgb) if self.is_terminal(): MAX_START_WAIT -= 1 return self.get_initial_state() return np.copy(self.screen_images_processed)
[ "def", "get_initial_state", "(", "self", ")", ":", "self", ".", "new_game", "(", ")", "for", "step", "in", "xrange", "(", "NR_IMAGES", ")", ":", "reward", ",", "new_screen_image_rgb", "=", "self", ".", "action_repeat", "(", "0", ")", "self", ".", "screen...
https://github.com/steveKapturowski/tensorflow-rl/blob/6dc58da69bad0349a646cfc94ea9c5d1eada8351/environments/emulator.py#L138-L148
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/fourwaysplitter.py
python
FourWaySplitter.SetAGWWindowStyleFlag
(self, agwStyle)
Sets the :class:`FourWaySplitter` window style flags. :param `agwStyle`: the AGW-specific window style. This can be a combination of the following bits: ================== =========== ================================================== Window Styles Hex Value Description ================== =========== ================================================== ``SP_NOSASH`` 0x10 No sash will be drawn on :class:`FourWaySplitter`. ``SP_LIVE_UPDATE`` 0x80 Don't draw XOR line but resize the child windows immediately. ``SP_3DBORDER`` 0x200 Draws a 3D effect border. ================== =========== ==================================================
Sets the :class:`FourWaySplitter` window style flags.
[ "Sets", "the", ":", "class", ":", "FourWaySplitter", "window", "style", "flags", "." ]
def SetAGWWindowStyleFlag(self, agwStyle): """ Sets the :class:`FourWaySplitter` window style flags. :param `agwStyle`: the AGW-specific window style. This can be a combination of the following bits: ================== =========== ================================================== Window Styles Hex Value Description ================== =========== ================================================== ``SP_NOSASH`` 0x10 No sash will be drawn on :class:`FourWaySplitter`. ``SP_LIVE_UPDATE`` 0x80 Don't draw XOR line but resize the child windows immediately. ``SP_3DBORDER`` 0x200 Draws a 3D effect border. ================== =========== ================================================== """ self._agwStyle = agwStyle self.Refresh()
[ "def", "SetAGWWindowStyleFlag", "(", "self", ",", "agwStyle", ")", ":", "self", ".", "_agwStyle", "=", "agwStyle", "self", ".", "Refresh", "(", ")" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/fourwaysplitter.py#L370-L387
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/cards/base_card.py
python
BaseCard.update_field
(self, n: int, value: Optional[Union[int, float, str]])
Updates a field based on it's field number. Parameters ---------- n : int the field number value : int/float/str/None the value to update the field to .. note:: This is dynamic if the card length changes. update_field can be used as follows to change the z coordinate of a node:: >>> nid = 1 >>> node = model.nodes[nid] >>> node.update_field(3, 0.1)
Updates a field based on it's field number.
[ "Updates", "a", "field", "based", "on", "it", "s", "field", "number", "." ]
def update_field(self, n: int, value: Optional[Union[int, float, str]]) -> None: """ Updates a field based on it's field number. Parameters ---------- n : int the field number value : int/float/str/None the value to update the field to .. note:: This is dynamic if the card length changes. update_field can be used as follows to change the z coordinate of a node:: >>> nid = 1 >>> node = model.nodes[nid] >>> node.update_field(3, 0.1) """ try: key_name = self._field_map[n] setattr(self, key_name, value) except KeyError: self._update_field_helper(n, value)
[ "def", "update_field", "(", "self", ",", "n", ":", "int", ",", "value", ":", "Optional", "[", "Union", "[", "int", ",", "float", ",", "str", "]", "]", ")", "->", "None", ":", "try", ":", "key_name", "=", "self", ".", "_field_map", "[", "n", "]", ...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/base_card.py#L143-L169
henkelis/sonospy
841f52010fd6e1e932d8f1a8896ad4e5a0667b8a
sonospy/brisa/upnp/control_point/service.py
python
Service.event_subscribe
(self, event_host, callback, cargo, auto_renew=True, renew_callback=None)
Subscribes for events. @param event_host: 2-tuple (host, port) with the event listener server. @param callback: callback @param cargo: callback parameters @param auto_renew: if True, the framework will automatically renew the subscription before it expires. If False, the program need to call event_renew method before the subscription timeout. @param renew_callback: renew callback. It will be used when auto_renew is True @type event_host: tuple @type callback: callable @type auto_renew: boolean @type renew_callback: callable
Subscribes for events.
[ "Subscribes", "for", "events", "." ]
def event_subscribe(self, event_host, callback, cargo, auto_renew=True, renew_callback=None): """ Subscribes for events. @param event_host: 2-tuple (host, port) with the event listener server. @param callback: callback @param cargo: callback parameters @param auto_renew: if True, the framework will automatically renew the subscription before it expires. If False, the program need to call event_renew method before the subscription timeout. @param renew_callback: renew callback. It will be used when auto_renew is True @type event_host: tuple @type callback: callable @type auto_renew: boolean @type renew_callback: callable """ if auto_renew: self._auto_renew_subs = AutoRenew(self, event_host, renew_callback, cargo) SubscribeRequest(self, event_host, callback, cargo)
[ "def", "event_subscribe", "(", "self", ",", "event_host", ",", "callback", ",", "cargo", ",", "auto_renew", "=", "True", ",", "renew_callback", "=", "None", ")", ":", "if", "auto_renew", ":", "self", ".", "_auto_renew_subs", "=", "AutoRenew", "(", "self", ...
https://github.com/henkelis/sonospy/blob/841f52010fd6e1e932d8f1a8896ad4e5a0667b8a/sonospy/brisa/upnp/control_point/service.py#L228-L249
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/networkx/classes/function.py
python
create_empty_copy
(G, with_data=True)
return H
Return a copy of the graph G with all of the edges removed. Parameters ---------- G : graph A NetworkX graph with_data : bool (default=True) Propagate Graph and Nodes data to the new graph. See Also ----- empty_graph
Return a copy of the graph G with all of the edges removed.
[ "Return", "a", "copy", "of", "the", "graph", "G", "with", "all", "of", "the", "edges", "removed", "." ]
def create_empty_copy(G, with_data=True): """Return a copy of the graph G with all of the edges removed. Parameters ---------- G : graph A NetworkX graph with_data : bool (default=True) Propagate Graph and Nodes data to the new graph. See Also ----- empty_graph """ H = G.fresh_copy() H.add_nodes_from(G.nodes(data=with_data)) if with_data: H.graph.update(G.graph) return H
[ "def", "create_empty_copy", "(", "G", ",", "with_data", "=", "True", ")", ":", "H", "=", "G", ".", "fresh_copy", "(", ")", "H", ".", "add_nodes_from", "(", "G", ".", "nodes", "(", "data", "=", "with_data", ")", ")", "if", "with_data", ":", "H", "."...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/networkx/classes/function.py#L512-L532
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/pdb.py
python
Pdb.do_retval
(self, arg)
retval Print the return value for the last return of a function.
retval Print the return value for the last return of a function.
[ "retval", "Print", "the", "return", "value", "for", "the", "last", "return", "of", "a", "function", "." ]
def do_retval(self, arg): """retval Print the return value for the last return of a function. """ if '__return__' in self.curframe_locals: self.message(repr(self.curframe_locals['__return__'])) else: self.error('Not yet returned!')
[ "def", "do_retval", "(", "self", ",", "arg", ")", ":", "if", "'__return__'", "in", "self", ".", "curframe_locals", ":", "self", ".", "message", "(", "repr", "(", "self", ".", "curframe_locals", "[", "'__return__'", "]", ")", ")", "else", ":", "self", "...
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/pdb.py#L1137-L1144
librosa/librosa
76029d35ce4c76a7475f07aab67fe2df3f73c25c
librosa/beat.py
python
tempo
( y=None, sr=22050, onset_envelope=None, hop_length=512, start_bpm=120, std_bpm=1.0, ac_size=8.0, max_tempo=320.0, aggregate=np.mean, prior=None, )
return np.take(bpms, best_period)
Estimate the tempo (beats per minute) Parameters ---------- y : np.ndarray [shape=(..., n)] or None audio time series. Multi-channel is supported. sr : number > 0 [scalar] sampling rate of the time series onset_envelope : np.ndarray [shape=(..., n)] pre-computed onset strength envelope hop_length : int > 0 [scalar] hop length of the time series start_bpm : float [scalar] initial guess of the BPM std_bpm : float > 0 [scalar] standard deviation of tempo distribution ac_size : float > 0 [scalar] length (in seconds) of the auto-correlation window max_tempo : float > 0 [scalar, optional] If provided, only estimate tempo below this threshold aggregate : callable [optional] Aggregation function for estimating global tempo. If `None`, then tempo is estimated independently for each frame. prior : scipy.stats.rv_continuous [optional] A prior distribution over tempo (in beats per minute). By default, a pseudo-log-normal prior is used. If given, ``start_bpm`` and ``std_bpm`` will be ignored. Returns ------- tempo : np.ndarray estimated tempo (beats per minute). If input is multi-channel, one tempo estimate per channel is provided. See Also -------- librosa.onset.onset_strength librosa.feature.tempogram Notes ----- This function caches at level 30. Examples -------- >>> # Estimate a static tempo >>> y, sr = librosa.load(librosa.ex('nutcracker'), duration=30) >>> onset_env = librosa.onset.onset_strength(y, sr=sr) >>> tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr) >>> tempo array([143.555]) >>> # Or a static tempo with a uniform prior instead >>> import scipy.stats >>> prior = scipy.stats.uniform(30, 300) # uniform over 30-300 BPM >>> utempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr, prior=prior) >>> utempo array([161.499]) >>> # Or a dynamic tempo >>> dtempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr, ... aggregate=None) >>> dtempo array([ 89.103, 89.103, 89.103, ..., 123.047, 123.047, 123.047]) >>> # Dynamic tempo with a proper log-normal prior >>> prior_lognorm = scipy.stats.lognorm(loc=np.log(120), scale=120, s=1) >>> dtempo_lognorm = librosa.beat.tempo(onset_envelope=onset_env, sr=sr, ... aggregate=None, ... prior=prior_lognorm) >>> dtempo_lognorm array([ 89.103, 89.103, 89.103, ..., 123.047, 123.047, 123.047]) Plot the estimated tempo against the onset autocorrelation >>> import matplotlib.pyplot as plt >>> # Convert to scalar >>> tempo = tempo.item() >>> utempo = utempo.item() >>> # Compute 2-second windowed autocorrelation >>> hop_length = 512 >>> ac = librosa.autocorrelate(onset_env, 2 * sr // hop_length) >>> freqs = librosa.tempo_frequencies(len(ac), sr=sr, ... hop_length=hop_length) >>> # Plot on a BPM axis. We skip the first (0-lag) bin. >>> fig, ax = plt.subplots() >>> ax.semilogx(freqs[1:], librosa.util.normalize(ac)[1:], ... label='Onset autocorrelation', base=2) >>> ax.axvline(tempo, 0, 1, alpha=0.75, linestyle='--', color='r', ... label='Tempo (default prior): {:.2f} BPM'.format(tempo)) >>> ax.axvline(utempo, 0, 1, alpha=0.75, linestyle=':', color='g', ... label='Tempo (uniform prior): {:.2f} BPM'.format(utempo)) >>> ax.set(xlabel='Tempo (BPM)', title='Static tempo estimation') >>> ax.grid(True) >>> ax.legend() Plot dynamic tempo estimates over a tempogram >>> fig, ax = plt.subplots() >>> tg = librosa.feature.tempogram(onset_envelope=onset_env, sr=sr, ... hop_length=hop_length) >>> librosa.display.specshow(tg, x_axis='time', y_axis='tempo', cmap='magma', ax=ax) >>> ax.plot(librosa.times_like(dtempo), dtempo, ... color='c', linewidth=1.5, label='Tempo estimate (default prior)') >>> ax.plot(librosa.times_like(dtempo_lognorm), dtempo_lognorm, ... color='c', linewidth=1.5, linestyle='--', ... label='Tempo estimate (lognorm prior)') >>> ax.set(title='Dynamic tempo estimation') >>> ax.legend()
Estimate the tempo (beats per minute)
[ "Estimate", "the", "tempo", "(", "beats", "per", "minute", ")" ]
def tempo( y=None, sr=22050, onset_envelope=None, hop_length=512, start_bpm=120, std_bpm=1.0, ac_size=8.0, max_tempo=320.0, aggregate=np.mean, prior=None, ): """Estimate the tempo (beats per minute) Parameters ---------- y : np.ndarray [shape=(..., n)] or None audio time series. Multi-channel is supported. sr : number > 0 [scalar] sampling rate of the time series onset_envelope : np.ndarray [shape=(..., n)] pre-computed onset strength envelope hop_length : int > 0 [scalar] hop length of the time series start_bpm : float [scalar] initial guess of the BPM std_bpm : float > 0 [scalar] standard deviation of tempo distribution ac_size : float > 0 [scalar] length (in seconds) of the auto-correlation window max_tempo : float > 0 [scalar, optional] If provided, only estimate tempo below this threshold aggregate : callable [optional] Aggregation function for estimating global tempo. If `None`, then tempo is estimated independently for each frame. prior : scipy.stats.rv_continuous [optional] A prior distribution over tempo (in beats per minute). By default, a pseudo-log-normal prior is used. If given, ``start_bpm`` and ``std_bpm`` will be ignored. Returns ------- tempo : np.ndarray estimated tempo (beats per minute). If input is multi-channel, one tempo estimate per channel is provided. See Also -------- librosa.onset.onset_strength librosa.feature.tempogram Notes ----- This function caches at level 30. Examples -------- >>> # Estimate a static tempo >>> y, sr = librosa.load(librosa.ex('nutcracker'), duration=30) >>> onset_env = librosa.onset.onset_strength(y, sr=sr) >>> tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr) >>> tempo array([143.555]) >>> # Or a static tempo with a uniform prior instead >>> import scipy.stats >>> prior = scipy.stats.uniform(30, 300) # uniform over 30-300 BPM >>> utempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr, prior=prior) >>> utempo array([161.499]) >>> # Or a dynamic tempo >>> dtempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr, ... aggregate=None) >>> dtempo array([ 89.103, 89.103, 89.103, ..., 123.047, 123.047, 123.047]) >>> # Dynamic tempo with a proper log-normal prior >>> prior_lognorm = scipy.stats.lognorm(loc=np.log(120), scale=120, s=1) >>> dtempo_lognorm = librosa.beat.tempo(onset_envelope=onset_env, sr=sr, ... aggregate=None, ... prior=prior_lognorm) >>> dtempo_lognorm array([ 89.103, 89.103, 89.103, ..., 123.047, 123.047, 123.047]) Plot the estimated tempo against the onset autocorrelation >>> import matplotlib.pyplot as plt >>> # Convert to scalar >>> tempo = tempo.item() >>> utempo = utempo.item() >>> # Compute 2-second windowed autocorrelation >>> hop_length = 512 >>> ac = librosa.autocorrelate(onset_env, 2 * sr // hop_length) >>> freqs = librosa.tempo_frequencies(len(ac), sr=sr, ... hop_length=hop_length) >>> # Plot on a BPM axis. We skip the first (0-lag) bin. >>> fig, ax = plt.subplots() >>> ax.semilogx(freqs[1:], librosa.util.normalize(ac)[1:], ... label='Onset autocorrelation', base=2) >>> ax.axvline(tempo, 0, 1, alpha=0.75, linestyle='--', color='r', ... label='Tempo (default prior): {:.2f} BPM'.format(tempo)) >>> ax.axvline(utempo, 0, 1, alpha=0.75, linestyle=':', color='g', ... label='Tempo (uniform prior): {:.2f} BPM'.format(utempo)) >>> ax.set(xlabel='Tempo (BPM)', title='Static tempo estimation') >>> ax.grid(True) >>> ax.legend() Plot dynamic tempo estimates over a tempogram >>> fig, ax = plt.subplots() >>> tg = librosa.feature.tempogram(onset_envelope=onset_env, sr=sr, ... hop_length=hop_length) >>> librosa.display.specshow(tg, x_axis='time', y_axis='tempo', cmap='magma', ax=ax) >>> ax.plot(librosa.times_like(dtempo), dtempo, ... color='c', linewidth=1.5, label='Tempo estimate (default prior)') >>> ax.plot(librosa.times_like(dtempo_lognorm), dtempo_lognorm, ... color='c', linewidth=1.5, linestyle='--', ... label='Tempo estimate (lognorm prior)') >>> ax.set(title='Dynamic tempo estimation') >>> ax.legend() """ if start_bpm <= 0: raise ParameterError("start_bpm must be strictly positive") win_length = core.time_to_frames(ac_size, sr=sr, hop_length=hop_length).item() tg = tempogram( y=y, sr=sr, onset_envelope=onset_envelope, hop_length=hop_length, win_length=win_length, ) # Eventually, we want this to work for time-varying tempo if aggregate is not None: tg = aggregate(tg, axis=-1, keepdims=True) # Get the BPM values for each bin, skipping the 0-lag bin bpms = core.tempo_frequencies(tg.shape[-2], hop_length=hop_length, sr=sr) # Weight the autocorrelation by a log-normal distribution if prior is None: logprior = -0.5 * ((np.log2(bpms) - np.log2(start_bpm)) / std_bpm) ** 2 else: logprior = prior.logpdf(bpms) # Kill everything above the max tempo if max_tempo is not None: max_idx = np.argmax(bpms < max_tempo) logprior[:max_idx] = -np.inf # explicit axis expansion logprior = util.expand_to(logprior, ndim=tg.ndim, axes=-2) # Get the maximum, weighted by the prior # Using log1p here for numerical stability best_period = np.argmax(np.log1p(1e6 * tg) + logprior, axis=-2) return np.take(bpms, best_period)
[ "def", "tempo", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "onset_envelope", "=", "None", ",", "hop_length", "=", "512", ",", "start_bpm", "=", "120", ",", "std_bpm", "=", "1.0", ",", "ac_size", "=", "8.0", ",", "max_tempo", "=", "320.0", ...
https://github.com/librosa/librosa/blob/76029d35ce4c76a7475f07aab67fe2df3f73c25c/librosa/beat.py#L213-L382
boston-dynamics/spot-sdk
5ffa12e6943a47323c7279d86e30346868755f52
python/bosdyn-client/src/bosdyn/client/command_line.py
python
GetImageCommand._run
(self, robot, options)
return True
Implementation of the command. Args: robot: Robot object on which to run the command. options: Parsed command-line arguments. Returns: True if successful, False if exceptions are caught.
Implementation of the command.
[ "Implementation", "of", "the", "command", "." ]
def _run(self, robot, options): """Implementation of the command. Args: robot: Robot object on which to run the command. options: Parsed command-line arguments. Returns: True if successful, False if exceptions are caught. """ image_requests = [ build_image_request(source_name, options.quality_percent) for source_name in options.source_name ] try: response = robot.ensure_client(options.service_name).get_image(image_requests) except UnknownImageSourceError: print('Requested image source "{}" does not exist. Available image sources:'.format( options.source_name)) _show_image_sources_list(robot, service_name=options.service_name) return False except ImageResponseError: print('Robot cannot generate the "{}" at this time. Retry the command.'.format( options.source_name)) return False # Save the image files in the correct format (jpeg, pgm for raw/rle). save_images_as_files(response) return True
[ "def", "_run", "(", "self", ",", "robot", ",", "options", ")", ":", "image_requests", "=", "[", "build_image_request", "(", "source_name", ",", "options", ".", "quality_percent", ")", "for", "source_name", "in", "options", ".", "source_name", "]", "try", ":"...
https://github.com/boston-dynamics/spot-sdk/blob/5ffa12e6943a47323c7279d86e30346868755f52/python/bosdyn-client/src/bosdyn/client/command_line.py#L1572-L1601
paulwinex/pw_MultiScriptEditor
e447e99f87cb07e238baf693b7e124e50efdbc51
multi_script_editor/managers/nuke/main.py
python
addAutoSaveDeleteFilter
(filter)
addAutoSaveDeleteFilter(filter) -> None Add a function to modify the autosave filename before Nuke attempts delete the autosave file. Look at rollingAutoSave.py in the nukescripts directory for an example of using the auto save filters. @param filter: A filter function. The first argument to the filter is the current autosave filename. This function should return the filename to delete or return None if no file should be deleted.
addAutoSaveDeleteFilter(filter) -> None
[ "addAutoSaveDeleteFilter", "(", "filter", ")", "-", ">", "None" ]
def addAutoSaveDeleteFilter(filter): """addAutoSaveDeleteFilter(filter) -> None Add a function to modify the autosave filename before Nuke attempts delete the autosave file. Look at rollingAutoSave.py in the nukescripts directory for an example of using the auto save filters. @param filter: A filter function. The first argument to the filter is the current autosave filename. This function should return the filename to delete or return None if no file should be deleted.""" pass
[ "def", "addAutoSaveDeleteFilter", "(", "filter", ")", ":", "pass" ]
https://github.com/paulwinex/pw_MultiScriptEditor/blob/e447e99f87cb07e238baf693b7e124e50efdbc51/multi_script_editor/managers/nuke/main.py#L4386-L4395
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/distutils/cmd.py
python
Command.make_file
(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1)
Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the command defined 'self.force', and it is true, then the command is unconditionally run -- does no timestamp checks.
Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the command defined 'self.force', and it is true, then the command is unconditionally run -- does no timestamp checks.
[ "Special", "case", "of", "execute", "()", "for", "operations", "that", "process", "one", "or", "more", "input", "files", "and", "generate", "one", "output", "file", ".", "Works", "just", "like", "execute", "()", "except", "the", "operation", "is", "skipped",...
def make_file(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1): """Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the command defined 'self.force', and it is true, then the command is unconditionally run -- does no timestamp checks. """ if skip_msg is None: skip_msg = "skipping %s (inputs unchanged)" % outfile # Allow 'infiles' to be a single string if isinstance(infiles, str): infiles = (infiles,) elif not isinstance(infiles, (list, tuple)): raise TypeError( "'infiles' must be a string, or a list or tuple of strings") if exec_msg is None: exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles)) # If 'outfile' must be regenerated (either because it doesn't # exist, is out-of-date, or the 'force' flag is true) then # perform the action that presumably regenerates it if self.force or dep_util.newer_group(infiles, outfile): self.execute(func, args, exec_msg, level) # Otherwise, print the "skip" message else: log.debug(skip_msg)
[ "def", "make_file", "(", "self", ",", "infiles", ",", "outfile", ",", "func", ",", "args", ",", "exec_msg", "=", "None", ",", "skip_msg", "=", "None", ",", "level", "=", "1", ")", ":", "if", "skip_msg", "is", "None", ":", "skip_msg", "=", "\"skipping...
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/distutils/cmd.py#L372-L402
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/idlelib/configDialog.py
python
ConfigDialog.PaintThemeSample
(self)
[]
def PaintThemeSample(self): if self.themeIsBuiltin.get(): #a default theme theme = self.builtinTheme.get() else: #a user theme theme = self.customTheme.get() for elementTitle in self.themeElements: element = self.themeElements[elementTitle][0] colours = idleConf.GetHighlight(theme, element) if element == 'cursor': #cursor sample needs special painting colours['background'] = idleConf.GetHighlight( theme, 'normal', fgBg='bg') #handle any unsaved changes to this theme if theme in self.changedItems['highlight']: themeDict = self.changedItems['highlight'][theme] if element + '-foreground' in themeDict: colours['foreground'] = themeDict[element + '-foreground'] if element + '-background' in themeDict: colours['background'] = themeDict[element + '-background'] self.textHighlightSample.tag_config(element, **colours) self.SetColourSample()
[ "def", "PaintThemeSample", "(", "self", ")", ":", "if", "self", ".", "themeIsBuiltin", ".", "get", "(", ")", ":", "#a default theme", "theme", "=", "self", ".", "builtinTheme", ".", "get", "(", ")", "else", ":", "#a user theme", "theme", "=", "self", "."...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/idlelib/configDialog.py#L916-L935
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/pens/reportLabPen.py
python
ReportLabPen._curveToOne
(self, p1, p2, p3)
[]
def _curveToOne(self, p1, p2, p3): (x1,y1) = p1 (x2,y2) = p2 (x3,y3) = p3 self.path.curveTo(x1, y1, x2, y2, x3, y3)
[ "def", "_curveToOne", "(", "self", ",", "p1", ",", "p2", ",", "p3", ")", ":", "(", "x1", ",", "y1", ")", "=", "p1", "(", "x2", ",", "y2", ")", "=", "p2", "(", "x3", ",", "y3", ")", "=", "p3", "self", ".", "path", ".", "curveTo", "(", "x1"...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/pens/reportLabPen.py#L26-L30
criteo/biggraphite
1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30
biggraphite/drivers/cassandra.py
python
_CassandraAccessor.delete_directory
(self, directory)
See bg_accessor.Accessor.
See bg_accessor.Accessor.
[ "See", "bg_accessor", ".", "Accessor", "." ]
def delete_directory(self, directory): """See bg_accessor.Accessor.""" super(_CassandraAccessor, self).delete_directory(directory) self._execute_metadata( DELETE_DIRECTORY_LATENCY, self.__delete_directory.with_params(directory) )
[ "def", "delete_directory", "(", "self", ",", "directory", ")", ":", "super", "(", "_CassandraAccessor", ",", "self", ")", ".", "delete_directory", "(", "directory", ")", "self", ".", "_execute_metadata", "(", "DELETE_DIRECTORY_LATENCY", ",", "self", ".", "__dele...
https://github.com/criteo/biggraphite/blob/1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30/biggraphite/drivers/cassandra.py#L1775-L1781
jmcgeheeiv/pyfakefs
197e3882749ef5fc12984ba6885023663ad4f883
pyfakefs/helpers.py
python
FakeStatResult.st_ctime
(self)
return ctime if self.use_float else int(ctime)
Return the creation time in seconds.
Return the creation time in seconds.
[ "Return", "the", "creation", "time", "in", "seconds", "." ]
def st_ctime(self) -> Union[int, float]: """Return the creation time in seconds.""" ctime = self._st_ctime_ns / 1e9 return ctime if self.use_float else int(ctime)
[ "def", "st_ctime", "(", "self", ")", "->", "Union", "[", "int", ",", "float", "]", ":", "ctime", "=", "self", ".", "_st_ctime_ns", "/", "1e9", "return", "ctime", "if", "self", ".", "use_float", "else", "int", "(", "ctime", ")" ]
https://github.com/jmcgeheeiv/pyfakefs/blob/197e3882749ef5fc12984ba6885023663ad4f883/pyfakefs/helpers.py#L207-L210
graphcore/examples
46d2b7687b829778369fc6328170a7b14761e5c6
applications/tensorflow/conformer/ipu_optimizer.py
python
AdamLossScalingOptimizer.__init__
(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-6, name="AdamLossScalingOptimizer", weights_dtype=tf.float16)
Constructs a AdamLossScalingOptimizer.
Constructs a AdamLossScalingOptimizer.
[ "Constructs", "a", "AdamLossScalingOptimizer", "." ]
def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-6, name="AdamLossScalingOptimizer", weights_dtype=tf.float16): """Constructs a AdamLossScalingOptimizer.""" super(AdamLossScalingOptimizer, self).__init__(False, name) self.learning_rate = tf.cast(learning_rate, dtype=weights_dtype) self.loss_scaling = loss_scaling self.beta_1 = beta_1 self.beta_2 = beta_2 self.epsilon = epsilon
[ "def", "__init__", "(", "self", ",", "learning_rate", ",", "loss_scaling", ",", "beta_1", "=", "0.9", ",", "beta_2", "=", "0.999", ",", "epsilon", "=", "1e-6", ",", "name", "=", "\"AdamLossScalingOptimizer\"", ",", "weights_dtype", "=", "tf", ".", "float16",...
https://github.com/graphcore/examples/blob/46d2b7687b829778369fc6328170a7b14761e5c6/applications/tensorflow/conformer/ipu_optimizer.py#L26-L41
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
official/vision/beta/projects/deepmac_maskrcnn/modeling/heads/instance_heads.py
python
DeepMaskHead.call
(self, inputs, training=None)
return mask_outputs
Forward pass of mask branch for the Mask-RCNN model. Args: inputs: A `list` of two tensors where inputs[0]: A `tf.Tensor` of shape [batch_size, num_instances, roi_height, roi_width, roi_channels], representing the ROI features. inputs[1]: A `tf.Tensor` of shape [batch_size, num_instances], representing the classes of the ROIs. training: A `bool` indicating whether it is in `training` mode. Returns: mask_outputs: A `tf.Tensor` of shape [batch_size, num_instances, roi_height * upsample_factor, roi_width * upsample_factor], representing the mask predictions.
Forward pass of mask branch for the Mask-RCNN model.
[ "Forward", "pass", "of", "mask", "branch", "for", "the", "Mask", "-", "RCNN", "model", "." ]
def call(self, inputs, training=None): """Forward pass of mask branch for the Mask-RCNN model. Args: inputs: A `list` of two tensors where inputs[0]: A `tf.Tensor` of shape [batch_size, num_instances, roi_height, roi_width, roi_channels], representing the ROI features. inputs[1]: A `tf.Tensor` of shape [batch_size, num_instances], representing the classes of the ROIs. training: A `bool` indicating whether it is in `training` mode. Returns: mask_outputs: A `tf.Tensor` of shape [batch_size, num_instances, roi_height * upsample_factor, roi_width * upsample_factor], representing the mask predictions. """ roi_features, roi_classes = inputs features_shape = tf.shape(roi_features) batch_size, num_rois, height, width, filters = ( features_shape[0], features_shape[1], features_shape[2], features_shape[3], features_shape[4]) if batch_size is None: batch_size = tf.shape(roi_features)[0] x = tf.reshape(roi_features, [-1, height, width, filters]) x = self._call_convnet_variant(x) x = self._deconv(x) x = self._deconv_bn(x) x = self._activation(x) logits = self._mask_regressor(x) mask_height = height * self._config_dict['upsample_factor'] mask_width = width * self._config_dict['upsample_factor'] if self._config_dict['class_agnostic']: logits = tf.reshape(logits, [-1, num_rois, mask_height, mask_width, 1]) else: logits = tf.reshape( logits, [-1, num_rois, mask_height, mask_width, self._config_dict['num_classes']]) batch_indices = tf.tile( tf.expand_dims(tf.range(batch_size), axis=1), [1, num_rois]) mask_indices = tf.tile( tf.expand_dims(tf.range(num_rois), axis=0), [batch_size, 1]) if self._config_dict['class_agnostic']: class_gather_indices = tf.zeros_like(roi_classes, dtype=tf.int32) else: class_gather_indices = tf.cast(roi_classes, dtype=tf.int32) gather_indices = tf.stack( [batch_indices, mask_indices, class_gather_indices], axis=2) mask_outputs = tf.gather_nd( tf.transpose(logits, [0, 1, 4, 2, 3]), gather_indices) return mask_outputs
[ "def", "call", "(", "self", ",", "inputs", ",", "training", "=", "None", ")", ":", "roi_features", ",", "roi_classes", "=", "inputs", "features_shape", "=", "tf", ".", "shape", "(", "roi_features", ")", "batch_size", ",", "num_rois", ",", "height", ",", ...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/vision/beta/projects/deepmac_maskrcnn/modeling/heads/instance_heads.py#L194-L254