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
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/site-packages/django/db/models/fields/__init__.py
python
Field.value_from_object
(self, obj)
return getattr(obj, self.attname)
Returns the value of this field in the given model instance.
Returns the value of this field in the given model instance.
[ "Returns", "the", "value", "of", "this", "field", "in", "the", "given", "model", "instance", "." ]
def value_from_object(self, obj): """ Returns the value of this field in the given model instance. """ return getattr(obj, self.attname)
[ "def", "value_from_object", "(", "self", ",", "obj", ")", ":", "return", "getattr", "(", "obj", ",", "self", ".", "attname", ")" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/db/models/fields/__init__.py#L489-L493
lyft/cartography
921a790d686c679ab5d8936b07e167fd424ee8d6
cartography/intel/okta/users.py
python
_load_okta_users
( neo4j_session: neo4j.Session, okta_org_id: str, user_list: List[Dict], okta_update_tag: int, )
Load Okta user information into the graph :param neo4j_session: session with neo4j server :param okta_org_id: oktat organization id :param user_list: list of users :param okta_update_tag: The timestamp value to set our new Neo4j resources with :return: Nothing
Load Okta user information into the graph :param neo4j_session: session with neo4j server :param okta_org_id: oktat organization id :param user_list: list of users :param okta_update_tag: The timestamp value to set our new Neo4j resources with :return: Nothing
[ "Load", "Okta", "user", "information", "into", "the", "graph", ":", "param", "neo4j_session", ":", "session", "with", "neo4j", "server", ":", "param", "okta_org_id", ":", "oktat", "organization", "id", ":", "param", "user_list", ":", "list", "of", "users", ":", "param", "okta_update_tag", ":", "The", "timestamp", "value", "to", "set", "our", "new", "Neo4j", "resources", "with", ":", "return", ":", "Nothing" ]
def _load_okta_users( neo4j_session: neo4j.Session, okta_org_id: str, user_list: List[Dict], okta_update_tag: int, ) -> None: """ Load Okta user information into the graph :param neo4j_session: session with neo4j server :param okta_org_id: oktat organization id :param user_list: list of users :param okta_update_tag: The timestamp value to set our new Neo4j resources with :return: Nothing """ ingest_statement = """ MATCH (org:OktaOrganization{id: {ORG_ID}}) WITH org UNWIND {USER_LIST} as user_data MERGE (new_user:OktaUser{id: user_data.id}) ON CREATE SET new_user.firstseen = timestamp() SET new_user.first_name = user_data.first_name, new_user.last_name = user_data.last_name, new_user.login = user_data.login, new_user.email = user_data.email, new_user.second_email = user_data.second_email, new_user.created = user_data.created, new_user.activated = user_data.activated, new_user.status_changed = user_data.status_changed, new_user.last_login = user_data.last_login, new_user.okta_last_updated = user_data.okta_last_updated, new_user.password_changed = user_data.password_changed, new_user.transition_to_status = user_data.transition_to_status, new_user.lastupdated = {okta_update_tag} WITH new_user, org MERGE (org)-[org_r:RESOURCE]->(new_user) ON CREATE SET org_r.firstseen = timestamp() SET org_r.lastupdated = {okta_update_tag} WITH new_user MERGE (h:Human{email: new_user.email}) ON CREATE SET new_user.firstseen = timestamp() SET h.lastupdated = {okta_update_tag} MERGE (h)-[r:IDENTITY_OKTA]->(new_user) ON CREATE SET new_user.firstseen = timestamp() SET h.lastupdated = {okta_update_tag} """ neo4j_session.run( ingest_statement, ORG_ID=okta_org_id, USER_LIST=user_list, okta_update_tag=okta_update_tag, )
[ "def", "_load_okta_users", "(", "neo4j_session", ":", "neo4j", ".", "Session", ",", "okta_org_id", ":", "str", ",", "user_list", ":", "List", "[", "Dict", "]", ",", "okta_update_tag", ":", "int", ",", ")", "->", "None", ":", "ingest_statement", "=", "\"\"\"\n MATCH (org:OktaOrganization{id: {ORG_ID}})\n WITH org\n UNWIND {USER_LIST} as user_data\n MERGE (new_user:OktaUser{id: user_data.id})\n ON CREATE SET new_user.firstseen = timestamp()\n SET new_user.first_name = user_data.first_name,\n new_user.last_name = user_data.last_name,\n new_user.login = user_data.login,\n new_user.email = user_data.email,\n new_user.second_email = user_data.second_email,\n new_user.created = user_data.created,\n new_user.activated = user_data.activated,\n new_user.status_changed = user_data.status_changed,\n new_user.last_login = user_data.last_login,\n new_user.okta_last_updated = user_data.okta_last_updated,\n new_user.password_changed = user_data.password_changed,\n new_user.transition_to_status = user_data.transition_to_status,\n new_user.lastupdated = {okta_update_tag}\n WITH new_user, org\n MERGE (org)-[org_r:RESOURCE]->(new_user)\n ON CREATE SET org_r.firstseen = timestamp()\n SET org_r.lastupdated = {okta_update_tag}\n WITH new_user\n MERGE (h:Human{email: new_user.email})\n ON CREATE SET new_user.firstseen = timestamp()\n SET h.lastupdated = {okta_update_tag}\n MERGE (h)-[r:IDENTITY_OKTA]->(new_user)\n ON CREATE SET new_user.firstseen = timestamp()\n SET h.lastupdated = {okta_update_tag}\n \"\"\"", "neo4j_session", ".", "run", "(", "ingest_statement", ",", "ORG_ID", "=", "okta_org_id", ",", "USER_LIST", "=", "user_list", ",", "okta_update_tag", "=", "okta_update_tag", ",", ")" ]
https://github.com/lyft/cartography/blob/921a790d686c679ab5d8936b07e167fd424ee8d6/cartography/intel/okta/users.py#L120-L170
pydicom/pynetdicom
f57d8214c82b63c8e76638af43ce331f584a80fa
pynetdicom/presentation.py
python
PresentationContext.context_id
(self, value: Optional[int])
Set the context's *ID* parameter. Parameters ---------- value : int An odd integer between 1 and 255 (inclusive).
Set the context's *ID* parameter.
[ "Set", "the", "context", "s", "*", "ID", "*", "parameter", "." ]
def context_id(self, value: Optional[int]) -> None: """Set the context's *ID* parameter. Parameters ---------- value : int An odd integer between 1 and 255 (inclusive). """ if value is not None and (not 1 <= value <= 255 or value % 2 == 0): raise ValueError( "'context_id' must be an odd integer between 1 and 255, inclusive" ) self._context_id = value
[ "def", "context_id", "(", "self", ",", "value", ":", "Optional", "[", "int", "]", ")", "->", "None", ":", "if", "value", "is", "not", "None", "and", "(", "not", "1", "<=", "value", "<=", "255", "or", "value", "%", "2", "==", "0", ")", ":", "raise", "ValueError", "(", "\"'context_id' must be an odd integer between 1 and 255, inclusive\"", ")", "self", ".", "_context_id", "=", "value" ]
https://github.com/pydicom/pynetdicom/blob/f57d8214c82b63c8e76638af43ce331f584a80fa/pynetdicom/presentation.py#L338-L351
frerich/clcache
cae73d8255d78db8ba11e23c51fd2c9a89e7475b
clcache/__main__.py
python
CompilerArtifactsRepository.removeEntry
(self, keyToBeRemoved)
[]
def removeEntry(self, keyToBeRemoved): compilerArtifactsDir = self.section(keyToBeRemoved).cacheEntryDir(keyToBeRemoved) rmtree(compilerArtifactsDir, ignore_errors=True)
[ "def", "removeEntry", "(", "self", ",", "keyToBeRemoved", ")", ":", "compilerArtifactsDir", "=", "self", ".", "section", "(", "keyToBeRemoved", ")", ".", "cacheEntryDir", "(", "keyToBeRemoved", ")", "rmtree", "(", "compilerArtifactsDir", ",", "ignore_errors", "=", "True", ")" ]
https://github.com/frerich/clcache/blob/cae73d8255d78db8ba11e23c51fd2c9a89e7475b/clcache/__main__.py#L423-L425
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
tokumx/datadog_checks/tokumx/vendor/bson/son.py
python
SON.to_dict
(self)
return transform_value(dict(self))
Convert a SON document to a normal Python dictionary instance. This is trickier than just *dict(...)* because it needs to be recursive.
Convert a SON document to a normal Python dictionary instance.
[ "Convert", "a", "SON", "document", "to", "a", "normal", "Python", "dictionary", "instance", "." ]
def to_dict(self): """Convert a SON document to a normal Python dictionary instance. This is trickier than just *dict(...)* because it needs to be recursive. """ def transform_value(value): if isinstance(value, list): return [transform_value(v) for v in value] elif isinstance(value, collections.Mapping): return dict([ (k, transform_value(v)) for k, v in iteritems(value)]) else: return value return transform_value(dict(self))
[ "def", "to_dict", "(", "self", ")", ":", "def", "transform_value", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "[", "transform_value", "(", "v", ")", "for", "v", "in", "value", "]", "elif", "isinstance", "(", "value", ",", "collections", ".", "Mapping", ")", ":", "return", "dict", "(", "[", "(", "k", ",", "transform_value", "(", "v", ")", ")", "for", "k", ",", "v", "in", "iteritems", "(", "value", ")", "]", ")", "else", ":", "return", "value", "return", "transform_value", "(", "dict", "(", "self", ")", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/tokumx/datadog_checks/tokumx/vendor/bson/son.py#L220-L237
pallets/jinja
077b7918a7642ff6742fe48a32e54d7875140894
src/jinja2/utils.py
python
pass_eval_context
(f: F)
return f
Pass the :class:`~jinja2.nodes.EvalContext` as the first argument to the decorated function when called while rendering a template. See :ref:`eval-context`. Can be used on functions, filters, and tests. If only ``EvalContext.environment`` is needed, use :func:`pass_environment`. .. versionadded:: 3.0.0 Replaces ``evalcontextfunction`` and ``evalcontextfilter``.
Pass the :class:`~jinja2.nodes.EvalContext` as the first argument to the decorated function when called while rendering a template. See :ref:`eval-context`.
[ "Pass", "the", ":", "class", ":", "~jinja2", ".", "nodes", ".", "EvalContext", "as", "the", "first", "argument", "to", "the", "decorated", "function", "when", "called", "while", "rendering", "a", "template", ".", "See", ":", "ref", ":", "eval", "-", "context", "." ]
def pass_eval_context(f: F) -> F: """Pass the :class:`~jinja2.nodes.EvalContext` as the first argument to the decorated function when called while rendering a template. See :ref:`eval-context`. Can be used on functions, filters, and tests. If only ``EvalContext.environment`` is needed, use :func:`pass_environment`. .. versionadded:: 3.0.0 Replaces ``evalcontextfunction`` and ``evalcontextfilter``. """ f.jinja_pass_arg = _PassArg.eval_context # type: ignore return f
[ "def", "pass_eval_context", "(", "f", ":", "F", ")", "->", "F", ":", "f", ".", "jinja_pass_arg", "=", "_PassArg", ".", "eval_context", "# type: ignore", "return", "f" ]
https://github.com/pallets/jinja/blob/077b7918a7642ff6742fe48a32e54d7875140894/src/jinja2/utils.py#L46-L60
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/orm/interfaces.py
python
PropComparator.has
(self, criterion=None, **kwargs)
return self.operate(PropComparator.has_op, criterion, **kwargs)
r"""Return true if this element references a member which meets the given criterion. The usual implementation of ``has()`` is :meth:`.RelationshipProperty.Comparator.has`. :param criterion: an optional ClauseElement formulated against the member class' table or attributes. :param \**kwargs: key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.
r"""Return true if this element references a member which meets the given criterion.
[ "r", "Return", "true", "if", "this", "element", "references", "a", "member", "which", "meets", "the", "given", "criterion", "." ]
def has(self, criterion=None, **kwargs): r"""Return true if this element references a member which meets the given criterion. The usual implementation of ``has()`` is :meth:`.RelationshipProperty.Comparator.has`. :param criterion: an optional ClauseElement formulated against the member class' table or attributes. :param \**kwargs: key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values. """ return self.operate(PropComparator.has_op, criterion, **kwargs)
[ "def", "has", "(", "self", ",", "criterion", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "operate", "(", "PropComparator", ".", "has_op", ",", "criterion", ",", "*", "*", "kwargs", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/orm/interfaces.py#L458-L474
hugapi/hug
8b5ac00632543addfdcecc326d0475a685a0cba7
examples/on_startup.py
python
test
()
return data
Returns all stored data
Returns all stored data
[ "Returns", "all", "stored", "data" ]
def test(): """Returns all stored data""" return data
[ "def", "test", "(", ")", ":", "return", "data" ]
https://github.com/hugapi/hug/blob/8b5ac00632543addfdcecc326d0475a685a0cba7/examples/on_startup.py#L21-L23
qutip/qutip
52d01da181a21b810c3407812c670f35fdc647e8
qutip/superoperator.py
python
vector_to_operator
(op)
return Qobj( sp_reshape(op.data.T, shape[::-1]).T, dims=dims, shape=shape, copy=False, )
Create a matrix representation given a quantum operator in vector form. The passed object should have a ``Qobj.type`` of 'operator-ket'; this function is not designed for general-purpose matrix reshaping. Parameters ---------- op : Qobj or QobjEvo Quantum operator in column-stacked-vector form. This must have a type of 'operator-ket'. Returns ------- Qobj or QobjEvo The same object, but re-cast into "standard" operator form. The output is the same type as the passed object.
Create a matrix representation given a quantum operator in vector form. The passed object should have a ``Qobj.type`` of 'operator-ket'; this function is not designed for general-purpose matrix reshaping.
[ "Create", "a", "matrix", "representation", "given", "a", "quantum", "operator", "in", "vector", "form", ".", "The", "passed", "object", "should", "have", "a", "Qobj", ".", "type", "of", "operator", "-", "ket", ";", "this", "function", "is", "not", "designed", "for", "general", "-", "purpose", "matrix", "reshaping", "." ]
def vector_to_operator(op): """ Create a matrix representation given a quantum operator in vector form. The passed object should have a ``Qobj.type`` of 'operator-ket'; this function is not designed for general-purpose matrix reshaping. Parameters ---------- op : Qobj or QobjEvo Quantum operator in column-stacked-vector form. This must have a type of 'operator-ket'. Returns ------- Qobj or QobjEvo The same object, but re-cast into "standard" operator form. The output is the same type as the passed object. """ if isinstance(op, QobjEvo): return op.apply(vector_to_operator) if not op.isoperket: raise ValueError( "only valid for operators in column-stacked 'operator-ket' format" ) # e.g. op.dims = [ [[rows], [cols]], [1]] dims = op.dims[0] shape = (np.prod(dims[0]), np.prod(dims[1])) return Qobj( sp_reshape(op.data.T, shape[::-1]).T, dims=dims, shape=shape, copy=False, )
[ "def", "vector_to_operator", "(", "op", ")", ":", "if", "isinstance", "(", "op", ",", "QobjEvo", ")", ":", "return", "op", ".", "apply", "(", "vector_to_operator", ")", "if", "not", "op", ".", "isoperket", ":", "raise", "ValueError", "(", "\"only valid for operators in column-stacked 'operator-ket' format\"", ")", "# e.g. op.dims = [ [[rows], [cols]], [1]]", "dims", "=", "op", ".", "dims", "[", "0", "]", "shape", "=", "(", "np", ".", "prod", "(", "dims", "[", "0", "]", ")", ",", "np", ".", "prod", "(", "dims", "[", "1", "]", ")", ")", "return", "Qobj", "(", "sp_reshape", "(", "op", ".", "data", ".", "T", ",", "shape", "[", ":", ":", "-", "1", "]", ")", ".", "T", ",", "dims", "=", "dims", ",", "shape", "=", "shape", ",", "copy", "=", "False", ",", ")" ]
https://github.com/qutip/qutip/blob/52d01da181a21b810c3407812c670f35fdc647e8/qutip/superoperator.py#L249-L279
scipy/scipy
e0a749f01e79046642ccfdc419edbf9e7ca141ad
scipy/stats/_mstats_basic.py
python
normaltest
(a, axis=0)
return NormaltestResult(k2, distributions.chi2.sf(k2, 2))
Tests whether a sample differs from a normal distribution. Parameters ---------- a : array_like The array containing the data to be tested. axis : int or None, optional Axis along which to compute test. Default is 0. If None, compute over the whole array `a`. Returns ------- statistic : float or array ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and ``k`` is the z-score returned by `kurtosistest`. pvalue : float or array A 2-sided chi squared probability for the hypothesis test. Notes ----- For more details about `normaltest`, see `stats.normaltest`.
Tests whether a sample differs from a normal distribution.
[ "Tests", "whether", "a", "sample", "differs", "from", "a", "normal", "distribution", "." ]
def normaltest(a, axis=0): """ Tests whether a sample differs from a normal distribution. Parameters ---------- a : array_like The array containing the data to be tested. axis : int or None, optional Axis along which to compute test. Default is 0. If None, compute over the whole array `a`. Returns ------- statistic : float or array ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and ``k`` is the z-score returned by `kurtosistest`. pvalue : float or array A 2-sided chi squared probability for the hypothesis test. Notes ----- For more details about `normaltest`, see `stats.normaltest`. """ a, axis = _chk_asarray(a, axis) s, _ = skewtest(a, axis) k, _ = kurtosistest(a, axis) k2 = s*s + k*k return NormaltestResult(k2, distributions.chi2.sf(k2, 2))
[ "def", "normaltest", "(", "a", ",", "axis", "=", "0", ")", ":", "a", ",", "axis", "=", "_chk_asarray", "(", "a", ",", "axis", ")", "s", ",", "_", "=", "skewtest", "(", "a", ",", "axis", ")", "k", ",", "_", "=", "kurtosistest", "(", "a", ",", "axis", ")", "k2", "=", "s", "*", "s", "+", "k", "*", "k", "return", "NormaltestResult", "(", "k2", ",", "distributions", ".", "chi2", ".", "sf", "(", "k2", ",", "2", ")", ")" ]
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/stats/_mstats_basic.py#L2868-L2898
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/fill.py
python
FillSkein.addGridLinePoints
( self, begin, end, gridPoints, gridRotationAngle, offset, y )
Add the segments of one line of a grid to the infill.
Add the segments of one line of a grid to the infill.
[ "Add", "the", "segments", "of", "one", "line", "of", "a", "grid", "to", "the", "infill", "." ]
def addGridLinePoints( self, begin, end, gridPoints, gridRotationAngle, offset, y ): 'Add the segments of one line of a grid to the infill.' if self.gridRadius == 0.0: return gridXStep = int(math.floor((begin) / self.gridXStepSize)) - 3 gridXOffset = offset + self.gridXStepSize * float(gridXStep) while gridXOffset < end: if gridXOffset >= begin: gridPointComplex = complex(gridXOffset, y) * gridRotationAngle if self.repository.infillPatternGridCircular.value or self.isPointInsideLineSegments(gridPointComplex): gridPoints.append(gridPointComplex) gridXStep = self.getNextGripXStep(gridXStep) gridXOffset = offset + self.gridXStepSize * float(gridXStep)
[ "def", "addGridLinePoints", "(", "self", ",", "begin", ",", "end", ",", "gridPoints", ",", "gridRotationAngle", ",", "offset", ",", "y", ")", ":", "if", "self", ".", "gridRadius", "==", "0.0", ":", "return", "gridXStep", "=", "int", "(", "math", ".", "floor", "(", "(", "begin", ")", "/", "self", ".", "gridXStepSize", ")", ")", "-", "3", "gridXOffset", "=", "offset", "+", "self", ".", "gridXStepSize", "*", "float", "(", "gridXStep", ")", "while", "gridXOffset", "<", "end", ":", "if", "gridXOffset", ">=", "begin", ":", "gridPointComplex", "=", "complex", "(", "gridXOffset", ",", "y", ")", "*", "gridRotationAngle", "if", "self", ".", "repository", ".", "infillPatternGridCircular", ".", "value", "or", "self", ".", "isPointInsideLineSegments", "(", "gridPointComplex", ")", ":", "gridPoints", ".", "append", "(", "gridPointComplex", ")", "gridXStep", "=", "self", ".", "getNextGripXStep", "(", "gridXStep", ")", "gridXOffset", "=", "offset", "+", "self", ".", "gridXStepSize", "*", "float", "(", "gridXStep", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/fill.py#L1048-L1060
pydicom/pynetdicom
f57d8214c82b63c8e76638af43ce331f584a80fa
pynetdicom/apps/common.py
python
ElementPath.update
(self, ds)
return ds
Return a pydicom Dataset after updating it. Parameters ---------- ds : pydicom.dataset.Dataset The dataset to update. Returns ------- pydicom.dataset.Dataset The updated dataset.
Return a pydicom Dataset after updating it.
[ "Return", "a", "pydicom", "Dataset", "after", "updating", "it", "." ]
def update(self, ds): """Return a pydicom Dataset after updating it. Parameters ---------- ds : pydicom.dataset.Dataset The dataset to update. Returns ------- pydicom.dataset.Dataset The updated dataset. """ if self.tag not in ds: # Add new element or sequence to dataset if self.is_sequence: # Add new SequenceElement with no items ds.add_new(self.tag, self.VR, []) # Add [N] empty items if self.item_nr is not None: for ii in range(self.item_nr + 1): ds[self.tag].value.append(Dataset()) # SequenceElement= if self.child is None: return ds else: # Element=(value) ds.add_new(self.tag, self.VR, self.value) return ds else: elem = ds[self.tag] # Either update or add new item if not self.is_sequence: # Update Element=(value) elem.value = self.value return ds # Check if we need to add a new item to an existing sequence # SequenceElement currently has N items nr_items = len(elem.value) if nr_items - self.item_nr == 0: # New SequenceElement[N + 1] item elem.value.append(Dataset()) elif nr_items < self.item_nr: for ii in range(self.item_nr - nr_items): elem.value.append(Dataset()) if self.child: self.child.update(ds[self.tag].value[self.item_nr]) return ds
[ "def", "update", "(", "self", ",", "ds", ")", ":", "if", "self", ".", "tag", "not", "in", "ds", ":", "# Add new element or sequence to dataset", "if", "self", ".", "is_sequence", ":", "# Add new SequenceElement with no items", "ds", ".", "add_new", "(", "self", ".", "tag", ",", "self", ".", "VR", ",", "[", "]", ")", "# Add [N] empty items", "if", "self", ".", "item_nr", "is", "not", "None", ":", "for", "ii", "in", "range", "(", "self", ".", "item_nr", "+", "1", ")", ":", "ds", "[", "self", ".", "tag", "]", ".", "value", ".", "append", "(", "Dataset", "(", ")", ")", "# SequenceElement=", "if", "self", ".", "child", "is", "None", ":", "return", "ds", "else", ":", "# Element=(value)", "ds", ".", "add_new", "(", "self", ".", "tag", ",", "self", ".", "VR", ",", "self", ".", "value", ")", "return", "ds", "else", ":", "elem", "=", "ds", "[", "self", ".", "tag", "]", "# Either update or add new item", "if", "not", "self", ".", "is_sequence", ":", "# Update Element=(value)", "elem", ".", "value", "=", "self", ".", "value", "return", "ds", "# Check if we need to add a new item to an existing sequence", "# SequenceElement currently has N items", "nr_items", "=", "len", "(", "elem", ".", "value", ")", "if", "nr_items", "-", "self", ".", "item_nr", "==", "0", ":", "# New SequenceElement[N + 1] item", "elem", ".", "value", ".", "append", "(", "Dataset", "(", ")", ")", "elif", "nr_items", "<", "self", ".", "item_nr", ":", "for", "ii", "in", "range", "(", "self", ".", "item_nr", "-", "nr_items", ")", ":", "elem", ".", "value", ".", "append", "(", "Dataset", "(", ")", ")", "if", "self", ".", "child", ":", "self", ".", "child", ".", "update", "(", "ds", "[", "self", ".", "tag", "]", ".", "value", "[", "self", ".", "item_nr", "]", ")", "return", "ds" ]
https://github.com/pydicom/pynetdicom/blob/f57d8214c82b63c8e76638af43ce331f584a80fa/pynetdicom/apps/common.py#L314-L367
feeluown/FeelUOwn
ec104689add09c351e6ca4133a5d0632294b3784
mpv.py
python
MPV.prepare_and_wait_for_event
(self, *event_types, cond=lambda evt: True)
Context manager that waits for the indicated event(s) like wait_for_event after running. If cond is given, waits until cond(event) is true. Raises a ShutdownError if the core is shutdown while waiting. This also happens when 'shutdown' is in event_types. Compared to wait_for_event this handles the case where a thread waits for an event it itself causes in a thread-safe way. An example from the testsuite is: with self.m.prepare_and_wait_for_event('client_message'): self.m.keypress(key) Using just wait_for_event it would be impossible to ensure the event is caught since it may already have been handled in the interval between keypress(...) running and a subsequent wait_for_event(...) call.
Context manager that waits for the indicated event(s) like wait_for_event after running. If cond is given, waits until cond(event) is true. Raises a ShutdownError if the core is shutdown while waiting. This also happens when 'shutdown' is in event_types. Compared to wait_for_event this handles the case where a thread waits for an event it itself causes in a thread-safe way. An example from the testsuite is: with self.m.prepare_and_wait_for_event('client_message'): self.m.keypress(key) Using just wait_for_event it would be impossible to ensure the event is caught since it may already have been handled in the interval between keypress(...) running and a subsequent wait_for_event(...) call.
[ "Context", "manager", "that", "waits", "for", "the", "indicated", "event", "(", "s", ")", "like", "wait_for_event", "after", "running", ".", "If", "cond", "is", "given", "waits", "until", "cond", "(", "event", ")", "is", "true", ".", "Raises", "a", "ShutdownError", "if", "the", "core", "is", "shutdown", "while", "waiting", ".", "This", "also", "happens", "when", "shutdown", "is", "in", "event_types", ".", "Compared", "to", "wait_for_event", "this", "handles", "the", "case", "where", "a", "thread", "waits", "for", "an", "event", "it", "itself", "causes", "in", "a", "thread", "-", "safe", "way", ".", "An", "example", "from", "the", "testsuite", "is", ":", "with", "self", ".", "m", ".", "prepare_and_wait_for_event", "(", "client_message", ")", ":", "self", ".", "m", ".", "keypress", "(", "key", ")", "Using", "just", "wait_for_event", "it", "would", "be", "impossible", "to", "ensure", "the", "event", "is", "caught", "since", "it", "may", "already", "have", "been", "handled", "in", "the", "interval", "between", "keypress", "(", "...", ")", "running", "and", "a", "subsequent", "wait_for_event", "(", "...", ")", "call", "." ]
def prepare_and_wait_for_event(self, *event_types, cond=lambda evt: True): """Context manager that waits for the indicated event(s) like wait_for_event after running. If cond is given, waits until cond(event) is true. Raises a ShutdownError if the core is shutdown while waiting. This also happens when 'shutdown' is in event_types. Compared to wait_for_event this handles the case where a thread waits for an event it itself causes in a thread-safe way. An example from the testsuite is: with self.m.prepare_and_wait_for_event('client_message'): self.m.keypress(key) Using just wait_for_event it would be impossible to ensure the event is caught since it may already have been handled in the interval between keypress(...) running and a subsequent wait_for_event(...) call. """ sema = threading.Semaphore(value=0) @self.event_callback('shutdown') def shutdown_handler(event): sema.release() @self.event_callback(*event_types) def target_handler(evt): if cond(evt): sema.release() yield sema.acquire() self.check_core_alive() shutdown_handler.unregister_mpv_events() target_handler.unregister_mpv_events()
[ "def", "prepare_and_wait_for_event", "(", "self", ",", "*", "event_types", ",", "cond", "=", "lambda", "evt", ":", "True", ")", ":", "sema", "=", "threading", ".", "Semaphore", "(", "value", "=", "0", ")", "@", "self", ".", "event_callback", "(", "'shutdown'", ")", "def", "shutdown_handler", "(", "event", ")", ":", "sema", ".", "release", "(", ")", "@", "self", ".", "event_callback", "(", "*", "event_types", ")", "def", "target_handler", "(", "evt", ")", ":", "if", "cond", "(", "evt", ")", ":", "sema", ".", "release", "(", ")", "yield", "sema", ".", "acquire", "(", ")", "self", ".", "check_core_alive", "(", ")", "shutdown_handler", ".", "unregister_mpv_events", "(", ")", "target_handler", ".", "unregister_mpv_events", "(", ")" ]
https://github.com/feeluown/FeelUOwn/blob/ec104689add09c351e6ca4133a5d0632294b3784/mpv.py#L983-L1011
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/click_view_service/transports/grpc.py
python
ClickViewServiceGrpcTransport.grpc_channel
(self)
return self._grpc_channel
Return the channel designed to connect to this service.
Return the channel designed to connect to this service.
[ "Return", "the", "channel", "designed", "to", "connect", "to", "this", "service", "." ]
def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service. """ return self._grpc_channel
[ "def", "grpc_channel", "(", "self", ")", "->", "grpc", ".", "Channel", ":", "return", "self", ".", "_grpc_channel" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/click_view_service/transports/grpc.py#L210-L213
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/nftables.py
python
insert
(table="filter", chain=None, position=None, rule=None, family="ipv4")
return ret
Insert a rule into the specified table & chain, at the specified position. If position is not specified, rule will be inserted in first position. This function accepts a rule in a standard nftables command format, starting with the chain. Trying to force users to adapt to a new method of creating rules would be irritating at best, and we already have a parser that can handle it. CLI Examples: .. code-block:: bash salt '*' nftables.insert filter input \\ rule='tcp dport 22 log accept' salt '*' nftables.insert filter input position=3 \\ rule='tcp dport 22 log accept' IPv6: salt '*' nftables.insert filter input \\ rule='tcp dport 22 log accept' \\ family=ipv6 salt '*' nftables.insert filter input position=3 \\ rule='tcp dport 22 log accept' \\ family=ipv6
Insert a rule into the specified table & chain, at the specified position.
[ "Insert", "a", "rule", "into", "the", "specified", "table", "&", "chain", "at", "the", "specified", "position", "." ]
def insert(table="filter", chain=None, position=None, rule=None, family="ipv4"): """ Insert a rule into the specified table & chain, at the specified position. If position is not specified, rule will be inserted in first position. This function accepts a rule in a standard nftables command format, starting with the chain. Trying to force users to adapt to a new method of creating rules would be irritating at best, and we already have a parser that can handle it. CLI Examples: .. code-block:: bash salt '*' nftables.insert filter input \\ rule='tcp dport 22 log accept' salt '*' nftables.insert filter input position=3 \\ rule='tcp dport 22 log accept' IPv6: salt '*' nftables.insert filter input \\ rule='tcp dport 22 log accept' \\ family=ipv6 salt '*' nftables.insert filter input position=3 \\ rule='tcp dport 22 log accept' \\ family=ipv6 """ ret = { "comment": "Failed to insert rule {} to table {}.".format(rule, table), "result": False, } if not chain: ret["comment"] = "Chain needs to be specified" return ret if not rule: ret["comment"] = "Rule needs to be specified" return ret res = check_table(table, family=family) if not res["result"]: return res res = check_chain(table, chain, family=family) if not res["result"]: return res res = check(table, chain, rule, family=family) if res["result"]: ret[ "comment" ] = "Rule {} chain {} in table {} in family {} already exists".format( rule, chain, table, family ) return ret nft_family = _NFTABLES_FAMILIES[family] if position: cmd = "{} insert rule {} {} {} position {} {}".format( _nftables_cmd(), nft_family, table, chain, position, rule ) else: cmd = "{} insert rule {} {} {} {}".format( _nftables_cmd(), nft_family, table, chain, rule ) out = __salt__["cmd.run"](cmd, python_shell=False) if not out: ret["result"] = True ret["comment"] = 'Added rule "{}" chain {} in table {} in family {}.'.format( rule, chain, table, family ) else: ret[ "comment" ] = 'Failed to add rule "{}" chain {} in table {} in family {}.'.format( rule, chain, table, family ) return ret
[ "def", "insert", "(", "table", "=", "\"filter\"", ",", "chain", "=", "None", ",", "position", "=", "None", ",", "rule", "=", "None", ",", "family", "=", "\"ipv4\"", ")", ":", "ret", "=", "{", "\"comment\"", ":", "\"Failed to insert rule {} to table {}.\"", ".", "format", "(", "rule", ",", "table", ")", ",", "\"result\"", ":", "False", ",", "}", "if", "not", "chain", ":", "ret", "[", "\"comment\"", "]", "=", "\"Chain needs to be specified\"", "return", "ret", "if", "not", "rule", ":", "ret", "[", "\"comment\"", "]", "=", "\"Rule needs to be specified\"", "return", "ret", "res", "=", "check_table", "(", "table", ",", "family", "=", "family", ")", "if", "not", "res", "[", "\"result\"", "]", ":", "return", "res", "res", "=", "check_chain", "(", "table", ",", "chain", ",", "family", "=", "family", ")", "if", "not", "res", "[", "\"result\"", "]", ":", "return", "res", "res", "=", "check", "(", "table", ",", "chain", ",", "rule", ",", "family", "=", "family", ")", "if", "res", "[", "\"result\"", "]", ":", "ret", "[", "\"comment\"", "]", "=", "\"Rule {} chain {} in table {} in family {} already exists\"", ".", "format", "(", "rule", ",", "chain", ",", "table", ",", "family", ")", "return", "ret", "nft_family", "=", "_NFTABLES_FAMILIES", "[", "family", "]", "if", "position", ":", "cmd", "=", "\"{} insert rule {} {} {} position {} {}\"", ".", "format", "(", "_nftables_cmd", "(", ")", ",", "nft_family", ",", "table", ",", "chain", ",", "position", ",", "rule", ")", "else", ":", "cmd", "=", "\"{} insert rule {} {} {} {}\"", ".", "format", "(", "_nftables_cmd", "(", ")", ",", "nft_family", ",", "table", ",", "chain", ",", "rule", ")", "out", "=", "__salt__", "[", "\"cmd.run\"", "]", "(", "cmd", ",", "python_shell", "=", "False", ")", "if", "not", "out", ":", "ret", "[", "\"result\"", "]", "=", "True", "ret", "[", "\"comment\"", "]", "=", "'Added rule \"{}\" chain {} in table {} in family {}.'", ".", "format", "(", "rule", ",", "chain", ",", "table", ",", "family", ")", "else", ":", "ret", "[", "\"comment\"", "]", "=", "'Failed to add rule \"{}\" chain {} in table {} in family {}.'", ".", "format", "(", "rule", ",", "chain", ",", "table", ",", "family", ")", "return", "ret" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/nftables.py#L934-L1016
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/tempfile.py
python
TemporaryDirectory.__init__
(self, suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False)
[]
def __init__(self, suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False): self.name = mkdtemp(suffix, prefix, dir) self._ignore_cleanup_errors = ignore_cleanup_errors self._finalizer = _weakref.finalize( self, self._cleanup, self.name, warn_message="Implicitly cleaning up {!r}".format(self), ignore_errors=self._ignore_cleanup_errors)
[ "def", "__init__", "(", "self", ",", "suffix", "=", "None", ",", "prefix", "=", "None", ",", "dir", "=", "None", ",", "ignore_cleanup_errors", "=", "False", ")", ":", "self", ".", "name", "=", "mkdtemp", "(", "suffix", ",", "prefix", ",", "dir", ")", "self", ".", "_ignore_cleanup_errors", "=", "ignore_cleanup_errors", "self", ".", "_finalizer", "=", "_weakref", ".", "finalize", "(", "self", ",", "self", ".", "_cleanup", ",", "self", ".", "name", ",", "warn_message", "=", "\"Implicitly cleaning up {!r}\"", ".", "format", "(", "self", ")", ",", "ignore_errors", "=", "self", ".", "_ignore_cleanup_errors", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/tempfile.py#L794-L801
wandb/client
3963364d8112b7dedb928fa423b6878ea1b467d9
wandb/apis/normalize.py
python
normalize_exceptions
(func)
return wrapper
Function decorator for catching common errors and re-raising as wandb.Error
Function decorator for catching common errors and re-raising as wandb.Error
[ "Function", "decorator", "for", "catching", "common", "errors", "and", "re", "-", "raising", "as", "wandb", ".", "Error" ]
def normalize_exceptions(func): """Function decorator for catching common errors and re-raising as wandb.Error""" @wraps(func) def wrapper(*args, **kwargs): message = "Whoa, you found a bug." try: return func(*args, **kwargs) except requests.HTTPError as err: raise CommError(err.response, err) except RetryError as err: if ( "response" in dir(err.last_exception) and err.last_exception.response is not None ): try: message = err.last_exception.response.json().get( "errors", [{"message": message}] )[0]["message"] except ValueError: message = err.last_exception.response.text else: message = err.last_exception if env.is_debug(): six.reraise( type(err.last_exception), err.last_exception, sys.exc_info()[2] ) else: six.reraise( CommError, CommError(message, err.last_exception), sys.exc_info()[2] ) except Exception as err: # gql raises server errors with dict's as strings... if len(err.args) > 0: payload = err.args[0] else: payload = err if str(payload).startswith("{"): message = ast.literal_eval(str(payload))["message"] else: message = str(err) if env.is_debug(): six.reraise(*sys.exc_info()) else: six.reraise(CommError, CommError(message, err), sys.exc_info()[2]) return wrapper
[ "def", "normalize_exceptions", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "message", "=", "\"Whoa, you found a bug.\"", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "requests", ".", "HTTPError", "as", "err", ":", "raise", "CommError", "(", "err", ".", "response", ",", "err", ")", "except", "RetryError", "as", "err", ":", "if", "(", "\"response\"", "in", "dir", "(", "err", ".", "last_exception", ")", "and", "err", ".", "last_exception", ".", "response", "is", "not", "None", ")", ":", "try", ":", "message", "=", "err", ".", "last_exception", ".", "response", ".", "json", "(", ")", ".", "get", "(", "\"errors\"", ",", "[", "{", "\"message\"", ":", "message", "}", "]", ")", "[", "0", "]", "[", "\"message\"", "]", "except", "ValueError", ":", "message", "=", "err", ".", "last_exception", ".", "response", ".", "text", "else", ":", "message", "=", "err", ".", "last_exception", "if", "env", ".", "is_debug", "(", ")", ":", "six", ".", "reraise", "(", "type", "(", "err", ".", "last_exception", ")", ",", "err", ".", "last_exception", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "else", ":", "six", ".", "reraise", "(", "CommError", ",", "CommError", "(", "message", ",", "err", ".", "last_exception", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "except", "Exception", "as", "err", ":", "# gql raises server errors with dict's as strings...", "if", "len", "(", "err", ".", "args", ")", ">", "0", ":", "payload", "=", "err", ".", "args", "[", "0", "]", "else", ":", "payload", "=", "err", "if", "str", "(", "payload", ")", ".", "startswith", "(", "\"{\"", ")", ":", "message", "=", "ast", ".", "literal_eval", "(", "str", "(", "payload", ")", ")", "[", "\"message\"", "]", "else", ":", "message", "=", "str", "(", "err", ")", "if", "env", ".", "is_debug", "(", ")", ":", "six", ".", "reraise", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "six", ".", "reraise", "(", "CommError", ",", "CommError", "(", "message", ",", "err", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "return", "wrapper" ]
https://github.com/wandb/client/blob/3963364d8112b7dedb928fa423b6878ea1b467d9/wandb/apis/normalize.py#L17-L64
tensorforce/tensorforce
085a62bd37e0fdfd05691db29edeb2e1714ffbda
tensorforce/agents/agent.py
python
Agent.tracked_tensors
(self)
return self.model.tracked_tensors()
Returns the current value of all tracked tensors (as specified by "tracking" agent argument). Note that not all tensors change at every timestep. Returns: dict[values]: Dictionary containing the current value of all tracked tensors.
Returns the current value of all tracked tensors (as specified by "tracking" agent argument). Note that not all tensors change at every timestep.
[ "Returns", "the", "current", "value", "of", "all", "tracked", "tensors", "(", "as", "specified", "by", "tracking", "agent", "argument", ")", ".", "Note", "that", "not", "all", "tensors", "change", "at", "every", "timestep", "." ]
def tracked_tensors(self): """ Returns the current value of all tracked tensors (as specified by "tracking" agent argument). Note that not all tensors change at every timestep. Returns: dict[values]: Dictionary containing the current value of all tracked tensors. """ return self.model.tracked_tensors()
[ "def", "tracked_tensors", "(", "self", ")", ":", "return", "self", ".", "model", ".", "tracked_tensors", "(", ")" ]
https://github.com/tensorforce/tensorforce/blob/085a62bd37e0fdfd05691db29edeb2e1714ffbda/tensorforce/agents/agent.py#L364-L372
kennethreitz-archive/requests3
69eb662703b40db58fdc6c095d0fe130c56649bb
requests3/core/_http/_sync/response.py
python
HTTPResponse.data
(self)
[]
def data(self): # For backwords-compat with earlier urllib3 0.4 and earlier. if self._body is not None: return self._body if self._fp: return self.read(cache_content=True)
[ "def", "data", "(", "self", ")", ":", "# For backwords-compat with earlier urllib3 0.4 and earlier.", "if", "self", ".", "_body", "is", "not", "None", ":", "return", "self", ".", "_body", "if", "self", ".", "_fp", ":", "return", "self", ".", "read", "(", "cache_content", "=", "True", ")" ]
https://github.com/kennethreitz-archive/requests3/blob/69eb662703b40db58fdc6c095d0fe130c56649bb/requests3/core/_http/_sync/response.py#L165-L171
AI-ON/Multitask-and-Transfer-Learning
31e0798d436e314ddbc64c4a6b935df1b2160e50
AMTLB/amtlb/transfer_benchmark.py
python
BenchmarkResult.record_game
(self, game_name, round)
[]
def record_game(self, game_name, round): self.games.append((game_name, round))
[ "def", "record_game", "(", "self", ",", "game_name", ",", "round", ")", ":", "self", ".", "games", ".", "append", "(", "(", "game_name", ",", "round", ")", ")" ]
https://github.com/AI-ON/Multitask-and-Transfer-Learning/blob/31e0798d436e314ddbc64c4a6b935df1b2160e50/AMTLB/amtlb/transfer_benchmark.py#L38-L39
elastic/detection-rules
fd824d1fd5404c00eadb0251c8eb4f71af52a6d5
detection_rules/rule_validators.py
python
KQLValidator.validate
(self, data: QueryRuleData, meta: RuleMeta)
Static method to validate the query, called from the parent which contains [metadata] information.
Static method to validate the query, called from the parent which contains [metadata] information.
[ "Static", "method", "to", "validate", "the", "query", "called", "from", "the", "parent", "which", "contains", "[", "metadata", "]", "information", "." ]
def validate(self, data: QueryRuleData, meta: RuleMeta) -> None: """Static method to validate the query, called from the parent which contains [metadata] information.""" ast = self.ast if meta.query_schema_validation is False or meta.maturity == "deprecated": # syntax only, which is done via self.ast return for stack_version, mapping in meta.get_validation_stack_versions().items(): beats_version = mapping['beats'] ecs_version = mapping['ecs'] err_trailer = f'stack: {stack_version}, beats: {beats_version}, ecs: {ecs_version}' beat_types = beats.parse_beats_from_index(data.index) beat_schema = beats.get_schema_from_kql(ast, beat_types, version=beats_version) if beat_types else None schema = ecs.get_kql_schema(version=ecs_version, indexes=data.index or [], beat_schema=beat_schema) try: kql.parse(self.query, schema=schema) except kql.KqlParseError as exc: message = exc.error_msg trailer = err_trailer if "Unknown field" in message and beat_types: trailer = f"\nTry adding event.module or event.dataset to specify beats module\n\n{trailer}" raise kql.KqlParseError(exc.error_msg, exc.line, exc.column, exc.source, len(exc.caret.lstrip()), trailer=trailer) from None except Exception: print(err_trailer) raise
[ "def", "validate", "(", "self", ",", "data", ":", "QueryRuleData", ",", "meta", ":", "RuleMeta", ")", "->", "None", ":", "ast", "=", "self", ".", "ast", "if", "meta", ".", "query_schema_validation", "is", "False", "or", "meta", ".", "maturity", "==", "\"deprecated\"", ":", "# syntax only, which is done via self.ast", "return", "for", "stack_version", ",", "mapping", "in", "meta", ".", "get_validation_stack_versions", "(", ")", ".", "items", "(", ")", ":", "beats_version", "=", "mapping", "[", "'beats'", "]", "ecs_version", "=", "mapping", "[", "'ecs'", "]", "err_trailer", "=", "f'stack: {stack_version}, beats: {beats_version}, ecs: {ecs_version}'", "beat_types", "=", "beats", ".", "parse_beats_from_index", "(", "data", ".", "index", ")", "beat_schema", "=", "beats", ".", "get_schema_from_kql", "(", "ast", ",", "beat_types", ",", "version", "=", "beats_version", ")", "if", "beat_types", "else", "None", "schema", "=", "ecs", ".", "get_kql_schema", "(", "version", "=", "ecs_version", ",", "indexes", "=", "data", ".", "index", "or", "[", "]", ",", "beat_schema", "=", "beat_schema", ")", "try", ":", "kql", ".", "parse", "(", "self", ".", "query", ",", "schema", "=", "schema", ")", "except", "kql", ".", "KqlParseError", "as", "exc", ":", "message", "=", "exc", ".", "error_msg", "trailer", "=", "err_trailer", "if", "\"Unknown field\"", "in", "message", "and", "beat_types", ":", "trailer", "=", "f\"\\nTry adding event.module or event.dataset to specify beats module\\n\\n{trailer}\"", "raise", "kql", ".", "KqlParseError", "(", "exc", ".", "error_msg", ",", "exc", ".", "line", ",", "exc", ".", "column", ",", "exc", ".", "source", ",", "len", "(", "exc", ".", "caret", ".", "lstrip", "(", ")", ")", ",", "trailer", "=", "trailer", ")", "from", "None", "except", "Exception", ":", "print", "(", "err_trailer", ")", "raise" ]
https://github.com/elastic/detection-rules/blob/fd824d1fd5404c00eadb0251c8eb4f71af52a6d5/detection_rules/rule_validators.py#L31-L60
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Shared/multiprocessing/util.py
python
is_exiting
()
return _exiting or _exiting is None
Returns true if the process is shutting down
Returns true if the process is shutting down
[ "Returns", "true", "if", "the", "process", "is", "shutting", "down" ]
def is_exiting(): ''' Returns true if the process is shutting down ''' return _exiting or _exiting is None
[ "def", "is_exiting", "(", ")", ":", "return", "_exiting", "or", "_exiting", "is", "None" ]
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Shared/multiprocessing/util.py#L286-L290
invesalius/invesalius3
0616d3e73bfe0baf7525877dbf6acab697395eb9
invesalius/utils.py
python
debug
(error_str)
Redirects output to file, or to the terminal This should be used in the place of "print"
Redirects output to file, or to the terminal This should be used in the place of "print"
[ "Redirects", "output", "to", "file", "or", "to", "the", "terminal", "This", "should", "be", "used", "in", "the", "place", "of", "print" ]
def debug(error_str): """ Redirects output to file, or to the terminal This should be used in the place of "print" """ from invesalius.session import Session session = Session() #if session.debug: print(error_str)
[ "def", "debug", "(", "error_str", ")", ":", "from", "invesalius", ".", "session", "import", "Session", "session", "=", "Session", "(", ")", "#if session.debug:", "print", "(", "error_str", ")" ]
https://github.com/invesalius/invesalius3/blob/0616d3e73bfe0baf7525877dbf6acab697395eb9/invesalius/utils.py#L74-L82
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/microphone.py
python
AudioCapture.reset
(self, log=True)
Restores to fresh state, ready to record again
Restores to fresh state, ready to record again
[ "Restores", "to", "fresh", "state", "ready", "to", "record", "again" ]
def reset(self, log=True): """Restores to fresh state, ready to record again """ if log and self.autoLog: msg = '%s: resetting at %.3f' logging.exp(msg % (self.loggingId, core.getTime())) self.__init__(name=self.name, saveDir=self.saveDir)
[ "def", "reset", "(", "self", ",", "log", "=", "True", ")", ":", "if", "log", "and", "self", ".", "autoLog", ":", "msg", "=", "'%s: resetting at %.3f'", "logging", ".", "exp", "(", "msg", "%", "(", "self", ".", "loggingId", ",", "core", ".", "getTime", "(", ")", ")", ")", "self", ".", "__init__", "(", "name", "=", "self", ".", "name", ",", "saveDir", "=", "self", ".", "saveDir", ")" ]
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/microphone.py#L215-L221
toxygen-project/toxygen
0a54012cf5ee72434b923bcde7d8f1a4e575ce2f
toxygen/callbacks.py
python
call_state
(toxav, friend_number, mask, user_data)
New call state
New call state
[ "New", "call", "state" ]
def call_state(toxav, friend_number, mask, user_data): """ New call state """ print(friend_number, mask) if mask == TOXAV_FRIEND_CALL_STATE['FINISHED'] or mask == TOXAV_FRIEND_CALL_STATE['ERROR']: invoke_in_main_thread(Profile.get_instance().stop_call, friend_number, True) else: Profile.get_instance().call.toxav_call_state_cb(friend_number, mask)
[ "def", "call_state", "(", "toxav", ",", "friend_number", ",", "mask", ",", "user_data", ")", ":", "print", "(", "friend_number", ",", "mask", ")", "if", "mask", "==", "TOXAV_FRIEND_CALL_STATE", "[", "'FINISHED'", "]", "or", "mask", "==", "TOXAV_FRIEND_CALL_STATE", "[", "'ERROR'", "]", ":", "invoke_in_main_thread", "(", "Profile", ".", "get_instance", "(", ")", ".", "stop_call", ",", "friend_number", ",", "True", ")", "else", ":", "Profile", ".", "get_instance", "(", ")", ".", "call", ".", "toxav_call_state_cb", "(", "friend_number", ",", "mask", ")" ]
https://github.com/toxygen-project/toxygen/blob/0a54012cf5ee72434b923bcde7d8f1a4e575ce2f/toxygen/callbacks.py#L295-L303
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/logutils/queue.py
python
QueueListener.__init__
(self, queue, *handlers)
Initialise an instance with the specified queue and handlers.
Initialise an instance with the specified queue and handlers.
[ "Initialise", "an", "instance", "with", "the", "specified", "queue", "and", "handlers", "." ]
def __init__(self, queue, *handlers): """ Initialise an instance with the specified queue and handlers. """ self.queue = queue self.handlers = handlers self._stop = threading.Event() self._thread = None
[ "def", "__init__", "(", "self", ",", "queue", ",", "*", "handlers", ")", ":", "self", ".", "queue", "=", "queue", "self", ".", "handlers", "=", "handlers", "self", ".", "_stop", "=", "threading", ".", "Event", "(", ")", "self", ".", "_thread", "=", "None" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/logutils/queue.py#L112-L120
stuartlangridge/ColourPicker
dec8f144918aa7964aaf86a346161beb7e997f09
pick/__main__.py
python
Main.sizeit
(self, w, h)
[]
def sizeit(self, w, h): self.w.resize(w, h)
[ "def", "sizeit", "(", "self", ",", "w", ",", "h", ")", ":", "self", ".", "w", ".", "resize", "(", "w", ",", "h", ")" ]
https://github.com/stuartlangridge/ColourPicker/blob/dec8f144918aa7964aaf86a346161beb7e997f09/pick/__main__.py#L388-L389
steveKapturowski/tensorflow-rl
6dc58da69bad0349a646cfc94ea9c5d1eada8351
utils/cts.py
python
Estimator.update
(self, symbol)
return log_prob
Updates our count for the given symbol.
Updates our count for the given symbol.
[ "Updates", "our", "count", "for", "the", "given", "symbol", "." ]
def update(self, symbol): """Updates our count for the given symbol.""" log_prob = math.log(self.prob(symbol)) self.counts[symbol] = ( self.counts.get(symbol, self._model.symbol_prior) + 1.0) self.count_total += 1.0 return log_prob
[ "def", "update", "(", "self", ",", "symbol", ")", ":", "log_prob", "=", "math", ".", "log", "(", "self", ".", "prob", "(", "symbol", ")", ")", "self", ".", "counts", "[", "symbol", "]", "=", "(", "self", ".", "counts", ".", "get", "(", "symbol", ",", "self", ".", "_model", ".", "symbol_prior", ")", "+", "1.0", ")", "self", ".", "count_total", "+=", "1.0", "return", "log_prob" ]
https://github.com/steveKapturowski/tensorflow-rl/blob/6dc58da69bad0349a646cfc94ea9c5d1eada8351/utils/cts.py#L72-L78
pretix/pretix
96f694cf61345f54132cd26cdeb07d5d11b34232
src/pretix/presale/views/cart.py
python
get_or_create_cart_id
(request, create=True)
return new_id
This method returns the cart ID in use for this request or creates a new cart ID if required. Before pretix 1.8.0, the user's session cookie was used as the cart ID in the database. With the cart session data isolation introduced in 1.8.0 (see cart_session()) this changed drastically. Now, a different random cart ID is used for every event and stored to the user's session with the 'current_cart_event_42' key (with 42 being the event ID). This became even more relevant and complex with the introduction of the pretix widget in 1.9.0. Since the widget operates from a different origin, it requires us to lower some security walls in order to function correctly: * The checkout and order views can no longer send X-Frame-Options: DENY headers as we include those pages in an iframe. This makes our users vulnerable to clickjacking. Possible scenario: A third-party website could trick you into submitting an order that you currently have in your cart. * The cart add view needs to drop CSRF protection and set Access-Control-Allow-Origin: *. This makes our users vulnerable to CSRF attacks adding unwanted products to their carts. Cross-Origin is not that much of an issue since we can't set Access-Control-Allow-Credentials for origin * either way, but on the other hand this also prevents us to change the current cart for legitimate reasons. We can mitigate all of these issues at the same time with the very simple strategy on only lowering these walls at unguessable URLs. This makes it impossible for an attacker to create an exploit with real-world impact. Therefore, we introduce cart namespacing in pretix 1.9.0. In addition to your default session that you have at /orga/event/ as usual, you will have a different cart session with a different cart ID at /orga/event/w/mysecretnonce123/. Such a namespace parameter can be passed to all views relevant to the widget (e.g. /orga/event/w/mysecretnonce123/cart/add) that are not already unguessable (like /orga/event/orders/ABCDE/secret123465456/). The actual cart IDs for those namespaced carts will then be stored at request.session['current_cart_event_42_mysecretnonce123']. However, we still need to work around the issue that we can't use Access-Control-Allow-Credentials but want to invoke /cart/add via a cross-origin request. This leads to /cart/add creating a new cart session every time it is invoked cross-origin by default. We solve this by returning the newly created cart ID from /cart/add in the response and allow passing it as the take_cart_id query parameter to the view in the iframe or to subsequent /cart/add requests. As an additional precaution, take_cart_id will only be honoured on POST requests or if there is an actual cart with this ID. This reduces the likelihood of strange behaviour if someone accidentally shares a link that includes this parameter. This method migrates legacy sessions created before the upgrade to 1.8.0 on a best-effort basis, meaning that the migration does not respect plugin-specific data and works best if the user only used the session for one event at the time of migration. If ``create`` is ``False`` and no session currently exists, ``None`` will be returned.
This method returns the cart ID in use for this request or creates a new cart ID if required.
[ "This", "method", "returns", "the", "cart", "ID", "in", "use", "for", "this", "request", "or", "creates", "a", "new", "cart", "ID", "if", "required", "." ]
def get_or_create_cart_id(request, create=True): """ This method returns the cart ID in use for this request or creates a new cart ID if required. Before pretix 1.8.0, the user's session cookie was used as the cart ID in the database. With the cart session data isolation introduced in 1.8.0 (see cart_session()) this changed drastically. Now, a different random cart ID is used for every event and stored to the user's session with the 'current_cart_event_42' key (with 42 being the event ID). This became even more relevant and complex with the introduction of the pretix widget in 1.9.0. Since the widget operates from a different origin, it requires us to lower some security walls in order to function correctly: * The checkout and order views can no longer send X-Frame-Options: DENY headers as we include those pages in an iframe. This makes our users vulnerable to clickjacking. Possible scenario: A third-party website could trick you into submitting an order that you currently have in your cart. * The cart add view needs to drop CSRF protection and set Access-Control-Allow-Origin: *. This makes our users vulnerable to CSRF attacks adding unwanted products to their carts. Cross-Origin is not that much of an issue since we can't set Access-Control-Allow-Credentials for origin * either way, but on the other hand this also prevents us to change the current cart for legitimate reasons. We can mitigate all of these issues at the same time with the very simple strategy on only lowering these walls at unguessable URLs. This makes it impossible for an attacker to create an exploit with real-world impact. Therefore, we introduce cart namespacing in pretix 1.9.0. In addition to your default session that you have at /orga/event/ as usual, you will have a different cart session with a different cart ID at /orga/event/w/mysecretnonce123/. Such a namespace parameter can be passed to all views relevant to the widget (e.g. /orga/event/w/mysecretnonce123/cart/add) that are not already unguessable (like /orga/event/orders/ABCDE/secret123465456/). The actual cart IDs for those namespaced carts will then be stored at request.session['current_cart_event_42_mysecretnonce123']. However, we still need to work around the issue that we can't use Access-Control-Allow-Credentials but want to invoke /cart/add via a cross-origin request. This leads to /cart/add creating a new cart session every time it is invoked cross-origin by default. We solve this by returning the newly created cart ID from /cart/add in the response and allow passing it as the take_cart_id query parameter to the view in the iframe or to subsequent /cart/add requests. As an additional precaution, take_cart_id will only be honoured on POST requests or if there is an actual cart with this ID. This reduces the likelihood of strange behaviour if someone accidentally shares a link that includes this parameter. This method migrates legacy sessions created before the upgrade to 1.8.0 on a best-effort basis, meaning that the migration does not respect plugin-specific data and works best if the user only used the session for one event at the time of migration. If ``create`` is ``False`` and no session currently exists, ``None`` will be returned. """ session_keyname = 'current_cart_event_{}'.format(request.event.pk) prefix = '' if request.resolver_match and request.resolver_match.kwargs.get('cart_namespace'): session_keyname += '_' + request.resolver_match.kwargs.get('cart_namespace') prefix = request.resolver_match.kwargs.get('cart_namespace') current_id = orig_current_id = request.session.get(session_keyname) if prefix and 'take_cart_id' in request.GET: pos = CartPosition.objects.filter(event=request.event, cart_id=request.GET.get('take_cart_id')) if request.method == "POST" or pos.exists() or 'ajax' in request.GET: current_id = request.GET.get('take_cart_id') if current_id and current_id in request.session.get('carts', {}): if current_id != orig_current_id: request.session[session_keyname] = current_id cart_invalidated = ( request.session['carts'][current_id].get('customer_cart_tied_to_login', False) and request.session['carts'][current_id].get('customer') and (not request.customer or request.session['carts'][current_id].get('customer') != request.customer.pk) ) if cart_invalidated: # This cart was created with a login but the person is now logged out. # Destroy the cart for privacy protection. request.session['carts'][current_id] = {} else: return current_id cart_data = {} if prefix and 'take_cart_id' in request.GET and current_id: new_id = current_id cached_widget_data = widget_data_cache.get('widget_data_{}'.format(current_id)) if cached_widget_data: cart_data['widget_data'] = cached_widget_data else: if not create: return None new_id = generate_cart_id(request, prefix=prefix) if 'widget_data' not in cart_data and 'widget_data' in request.GET: try: cart_data['widget_data'] = json.loads(request.GET.get('widget_data')) except ValueError: pass if 'carts' not in request.session: request.session['carts'] = {} if new_id not in request.session['carts']: request.session['carts'][new_id] = cart_data request.session[session_keyname] = new_id return new_id
[ "def", "get_or_create_cart_id", "(", "request", ",", "create", "=", "True", ")", ":", "session_keyname", "=", "'current_cart_event_{}'", ".", "format", "(", "request", ".", "event", ".", "pk", ")", "prefix", "=", "''", "if", "request", ".", "resolver_match", "and", "request", ".", "resolver_match", ".", "kwargs", ".", "get", "(", "'cart_namespace'", ")", ":", "session_keyname", "+=", "'_'", "+", "request", ".", "resolver_match", ".", "kwargs", ".", "get", "(", "'cart_namespace'", ")", "prefix", "=", "request", ".", "resolver_match", ".", "kwargs", ".", "get", "(", "'cart_namespace'", ")", "current_id", "=", "orig_current_id", "=", "request", ".", "session", ".", "get", "(", "session_keyname", ")", "if", "prefix", "and", "'take_cart_id'", "in", "request", ".", "GET", ":", "pos", "=", "CartPosition", ".", "objects", ".", "filter", "(", "event", "=", "request", ".", "event", ",", "cart_id", "=", "request", ".", "GET", ".", "get", "(", "'take_cart_id'", ")", ")", "if", "request", ".", "method", "==", "\"POST\"", "or", "pos", ".", "exists", "(", ")", "or", "'ajax'", "in", "request", ".", "GET", ":", "current_id", "=", "request", ".", "GET", ".", "get", "(", "'take_cart_id'", ")", "if", "current_id", "and", "current_id", "in", "request", ".", "session", ".", "get", "(", "'carts'", ",", "{", "}", ")", ":", "if", "current_id", "!=", "orig_current_id", ":", "request", ".", "session", "[", "session_keyname", "]", "=", "current_id", "cart_invalidated", "=", "(", "request", ".", "session", "[", "'carts'", "]", "[", "current_id", "]", ".", "get", "(", "'customer_cart_tied_to_login'", ",", "False", ")", "and", "request", ".", "session", "[", "'carts'", "]", "[", "current_id", "]", ".", "get", "(", "'customer'", ")", "and", "(", "not", "request", ".", "customer", "or", "request", ".", "session", "[", "'carts'", "]", "[", "current_id", "]", ".", "get", "(", "'customer'", ")", "!=", "request", ".", "customer", ".", "pk", ")", ")", "if", "cart_invalidated", ":", "# This cart was created with a login but the person is now logged out.", "# Destroy the cart for privacy protection.", "request", ".", "session", "[", "'carts'", "]", "[", "current_id", "]", "=", "{", "}", "else", ":", "return", "current_id", "cart_data", "=", "{", "}", "if", "prefix", "and", "'take_cart_id'", "in", "request", ".", "GET", "and", "current_id", ":", "new_id", "=", "current_id", "cached_widget_data", "=", "widget_data_cache", ".", "get", "(", "'widget_data_{}'", ".", "format", "(", "current_id", ")", ")", "if", "cached_widget_data", ":", "cart_data", "[", "'widget_data'", "]", "=", "cached_widget_data", "else", ":", "if", "not", "create", ":", "return", "None", "new_id", "=", "generate_cart_id", "(", "request", ",", "prefix", "=", "prefix", ")", "if", "'widget_data'", "not", "in", "cart_data", "and", "'widget_data'", "in", "request", ".", "GET", ":", "try", ":", "cart_data", "[", "'widget_data'", "]", "=", "json", ".", "loads", "(", "request", ".", "GET", ".", "get", "(", "'widget_data'", ")", ")", "except", "ValueError", ":", "pass", "if", "'carts'", "not", "in", "request", ".", "session", ":", "request", ".", "session", "[", "'carts'", "]", "=", "{", "}", "if", "new_id", "not", "in", "request", ".", "session", "[", "'carts'", "]", ":", "request", ".", "session", "[", "'carts'", "]", "[", "new_id", "]", "=", "cart_data", "request", ".", "session", "[", "session_keyname", "]", "=", "new_id", "return", "new_id" ]
https://github.com/pretix/pretix/blob/96f694cf61345f54132cd26cdeb07d5d11b34232/src/pretix/presale/views/cart.py#L280-L384
faucetsdn/ryu
537f35f4b2bc634ef05e3f28373eb5e24609f989
ryu/cmd/of_config_cli.py
python
Cmd.do_get
(self, line)
get <peer> eg. get sw1
get <peer> eg. get sw1
[ "get", "<peer", ">", "eg", ".", "get", "sw1" ]
def do_get(self, line): """get <peer> eg. get sw1 """ def f(p, args): print(p.get()) self._request(line, f)
[ "def", "do_get", "(", "self", ",", "line", ")", ":", "def", "f", "(", "p", ",", "args", ")", ":", "print", "(", "p", ".", "get", "(", ")", ")", "self", ".", "_request", "(", "line", ",", "f", ")" ]
https://github.com/faucetsdn/ryu/blob/537f35f4b2bc634ef05e3f28373eb5e24609f989/ryu/cmd/of_config_cli.py#L143-L151
kvesteri/sqlalchemy-utils
850d0ea5a8a84c0529d175ee41b9036bea597119
sqlalchemy_utils/functions/foreign_keys.py
python
dependent_objects
(obj, foreign_keys=None)
return chain
Return a :class:`~sqlalchemy_utils.query_chain.QueryChain` that iterates through all dependent objects for given SQLAlchemy object. Consider a User object is referenced in various articles and also in various orders. Getting all these dependent objects is as easy as:: from sqlalchemy_utils import dependent_objects dependent_objects(user) If you expect an object to have lots of dependent_objects it might be good to limit the results:: dependent_objects(user).limit(5) The common use case is checking for all restrict dependent objects before deleting parent object and inform the user if there are dependent objects with ondelete='RESTRICT' foreign keys. If this kind of checking is not used it will lead to nasty IntegrityErrors being raised. In the following example we delete given user if it doesn't have any foreign key restricted dependent objects:: from sqlalchemy_utils import get_referencing_foreign_keys user = session.query(User).get(some_user_id) deps = list( dependent_objects( user, ( fk for fk in get_referencing_foreign_keys(User) # On most databases RESTRICT is the default mode hence we # check for None values also if fk.ondelete == 'RESTRICT' or fk.ondelete is None ) ).limit(5) ) if deps: # Do something to inform the user pass else: session.delete(user) :param obj: SQLAlchemy declarative model object :param foreign_keys: A sequence of foreign keys to use for searching the dependent_objects for given object. By default this is None, indicating that all foreign keys referencing the object will be used. .. note:: This function does not support exotic mappers that use multiple tables .. seealso:: :func:`get_referencing_foreign_keys` .. seealso:: :func:`merge_references` .. versionadded: 0.26.0
Return a :class:`~sqlalchemy_utils.query_chain.QueryChain` that iterates through all dependent objects for given SQLAlchemy object.
[ "Return", "a", ":", "class", ":", "~sqlalchemy_utils", ".", "query_chain", ".", "QueryChain", "that", "iterates", "through", "all", "dependent", "objects", "for", "given", "SQLAlchemy", "object", "." ]
def dependent_objects(obj, foreign_keys=None): """ Return a :class:`~sqlalchemy_utils.query_chain.QueryChain` that iterates through all dependent objects for given SQLAlchemy object. Consider a User object is referenced in various articles and also in various orders. Getting all these dependent objects is as easy as:: from sqlalchemy_utils import dependent_objects dependent_objects(user) If you expect an object to have lots of dependent_objects it might be good to limit the results:: dependent_objects(user).limit(5) The common use case is checking for all restrict dependent objects before deleting parent object and inform the user if there are dependent objects with ondelete='RESTRICT' foreign keys. If this kind of checking is not used it will lead to nasty IntegrityErrors being raised. In the following example we delete given user if it doesn't have any foreign key restricted dependent objects:: from sqlalchemy_utils import get_referencing_foreign_keys user = session.query(User).get(some_user_id) deps = list( dependent_objects( user, ( fk for fk in get_referencing_foreign_keys(User) # On most databases RESTRICT is the default mode hence we # check for None values also if fk.ondelete == 'RESTRICT' or fk.ondelete is None ) ).limit(5) ) if deps: # Do something to inform the user pass else: session.delete(user) :param obj: SQLAlchemy declarative model object :param foreign_keys: A sequence of foreign keys to use for searching the dependent_objects for given object. By default this is None, indicating that all foreign keys referencing the object will be used. .. note:: This function does not support exotic mappers that use multiple tables .. seealso:: :func:`get_referencing_foreign_keys` .. seealso:: :func:`merge_references` .. versionadded: 0.26.0 """ if foreign_keys is None: foreign_keys = get_referencing_foreign_keys(obj) session = object_session(obj) chain = QueryChain([]) classes = _get_class_registry(obj.__class__) for table, keys in group_foreign_keys(foreign_keys): keys = list(keys) for class_ in classes.values(): try: mapper = sa.inspect(class_) except NoInspectionAvailable: continue parent_mapper = mapper.inherits if ( table in mapper.tables and not (parent_mapper and table in parent_mapper.tables) ): query = session.query(class_).filter( sa.or_(*_get_criteria(keys, class_, obj)) ) chain.queries.append(query) return chain
[ "def", "dependent_objects", "(", "obj", ",", "foreign_keys", "=", "None", ")", ":", "if", "foreign_keys", "is", "None", ":", "foreign_keys", "=", "get_referencing_foreign_keys", "(", "obj", ")", "session", "=", "object_session", "(", "obj", ")", "chain", "=", "QueryChain", "(", "[", "]", ")", "classes", "=", "_get_class_registry", "(", "obj", ".", "__class__", ")", "for", "table", ",", "keys", "in", "group_foreign_keys", "(", "foreign_keys", ")", ":", "keys", "=", "list", "(", "keys", ")", "for", "class_", "in", "classes", ".", "values", "(", ")", ":", "try", ":", "mapper", "=", "sa", ".", "inspect", "(", "class_", ")", "except", "NoInspectionAvailable", ":", "continue", "parent_mapper", "=", "mapper", ".", "inherits", "if", "(", "table", "in", "mapper", ".", "tables", "and", "not", "(", "parent_mapper", "and", "table", "in", "parent_mapper", ".", "tables", ")", ")", ":", "query", "=", "session", ".", "query", "(", "class_", ")", ".", "filter", "(", "sa", ".", "or_", "(", "*", "_get_criteria", "(", "keys", ",", "class_", ",", "obj", ")", ")", ")", "chain", ".", "queries", ".", "append", "(", "query", ")", "return", "chain" ]
https://github.com/kvesteri/sqlalchemy-utils/blob/850d0ea5a8a84c0529d175ee41b9036bea597119/sqlalchemy_utils/functions/foreign_keys.py#L192-L286
modoboa/modoboa
9065b7a5679fee149fc6f6f0e1760699c194cf89
modoboa/admin/models/mailbox.py
python
MailboxManager.get_for_admin
(self, admin, squery=None)
return self.get_queryset().select_related().filter(qf)
Return the mailboxes that belong to this admin. The result will contain the mailboxes defined for each domain that user can see. :param string squery: a search query :return: a list of ``Mailbox`` objects
Return the mailboxes that belong to this admin.
[ "Return", "the", "mailboxes", "that", "belong", "to", "this", "admin", "." ]
def get_for_admin(self, admin, squery=None): """Return the mailboxes that belong to this admin. The result will contain the mailboxes defined for each domain that user can see. :param string squery: a search query :return: a list of ``Mailbox`` objects """ qf = None if squery is not None: if "@" in squery: parts = squery.split("@") addrfilter = "@".join(parts[:-1]) domfilter = parts[-1] qf = ( Q(address__contains=addrfilter) & Q(domain__name__contains=domfilter) ) else: qf = ( Q(address__contains=squery) | Q(domain__name__contains=squery) ) ids = admin.objectaccess_set \ .filter(content_type=ContentType.objects.get_for_model(Mailbox)) \ .values_list("object_id", flat=True) if qf is not None: qf = Q(pk__in=ids) & qf else: qf = Q(pk__in=ids) return self.get_queryset().select_related().filter(qf)
[ "def", "get_for_admin", "(", "self", ",", "admin", ",", "squery", "=", "None", ")", ":", "qf", "=", "None", "if", "squery", "is", "not", "None", ":", "if", "\"@\"", "in", "squery", ":", "parts", "=", "squery", ".", "split", "(", "\"@\"", ")", "addrfilter", "=", "\"@\"", ".", "join", "(", "parts", "[", ":", "-", "1", "]", ")", "domfilter", "=", "parts", "[", "-", "1", "]", "qf", "=", "(", "Q", "(", "address__contains", "=", "addrfilter", ")", "&", "Q", "(", "domain__name__contains", "=", "domfilter", ")", ")", "else", ":", "qf", "=", "(", "Q", "(", "address__contains", "=", "squery", ")", "|", "Q", "(", "domain__name__contains", "=", "squery", ")", ")", "ids", "=", "admin", ".", "objectaccess_set", ".", "filter", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "Mailbox", ")", ")", ".", "values_list", "(", "\"object_id\"", ",", "flat", "=", "True", ")", "if", "qf", "is", "not", "None", ":", "qf", "=", "Q", "(", "pk__in", "=", "ids", ")", "&", "qf", "else", ":", "qf", "=", "Q", "(", "pk__in", "=", "ids", ")", "return", "self", ".", "get_queryset", "(", ")", ".", "select_related", "(", ")", ".", "filter", "(", "qf", ")" ]
https://github.com/modoboa/modoboa/blob/9065b7a5679fee149fc6f6f0e1760699c194cf89/modoboa/admin/models/mailbox.py#L54-L85
IDArlingTeam/IDArling
d15b9b7c8bdeb992c569efcc49adf7642bb82cdf
idarling/shared/packets.py
python
PacketDeferred.add_errback
(self, errback)
return self
Register an errback for this deferred.
Register an errback for this deferred.
[ "Register", "an", "errback", "for", "this", "deferred", "." ]
def add_errback(self, errback): """Register an errback for this deferred.""" self._errback = errback return self
[ "def", "add_errback", "(", "self", ",", "errback", ")", ":", "self", ".", "_errback", "=", "errback", "return", "self" ]
https://github.com/IDArlingTeam/IDArling/blob/d15b9b7c8bdeb992c569efcc49adf7642bb82cdf/idarling/shared/packets.py#L194-L197
GitGuardian/ggshield
94a1fa0f6402cd1df2dd3dbc5b932862e85f99e5
ggshield/output/text/message.py
python
leak_message_located
( flat_matches_dict: Dict[int, List[Match]], lines: List[Line], padding: int, offset: int, nb_lines: int, clip_long_lines: bool = False, )
return leak_msg.getvalue()
Display leak message of an incident with location in content. :param lines: The lines list :param line_index: The last index in the line :param detector_line: The list of detectors object in the line :param padding: The line padding :param offset: The offset due to the line display
Display leak message of an incident with location in content.
[ "Display", "leak", "message", "of", "an", "incident", "with", "location", "in", "content", "." ]
def leak_message_located( flat_matches_dict: Dict[int, List[Match]], lines: List[Line], padding: int, offset: int, nb_lines: int, clip_long_lines: bool = False, ) -> str: """ Display leak message of an incident with location in content. :param lines: The lines list :param line_index: The last index in the line :param detector_line: The list of detectors object in the line :param padding: The line padding :param offset: The offset due to the line display """ leak_msg = StringIO() max_width = shutil.get_terminal_size()[0] - offset if clip_long_lines else 0 lines_to_display = get_lines_to_display(flat_matches_dict, lines, nb_lines) old_line_number: Optional[int] = None for line_number in sorted(lines_to_display): multiline_end = None line = lines[line_number] line_content = line.content if old_line_number is not None and line_number - old_line_number != 1: leak_msg.write(format_line_count_break(padding)) # The current line number matches a found secret if line_number in flat_matches_dict: for flat_match in sorted( flat_matches_dict[line_number], key=lambda x: x.index_start, # type: ignore ): is_multiline = flat_match.line_start != flat_match.line_end if is_multiline: detector_position = float("inf"), float("-inf") # Iterate on the different (and consecutive) lines of the secret for match_line_index, match_line in enumerate( flat_match.match.splitlines(False) ): multiline_line_number = line_number + match_line_index leak_msg.write( lines[multiline_line_number].build_line_count( padding, is_secret=True ) ) if match_line_index == 0: # The first line of the secret may contain something else # before formatted_line, secret_position = format_line_with_secret( line_content, flat_match.index_start, len(line_content), max_width, ) elif multiline_line_number == flat_match.line_end: # The last line of the secret may contain something else # after last_line_content = lines[flat_match.line_end].content formatted_line, secret_position = format_line_with_secret( last_line_content, 0, len(match_line), max_width ) multiline_end = multiline_line_number else: # All the other lines have nothing else but a part of the # secret in them formatted_line, secret_position = format_line_with_secret( match_line, 0, len(match_line), max_width ) leak_msg.write(formatted_line) detector_position = ( min(detector_position[0], secret_position[0]), max(detector_position[1], secret_position[1]), ) else: leak_msg.write(line.build_line_count(padding, is_secret=True)) formatted_line, detector_position = format_line_with_secret( line_content, flat_match.index_start, flat_match.index_end, max_width, ) leak_msg.write(formatted_line) detector_position = int(detector_position[0]), int(detector_position[1]) detector = format_detector(flat_match.match_type, *detector_position) leak_msg.write(display_detector(detector, offset)) # The current line is just here for context else: leak_msg.write(line.build_line_count(padding, is_secret=False)) if clip_long_lines: line_content = clip_long_line(line_content, max_width, after=True) leak_msg.write(f"{display_patch(line_content)}\n") old_line_number = multiline_end if multiline_end else line_number return leak_msg.getvalue()
[ "def", "leak_message_located", "(", "flat_matches_dict", ":", "Dict", "[", "int", ",", "List", "[", "Match", "]", "]", ",", "lines", ":", "List", "[", "Line", "]", ",", "padding", ":", "int", ",", "offset", ":", "int", ",", "nb_lines", ":", "int", ",", "clip_long_lines", ":", "bool", "=", "False", ",", ")", "->", "str", ":", "leak_msg", "=", "StringIO", "(", ")", "max_width", "=", "shutil", ".", "get_terminal_size", "(", ")", "[", "0", "]", "-", "offset", "if", "clip_long_lines", "else", "0", "lines_to_display", "=", "get_lines_to_display", "(", "flat_matches_dict", ",", "lines", ",", "nb_lines", ")", "old_line_number", ":", "Optional", "[", "int", "]", "=", "None", "for", "line_number", "in", "sorted", "(", "lines_to_display", ")", ":", "multiline_end", "=", "None", "line", "=", "lines", "[", "line_number", "]", "line_content", "=", "line", ".", "content", "if", "old_line_number", "is", "not", "None", "and", "line_number", "-", "old_line_number", "!=", "1", ":", "leak_msg", ".", "write", "(", "format_line_count_break", "(", "padding", ")", ")", "# The current line number matches a found secret", "if", "line_number", "in", "flat_matches_dict", ":", "for", "flat_match", "in", "sorted", "(", "flat_matches_dict", "[", "line_number", "]", ",", "key", "=", "lambda", "x", ":", "x", ".", "index_start", ",", "# type: ignore", ")", ":", "is_multiline", "=", "flat_match", ".", "line_start", "!=", "flat_match", ".", "line_end", "if", "is_multiline", ":", "detector_position", "=", "float", "(", "\"inf\"", ")", ",", "float", "(", "\"-inf\"", ")", "# Iterate on the different (and consecutive) lines of the secret", "for", "match_line_index", ",", "match_line", "in", "enumerate", "(", "flat_match", ".", "match", ".", "splitlines", "(", "False", ")", ")", ":", "multiline_line_number", "=", "line_number", "+", "match_line_index", "leak_msg", ".", "write", "(", "lines", "[", "multiline_line_number", "]", ".", "build_line_count", "(", "padding", ",", "is_secret", "=", "True", ")", ")", "if", "match_line_index", "==", "0", ":", "# The first line of the secret may contain something else", "# before", "formatted_line", ",", "secret_position", "=", "format_line_with_secret", "(", "line_content", ",", "flat_match", ".", "index_start", ",", "len", "(", "line_content", ")", ",", "max_width", ",", ")", "elif", "multiline_line_number", "==", "flat_match", ".", "line_end", ":", "# The last line of the secret may contain something else", "# after", "last_line_content", "=", "lines", "[", "flat_match", ".", "line_end", "]", ".", "content", "formatted_line", ",", "secret_position", "=", "format_line_with_secret", "(", "last_line_content", ",", "0", ",", "len", "(", "match_line", ")", ",", "max_width", ")", "multiline_end", "=", "multiline_line_number", "else", ":", "# All the other lines have nothing else but a part of the", "# secret in them", "formatted_line", ",", "secret_position", "=", "format_line_with_secret", "(", "match_line", ",", "0", ",", "len", "(", "match_line", ")", ",", "max_width", ")", "leak_msg", ".", "write", "(", "formatted_line", ")", "detector_position", "=", "(", "min", "(", "detector_position", "[", "0", "]", ",", "secret_position", "[", "0", "]", ")", ",", "max", "(", "detector_position", "[", "1", "]", ",", "secret_position", "[", "1", "]", ")", ",", ")", "else", ":", "leak_msg", ".", "write", "(", "line", ".", "build_line_count", "(", "padding", ",", "is_secret", "=", "True", ")", ")", "formatted_line", ",", "detector_position", "=", "format_line_with_secret", "(", "line_content", ",", "flat_match", ".", "index_start", ",", "flat_match", ".", "index_end", ",", "max_width", ",", ")", "leak_msg", ".", "write", "(", "formatted_line", ")", "detector_position", "=", "int", "(", "detector_position", "[", "0", "]", ")", ",", "int", "(", "detector_position", "[", "1", "]", ")", "detector", "=", "format_detector", "(", "flat_match", ".", "match_type", ",", "*", "detector_position", ")", "leak_msg", ".", "write", "(", "display_detector", "(", "detector", ",", "offset", ")", ")", "# The current line is just here for context", "else", ":", "leak_msg", ".", "write", "(", "line", ".", "build_line_count", "(", "padding", ",", "is_secret", "=", "False", ")", ")", "if", "clip_long_lines", ":", "line_content", "=", "clip_long_line", "(", "line_content", ",", "max_width", ",", "after", "=", "True", ")", "leak_msg", ".", "write", "(", "f\"{display_patch(line_content)}\\n\"", ")", "old_line_number", "=", "multiline_end", "if", "multiline_end", "else", "line_number", "return", "leak_msg", ".", "getvalue", "(", ")" ]
https://github.com/GitGuardian/ggshield/blob/94a1fa0f6402cd1df2dd3dbc5b932862e85f99e5/ggshield/output/text/message.py#L19-L125
mathics/Mathics
318e06dea8f1c70758a50cb2f95c9900150e3a68
mathics/builtin/files_io/importexport.py
python
ImportString.apply_elements
(self, data, elements, evaluation, options={})
return self._import( None, determine_filetype, elements, evaluation, options, data=data )
ImportString[data_, elements_List?(AllTrue[#, NotOptionQ]&), OptionsPattern[]]
ImportString[data_, elements_List?(AllTrue[#, NotOptionQ]&), OptionsPattern[]]
[ "ImportString", "[", "data_", "elements_List?", "(", "AllTrue", "[", "#", "NotOptionQ", "]", "&", ")", "OptionsPattern", "[]", "]" ]
def apply_elements(self, data, elements, evaluation, options={}): "ImportString[data_, elements_List?(AllTrue[#, NotOptionQ]&), OptionsPattern[]]" if not (isinstance(data, String)): evaluation.message("ImportString", "string", data) return SymbolFailed path = data.get_string_value() def determine_filetype(): if not FileFormat.detector: loader = magic.MagicLoader() loader.load() FileFormat.detector = magic.MagicDetector(loader.mimetypes) mime = set(FileFormat.detector.match("", data=data.to_python())) result = [] for key in mimetype_dict.keys(): if key in mime: result.append(mimetype_dict[key]) # the following fixes an extremely annoying behaviour on some (not all) # installations of Windows, where we end up classifying .csv files als XLS. if ( len(result) == 1 and result[0] == "XLS" and path.lower().endswith(".csv") ): return String("CSV") if len(result) == 0: result = "Binary" elif len(result) == 1: result = result[0] else: return None return result return self._import( None, determine_filetype, elements, evaluation, options, data=data )
[ "def", "apply_elements", "(", "self", ",", "data", ",", "elements", ",", "evaluation", ",", "options", "=", "{", "}", ")", ":", "if", "not", "(", "isinstance", "(", "data", ",", "String", ")", ")", ":", "evaluation", ".", "message", "(", "\"ImportString\"", ",", "\"string\"", ",", "data", ")", "return", "SymbolFailed", "path", "=", "data", ".", "get_string_value", "(", ")", "def", "determine_filetype", "(", ")", ":", "if", "not", "FileFormat", ".", "detector", ":", "loader", "=", "magic", ".", "MagicLoader", "(", ")", "loader", ".", "load", "(", ")", "FileFormat", ".", "detector", "=", "magic", ".", "MagicDetector", "(", "loader", ".", "mimetypes", ")", "mime", "=", "set", "(", "FileFormat", ".", "detector", ".", "match", "(", "\"\"", ",", "data", "=", "data", ".", "to_python", "(", ")", ")", ")", "result", "=", "[", "]", "for", "key", "in", "mimetype_dict", ".", "keys", "(", ")", ":", "if", "key", "in", "mime", ":", "result", ".", "append", "(", "mimetype_dict", "[", "key", "]", ")", "# the following fixes an extremely annoying behaviour on some (not all)", "# installations of Windows, where we end up classifying .csv files als XLS.", "if", "(", "len", "(", "result", ")", "==", "1", "and", "result", "[", "0", "]", "==", "\"XLS\"", "and", "path", ".", "lower", "(", ")", ".", "endswith", "(", "\".csv\"", ")", ")", ":", "return", "String", "(", "\"CSV\"", ")", "if", "len", "(", "result", ")", "==", "0", ":", "result", "=", "\"Binary\"", "elif", "len", "(", "result", ")", "==", "1", ":", "result", "=", "result", "[", "0", "]", "else", ":", "return", "None", "return", "result", "return", "self", ".", "_import", "(", "None", ",", "determine_filetype", ",", "elements", ",", "evaluation", ",", "options", ",", "data", "=", "data", ")" ]
https://github.com/mathics/Mathics/blob/318e06dea8f1c70758a50cb2f95c9900150e3a68/mathics/builtin/files_io/importexport.py#L1611-L1650
gdraheim/docker-systemctl-replacement
9cbe1a00eb4bdac6ff05b96ca34ec9ed3d8fc06c
docker_mirror.py
python
DockerMirrorPackagesRepo.host_system_image
(self)
return ""
returns the docker image name which corresponds to the operating system distribution of the host system. This image name is the key for the other mirror functions.
returns the docker image name which corresponds to the operating system distribution of the host system. This image name is the key for the other mirror functions.
[ "returns", "the", "docker", "image", "name", "which", "corresponds", "to", "the", "operating", "system", "distribution", "of", "the", "host", "system", ".", "This", "image", "name", "is", "the", "key", "for", "the", "other", "mirror", "functions", "." ]
def host_system_image(self): """ returns the docker image name which corresponds to the operating system distribution of the host system. This image name is the key for the other mirror functions. """ distro, version = self.detect_etc_image("/etc") logg.info(":%s:%s host system image detected", distro, version) if distro and version: return "%s:%s" % (distro, version) return ""
[ "def", "host_system_image", "(", "self", ")", ":", "distro", ",", "version", "=", "self", ".", "detect_etc_image", "(", "\"/etc\"", ")", "logg", ".", "info", "(", "\":%s:%s host system image detected\"", ",", "distro", ",", "version", ")", "if", "distro", "and", "version", ":", "return", "\"%s:%s\"", "%", "(", "distro", ",", "version", ")", "return", "\"\"" ]
https://github.com/gdraheim/docker-systemctl-replacement/blob/9cbe1a00eb4bdac6ff05b96ca34ec9ed3d8fc06c/docker_mirror.py#L80-L88
pysmt/pysmt
ade4dc2a825727615033a96d31c71e9f53ce4764
pysmt/solvers/yices.py
python
init
()
[]
def init(): if not getattr(init, 'initialized', False): yicespy.yices_init() init.initialized = True
[ "def", "init", "(", ")", ":", "if", "not", "getattr", "(", "init", ",", "'initialized'", ",", "False", ")", ":", "yicespy", ".", "yices_init", "(", ")", "init", ".", "initialized", "=", "True" ]
https://github.com/pysmt/pysmt/blob/ade4dc2a825727615033a96d31c71e9f53ce4764/pysmt/solvers/yices.py#L44-L47
openstack/solum
93f8cc562d3c2ea0ab3af4061c07348e61f30806
solum/common/trace_data.py
python
TraceData.__init__
(self)
Initialize class storage.
Initialize class storage.
[ "Initialize", "class", "storage", "." ]
def __init__(self): """Initialize class storage.""" self.request_id = "<not set>" self._auto_clear = False self._user_data = {} self._support_data = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "request_id", "=", "\"<not set>\"", "self", ".", "_auto_clear", "=", "False", "self", ".", "_user_data", "=", "{", "}", "self", ".", "_support_data", "=", "{", "}" ]
https://github.com/openstack/solum/blob/93f8cc562d3c2ea0ab3af4061c07348e61f30806/solum/common/trace_data.py#L33-L38
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
calendarserver/tools/tables.py
python
Table.setData
(self, table)
[]
def setData(self, table): self.hasTitles = True self.headers.append(table[0]) self.rows = table[1:] self._getMaxColumnCount()
[ "def", "setData", "(", "self", ",", "table", ")", ":", "self", ".", "hasTitles", "=", "True", "self", ".", "headers", ".", "append", "(", "table", "[", "0", "]", ")", "self", ".", "rows", "=", "table", "[", "1", ":", "]", "self", ".", "_getMaxColumnCount", "(", ")" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/calendarserver/tools/tables.py#L68-L73
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/vendor/pydot/pydot.py
python
Graph.get_simplify
(self)
return self.obj_dict['simplify']
Get whether to simplify or not. Refer to set_simplify for more information.
Get whether to simplify or not.
[ "Get", "whether", "to", "simplify", "or", "not", "." ]
def get_simplify(self): """Get whether to simplify or not. Refer to set_simplify for more information. """ return self.obj_dict['simplify']
[ "def", "get_simplify", "(", "self", ")", ":", "return", "self", ".", "obj_dict", "[", "'simplify'", "]" ]
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/vendor/pydot/pydot.py#L1030-L1036
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/galgebra/ga.py
python
MV.reduce_basis_loop
(blst)
return True
blst is a list of integers [i_{1},...,i_{r}] representing the geometric product of r basis vectors a_{{i_1}}*...*a_{{i_r}}. reduce_basis_loop searches along the list [i_{1},...,i_{r}] untill it finds i_{j} == i_{j+1} and in this case contracts the list, or if i_{j} > i_{j+1} it revises the list (~i_{j} means remove i_{j} from the list) Case 1: If i_{j} == i_{j+1}, return a_{i_{j}}**2 and [i_{1},..,~i_{j},~i_{j+1},...,i_{r}] Case 2: If i_{j} > i_{j+1}, return a_{i_{j}}.a_{i_{j+1}}, [i_{1},..,~i_{j},~i_{j+1},...,i_{r}], and [i_{1},..,i_{j+1},i_{j},...,i_{r}]
blst is a list of integers [i_{1},...,i_{r}] representing the geometric product of r basis vectors a_{{i_1}}*...*a_{{i_r}}. reduce_basis_loop searches along the list [i_{1},...,i_{r}] untill it finds i_{j} == i_{j+1} and in this case contracts the list, or if i_{j} > i_{j+1} it revises the list (~i_{j} means remove i_{j} from the list)
[ "blst", "is", "a", "list", "of", "integers", "[", "i_", "{", "1", "}", "...", "i_", "{", "r", "}", "]", "representing", "the", "geometric", "product", "of", "r", "basis", "vectors", "a_", "{{", "i_1", "}}", "*", "...", "*", "a_", "{{", "i_r", "}}", ".", "reduce_basis_loop", "searches", "along", "the", "list", "[", "i_", "{", "1", "}", "...", "i_", "{", "r", "}", "]", "untill", "it", "finds", "i_", "{", "j", "}", "==", "i_", "{", "j", "+", "1", "}", "and", "in", "this", "case", "contracts", "the", "list", "or", "if", "i_", "{", "j", "}", ">", "i_", "{", "j", "+", "1", "}", "it", "revises", "the", "list", "(", "~i_", "{", "j", "}", "means", "remove", "i_", "{", "j", "}", "from", "the", "list", ")" ]
def reduce_basis_loop(blst): """ blst is a list of integers [i_{1},...,i_{r}] representing the geometric product of r basis vectors a_{{i_1}}*...*a_{{i_r}}. reduce_basis_loop searches along the list [i_{1},...,i_{r}] untill it finds i_{j} == i_{j+1} and in this case contracts the list, or if i_{j} > i_{j+1} it revises the list (~i_{j} means remove i_{j} from the list) Case 1: If i_{j} == i_{j+1}, return a_{i_{j}}**2 and [i_{1},..,~i_{j},~i_{j+1},...,i_{r}] Case 2: If i_{j} > i_{j+1}, return a_{i_{j}}.a_{i_{j+1}}, [i_{1},..,~i_{j},~i_{j+1},...,i_{r}], and [i_{1},..,i_{j+1},i_{j},...,i_{r}] """ nblst = len(blst) # number of basis vectors if nblst <= 1: return True # a scalar or vector is already reduced jstep = 1 while jstep < nblst: istep = jstep - 1 if blst[istep] == blst[jstep]: # basis vectorindex is repeated i = blst[istep] # save basis vector index if len(blst) > 2: blst = blst[:istep] + blst[jstep + 1:] # contract blst else: blst = [] if len(blst) <= 1 or jstep == nblst - 1: blst_flg = True # revision of blst is complete else: blst_flg = False # more revision needed return MV.metric[i, i], blst, blst_flg if blst[istep] > blst[jstep]: # blst not in normal order blst1 = blst[:istep] + blst[jstep + 1:] # contract blst a1 = MV.metric2[blst[jstep], blst[istep]] # coef of contraction blst = blst[:istep] + [blst[jstep]] + [blst[istep]] + blst[jstep + 1:] # revise blst if len(blst1) <= 1: blst1_flg = True # revision of blst is complete else: blst1_flg = False # more revision needed return a1, blst1, blst1_flg, blst jstep += 1 return True
[ "def", "reduce_basis_loop", "(", "blst", ")", ":", "nblst", "=", "len", "(", "blst", ")", "# number of basis vectors", "if", "nblst", "<=", "1", ":", "return", "True", "# a scalar or vector is already reduced", "jstep", "=", "1", "while", "jstep", "<", "nblst", ":", "istep", "=", "jstep", "-", "1", "if", "blst", "[", "istep", "]", "==", "blst", "[", "jstep", "]", ":", "# basis vectorindex is repeated", "i", "=", "blst", "[", "istep", "]", "# save basis vector index", "if", "len", "(", "blst", ")", ">", "2", ":", "blst", "=", "blst", "[", ":", "istep", "]", "+", "blst", "[", "jstep", "+", "1", ":", "]", "# contract blst", "else", ":", "blst", "=", "[", "]", "if", "len", "(", "blst", ")", "<=", "1", "or", "jstep", "==", "nblst", "-", "1", ":", "blst_flg", "=", "True", "# revision of blst is complete", "else", ":", "blst_flg", "=", "False", "# more revision needed", "return", "MV", ".", "metric", "[", "i", ",", "i", "]", ",", "blst", ",", "blst_flg", "if", "blst", "[", "istep", "]", ">", "blst", "[", "jstep", "]", ":", "# blst not in normal order", "blst1", "=", "blst", "[", ":", "istep", "]", "+", "blst", "[", "jstep", "+", "1", ":", "]", "# contract blst", "a1", "=", "MV", ".", "metric2", "[", "blst", "[", "jstep", "]", ",", "blst", "[", "istep", "]", "]", "# coef of contraction", "blst", "=", "blst", "[", ":", "istep", "]", "+", "[", "blst", "[", "jstep", "]", "]", "+", "[", "blst", "[", "istep", "]", "]", "+", "blst", "[", "jstep", "+", "1", ":", "]", "# revise blst", "if", "len", "(", "blst1", ")", "<=", "1", ":", "blst1_flg", "=", "True", "# revision of blst is complete", "else", ":", "blst1_flg", "=", "False", "# more revision needed", "return", "a1", ",", "blst1", ",", "blst1_flg", ",", "blst", "jstep", "+=", "1", "return", "True" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/galgebra/ga.py#L1232-L1274
horazont/aioxmpp
c701e6399c90a6bb9bec0349018a03bd7b644cde
aioxmpp/cache.py
python
LRUDict._test_consistency
(self)
return (_length(self.__root) == len(self.__links) and _has_consistent_links(self.__root, self.__links))
This method is only used for testing to assert that the operations leave the LRUDict in a valid state.
This method is only used for testing to assert that the operations leave the LRUDict in a valid state.
[ "This", "method", "is", "only", "used", "for", "testing", "to", "assert", "that", "the", "operations", "leave", "the", "LRUDict", "in", "a", "valid", "state", "." ]
def _test_consistency(self): """ This method is only used for testing to assert that the operations leave the LRUDict in a valid state. """ return (_length(self.__root) == len(self.__links) and _has_consistent_links(self.__root, self.__links))
[ "def", "_test_consistency", "(", "self", ")", ":", "return", "(", "_length", "(", "self", ".", "__root", ")", "==", "len", "(", "self", ".", "__links", ")", "and", "_has_consistent_links", "(", "self", ".", "__root", ",", "self", ".", "__links", ")", ")" ]
https://github.com/horazont/aioxmpp/blob/c701e6399c90a6bb9bec0349018a03bd7b644cde/aioxmpp/cache.py#L112-L118
WerWolv/EdiZon_CheatsConfigsAndScripts
d16d36c7509c01dca770f402babd83ff2e9ae6e7
Scripts/lib/python3.5/threading.py
python
Thread.name
(self)
return self._name
A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.
A string used for identification purposes only.
[ "A", "string", "used", "for", "identification", "purposes", "only", "." ]
def name(self): """A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. """ assert self._initialized, "Thread.__init__() not called" return self._name
[ "def", "name", "(", "self", ")", ":", "assert", "self", ".", "_initialized", ",", "\"Thread.__init__() not called\"", "return", "self", ".", "_name" ]
https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/threading.py#L1075-L1083
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
tools/xsser/XSSer/main.py
python
xsser.run
(self, opts=None)
Run xsser.
Run xsser.
[ "Run", "xsser", "." ]
def run(self, opts=None): """ Run xsser. """ self._landing = False for reporter in self._reporters: reporter.start_attack() if opts: options = self.create_options(opts) self.set_options(options) if not self.mothership and not self.hub: self.hub = HubThread(self) self.hub.start() options = self.options # step 0: third party tricks if options.imx: # create -fake- image with code injected p = self.optionParser self.report('='*75) self.report(str(p.version)) self.report('='*75) self.report("[Image XSS auto-builder]...remember, only IE6 and below versions ;)") self.report('='*75) self.report(''.join(self.create_fake_image(self.options.imx, self.options.script))) self.report('='*75 + "\n") if options.flash: # create -fake- flash movie (.swf) with code injected p = self.optionParser self.report('='*75) self.report(str(p.version)) self.report('='*75) self.report("[Flash Attack! XSS auto-builder]...ready to be embedded ;)") self.report('='*75) self.report(''.join(self.create_fake_flash(self.options.flash, self.options.script))) self.report('='*75 + "\n") if options.xsser_gtk: self.create_gtk_interface() return nthreads = max(1, abs(options.threads)) nworkers = len(self.pool.workers) if nthreads != nworkers: if nthreads < nworkers: self.pool.dismissWorkers(nworkers-nthreads) else: self.pool.createWorkers(nthreads-nworkers) for reporter in self._reporters: reporter.report_state('scanning') # step 1: get urls urls = self.try_running(self._get_attack_urls, "\nInternal error getting -targets-. look at the end of this Traceback to see whats wrong") for reporter in self._reporters: reporter.report_state('arming') # step 2: get payloads payloads = self.try_running(self.get_payloads, "\nInternal error getting -payloads-") for reporter in self._reporters: reporter.report_state('cloaking') if options.Dwo: payloads = self.process_payloads_ipfuzzing(payloads) elif options.Doo: payloads = self.process_payloads_ipfuzzing_octal(payloads) for reporter in self._reporters: reporter.report_state('locking targets') # step 3: get query string query_string = self.try_running(self.get_query_string, "\nInternal error getting query -string-") # step 4: print curl options if requested if options.verbose: Curl.print_options() for reporter in self._reporters: reporter.report_state('sanitize') urls = self.sanitize_urls(urls) for reporter in self._reporters: reporter.report_state('attack') # step 5: perform attack self.try_running(self.attack, "\nInternal problems running attack: ", (urls, payloads, query_string)) for reporter in self._reporters: reporter.report_state('reporting') if len(self.final_attacks): self.report("Waiting for tokens to arrive") while self._ongoing_requests and not self._landing: if not self.pool: self.mothership.poll_workers() else: self.poll_workers() time.sleep(0.2) for reporter in self._reporters: reporter.report_state('final sweep..') print("="*75 + "\n") if self.pool: self.pool.dismissWorkers(len(self.pool.workers)) self.pool.joinAllDismissedWorkers() start = time.time() while not self._landing and len(self.final_attacks) and time.time() - start < 5.0: time.sleep(0.2) for reporter in self._reporters: reporter.report_state('landing.. '+str(int(5.0 - (time.time() - start)))) if self.final_attacks: self.report("Forcing a reverse connection XSSer will certificate that your target is 100% vulnerable\n") for final_attack in self.final_attacks.itervalues(): if not final_attack['url'] == None: self.report("Connecting from:", final_attack['url'] , "\n") self.report(",".join(self.successfull_urls) , "is connecting remotely to XSSer... You have it! ;-)", "\n") self.report("="*50 + "\n") for reporter in self._reporters: reporter.end_attack() if self.mothership: self.mothership.remove_reporter(self) print("="*75 + "\n") self.report("Mosquito(s) landed!\n") else: self.report("Mosquito(s) landed!") self.print_results()
[ "def", "run", "(", "self", ",", "opts", "=", "None", ")", ":", "self", ".", "_landing", "=", "False", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "start_attack", "(", ")", "if", "opts", ":", "options", "=", "self", ".", "create_options", "(", "opts", ")", "self", ".", "set_options", "(", "options", ")", "if", "not", "self", ".", "mothership", "and", "not", "self", ".", "hub", ":", "self", ".", "hub", "=", "HubThread", "(", "self", ")", "self", ".", "hub", ".", "start", "(", ")", "options", "=", "self", ".", "options", "# step 0: third party tricks", "if", "options", ".", "imx", ":", "# create -fake- image with code injected", "p", "=", "self", ".", "optionParser", "self", ".", "report", "(", "'='", "*", "75", ")", "self", ".", "report", "(", "str", "(", "p", ".", "version", ")", ")", "self", ".", "report", "(", "'='", "*", "75", ")", "self", ".", "report", "(", "\"[Image XSS auto-builder]...remember, only IE6 and below versions ;)\"", ")", "self", ".", "report", "(", "'='", "*", "75", ")", "self", ".", "report", "(", "''", ".", "join", "(", "self", ".", "create_fake_image", "(", "self", ".", "options", ".", "imx", ",", "self", ".", "options", ".", "script", ")", ")", ")", "self", ".", "report", "(", "'='", "*", "75", "+", "\"\\n\"", ")", "if", "options", ".", "flash", ":", "# create -fake- flash movie (.swf) with code injected", "p", "=", "self", ".", "optionParser", "self", ".", "report", "(", "'='", "*", "75", ")", "self", ".", "report", "(", "str", "(", "p", ".", "version", ")", ")", "self", ".", "report", "(", "'='", "*", "75", ")", "self", ".", "report", "(", "\"[Flash Attack! XSS auto-builder]...ready to be embedded ;)\"", ")", "self", ".", "report", "(", "'='", "*", "75", ")", "self", ".", "report", "(", "''", ".", "join", "(", "self", ".", "create_fake_flash", "(", "self", ".", "options", ".", "flash", ",", "self", ".", "options", ".", "script", ")", ")", ")", "self", ".", "report", "(", "'='", "*", "75", "+", "\"\\n\"", ")", "if", "options", ".", "xsser_gtk", ":", "self", ".", "create_gtk_interface", "(", ")", "return", "nthreads", "=", "max", "(", "1", ",", "abs", "(", "options", ".", "threads", ")", ")", "nworkers", "=", "len", "(", "self", ".", "pool", ".", "workers", ")", "if", "nthreads", "!=", "nworkers", ":", "if", "nthreads", "<", "nworkers", ":", "self", ".", "pool", ".", "dismissWorkers", "(", "nworkers", "-", "nthreads", ")", "else", ":", "self", ".", "pool", ".", "createWorkers", "(", "nthreads", "-", "nworkers", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "report_state", "(", "'scanning'", ")", "# step 1: get urls", "urls", "=", "self", ".", "try_running", "(", "self", ".", "_get_attack_urls", ",", "\"\\nInternal error getting -targets-. look at the end of this Traceback to see whats wrong\"", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "report_state", "(", "'arming'", ")", "# step 2: get payloads", "payloads", "=", "self", ".", "try_running", "(", "self", ".", "get_payloads", ",", "\"\\nInternal error getting -payloads-\"", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "report_state", "(", "'cloaking'", ")", "if", "options", ".", "Dwo", ":", "payloads", "=", "self", ".", "process_payloads_ipfuzzing", "(", "payloads", ")", "elif", "options", ".", "Doo", ":", "payloads", "=", "self", ".", "process_payloads_ipfuzzing_octal", "(", "payloads", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "report_state", "(", "'locking targets'", ")", "# step 3: get query string", "query_string", "=", "self", ".", "try_running", "(", "self", ".", "get_query_string", ",", "\"\\nInternal error getting query -string-\"", ")", "# step 4: print curl options if requested", "if", "options", ".", "verbose", ":", "Curl", ".", "print_options", "(", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "report_state", "(", "'sanitize'", ")", "urls", "=", "self", ".", "sanitize_urls", "(", "urls", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "report_state", "(", "'attack'", ")", "# step 5: perform attack", "self", ".", "try_running", "(", "self", ".", "attack", ",", "\"\\nInternal problems running attack: \"", ",", "(", "urls", ",", "payloads", ",", "query_string", ")", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "report_state", "(", "'reporting'", ")", "if", "len", "(", "self", ".", "final_attacks", ")", ":", "self", ".", "report", "(", "\"Waiting for tokens to arrive\"", ")", "while", "self", ".", "_ongoing_requests", "and", "not", "self", ".", "_landing", ":", "if", "not", "self", ".", "pool", ":", "self", ".", "mothership", ".", "poll_workers", "(", ")", "else", ":", "self", ".", "poll_workers", "(", ")", "time", ".", "sleep", "(", "0.2", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "report_state", "(", "'final sweep..'", ")", "print", "(", "\"=\"", "*", "75", "+", "\"\\n\"", ")", "if", "self", ".", "pool", ":", "self", ".", "pool", ".", "dismissWorkers", "(", "len", "(", "self", ".", "pool", ".", "workers", ")", ")", "self", ".", "pool", ".", "joinAllDismissedWorkers", "(", ")", "start", "=", "time", ".", "time", "(", ")", "while", "not", "self", ".", "_landing", "and", "len", "(", "self", ".", "final_attacks", ")", "and", "time", ".", "time", "(", ")", "-", "start", "<", "5.0", ":", "time", ".", "sleep", "(", "0.2", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "report_state", "(", "'landing.. '", "+", "str", "(", "int", "(", "5.0", "-", "(", "time", ".", "time", "(", ")", "-", "start", ")", ")", ")", ")", "if", "self", ".", "final_attacks", ":", "self", ".", "report", "(", "\"Forcing a reverse connection XSSer will certificate that your target is 100% vulnerable\\n\"", ")", "for", "final_attack", "in", "self", ".", "final_attacks", ".", "itervalues", "(", ")", ":", "if", "not", "final_attack", "[", "'url'", "]", "==", "None", ":", "self", ".", "report", "(", "\"Connecting from:\"", ",", "final_attack", "[", "'url'", "]", ",", "\"\\n\"", ")", "self", ".", "report", "(", "\",\"", ".", "join", "(", "self", ".", "successfull_urls", ")", ",", "\"is connecting remotely to XSSer... You have it! ;-)\"", ",", "\"\\n\"", ")", "self", ".", "report", "(", "\"=\"", "*", "50", "+", "\"\\n\"", ")", "for", "reporter", "in", "self", ".", "_reporters", ":", "reporter", ".", "end_attack", "(", ")", "if", "self", ".", "mothership", ":", "self", ".", "mothership", ".", "remove_reporter", "(", "self", ")", "print", "(", "\"=\"", "*", "75", "+", "\"\\n\"", ")", "self", ".", "report", "(", "\"Mosquito(s) landed!\\n\"", ")", "else", ":", "self", ".", "report", "(", "\"Mosquito(s) landed!\"", ")", "self", ".", "print_results", "(", ")" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/tools/xsser/XSSer/main.py#L1378-L1501
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/geometry/polyhedron/modules/formal_polyhedra_module.py
python
FormalPolyhedraModule.__classcall__
(cls, base_ring, dimension, basis, category=None)
return super(FormalPolyhedraModule, cls).__classcall__(cls, base_ring=base_ring, dimension=dimension, basis=basis, category=category)
r""" Normalize the arguments for caching. TESTS:: sage: from sage.geometry.polyhedron.modules.formal_polyhedra_module import FormalPolyhedraModule sage: FormalPolyhedraModule(QQ, 1, ()) is FormalPolyhedraModule(QQ, 1, []) True
r""" Normalize the arguments for caching.
[ "r", "Normalize", "the", "arguments", "for", "caching", "." ]
def __classcall__(cls, base_ring, dimension, basis, category=None): r""" Normalize the arguments for caching. TESTS:: sage: from sage.geometry.polyhedron.modules.formal_polyhedra_module import FormalPolyhedraModule sage: FormalPolyhedraModule(QQ, 1, ()) is FormalPolyhedraModule(QQ, 1, []) True """ if isinstance(basis, list): basis = tuple(basis) if category is None: category = GradedModulesWithBasis(base_ring) return super(FormalPolyhedraModule, cls).__classcall__(cls, base_ring=base_ring, dimension=dimension, basis=basis, category=category)
[ "def", "__classcall__", "(", "cls", ",", "base_ring", ",", "dimension", ",", "basis", ",", "category", "=", "None", ")", ":", "if", "isinstance", "(", "basis", ",", "list", ")", ":", "basis", "=", "tuple", "(", "basis", ")", "if", "category", "is", "None", ":", "category", "=", "GradedModulesWithBasis", "(", "base_ring", ")", "return", "super", "(", "FormalPolyhedraModule", ",", "cls", ")", ".", "__classcall__", "(", "cls", ",", "base_ring", "=", "base_ring", ",", "dimension", "=", "dimension", ",", "basis", "=", "basis", ",", "category", "=", "category", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/geometry/polyhedron/modules/formal_polyhedra_module.py#L74-L92
NVIDIA-AI-IOT/torch2trt
2732b35ac4dbe3d6e93cd74910af4e4729f1d93b
examples/contrib/quantization_aware_training/models/resnet.py
python
wide_resnet50_2
(pretrained=False, progress=True, **kwargs)
return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
r"""Wide ResNet-50-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_ The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 channels, and in Wide ResNet-50-2 has 2048-1024-2048. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
r"""Wide ResNet-50-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
[ "r", "Wide", "ResNet", "-", "50", "-", "2", "model", "from", "Wide", "Residual", "Networks", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1605", ".", "07146", ".", "pdf", ">", "_" ]
def wide_resnet50_2(pretrained=False, progress=True, **kwargs): r"""Wide ResNet-50-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_ The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 channels, and in Wide ResNet-50-2 has 2048-1024-2048. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ kwargs['width_per_group'] = 64 * 2 return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
[ "def", "wide_resnet50_2", "(", "pretrained", "=", "False", ",", "progress", "=", "True", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'width_per_group'", "]", "=", "64", "*", "2", "return", "_resnet", "(", "'wide_resnet50_2'", ",", "Bottleneck", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",", "pretrained", ",", "progress", ",", "*", "*", "kwargs", ")" ]
https://github.com/NVIDIA-AI-IOT/torch2trt/blob/2732b35ac4dbe3d6e93cd74910af4e4729f1d93b/examples/contrib/quantization_aware_training/models/resnet.py#L311-L326
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/core/grr_response_core/lib/interpolation.py
python
Substitution.__init__
(self, var_config: VarConfig, scope_config: ScopeConfig)
Initializes the substitution environment. Args: var_config: A configuration (concrete values) of pattern variables. scope_config: A configuration (concrete values) of pattern scopes.
Initializes the substitution environment.
[ "Initializes", "the", "substitution", "environment", "." ]
def __init__(self, var_config: VarConfig, scope_config: ScopeConfig): """Initializes the substitution environment. Args: var_config: A configuration (concrete values) of pattern variables. scope_config: A configuration (concrete values) of pattern scopes. """ self._substs = {} self._var_config = var_config self._scope_config = scope_config for var_id, var_value in var_config.items(): key = "%%{var}%%".format(var=var_id) self._substs[key] = str(var_value) for scope_id, var_config in scope_config.items(): for var_id, var_value in var_config.items(): key = "%%{scope}.{var}%%".format(scope=scope_id, var=var_id) self._substs[key] = str(var_value)
[ "def", "__init__", "(", "self", ",", "var_config", ":", "VarConfig", ",", "scope_config", ":", "ScopeConfig", ")", ":", "self", ".", "_substs", "=", "{", "}", "self", ".", "_var_config", "=", "var_config", "self", ".", "_scope_config", "=", "scope_config", "for", "var_id", ",", "var_value", "in", "var_config", ".", "items", "(", ")", ":", "key", "=", "\"%%{var}%%\"", ".", "format", "(", "var", "=", "var_id", ")", "self", ".", "_substs", "[", "key", "]", "=", "str", "(", "var_value", ")", "for", "scope_id", ",", "var_config", "in", "scope_config", ".", "items", "(", ")", ":", "for", "var_id", ",", "var_value", "in", "var_config", ".", "items", "(", ")", ":", "key", "=", "\"%%{scope}.{var}%%\"", ".", "format", "(", "scope", "=", "scope_id", ",", "var", "=", "var_id", ")", "self", ".", "_substs", "[", "key", "]", "=", "str", "(", "var_value", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/core/grr_response_core/lib/interpolation.py#L28-L46
nodesign/weio
1d67d705a5c36a2e825ad13feab910b0aca9a2e8
openWrt/files/usr/lib/python2.7/site-packages/tornado/gen.py
python
engine
(func)
return wrapper
Callback-oriented decorator for asynchronous generators. This is an older interface; for new code that does not need to be compatible with versions of Tornado older than 3.0 the `coroutine` decorator is recommended instead. This decorator is similar to `coroutine`, except it does not return a `.Future` and the ``callback`` argument is not treated specially. In most cases, functions decorated with `engine` should take a ``callback`` argument and invoke it with their result when they are finished. One notable exception is the `~tornado.web.RequestHandler` ``get``/``post``/etc methods, which use ``self.finish()`` in place of a callback argument.
Callback-oriented decorator for asynchronous generators.
[ "Callback", "-", "oriented", "decorator", "for", "asynchronous", "generators", "." ]
def engine(func): """Callback-oriented decorator for asynchronous generators. This is an older interface; for new code that does not need to be compatible with versions of Tornado older than 3.0 the `coroutine` decorator is recommended instead. This decorator is similar to `coroutine`, except it does not return a `.Future` and the ``callback`` argument is not treated specially. In most cases, functions decorated with `engine` should take a ``callback`` argument and invoke it with their result when they are finished. One notable exception is the `~tornado.web.RequestHandler` ``get``/``post``/etc methods, which use ``self.finish()`` in place of a callback argument. """ @functools.wraps(func) def wrapper(*args, **kwargs): runner = None def handle_exception(typ, value, tb): # if the function throws an exception before its first "yield" # (or is not a generator at all), the Runner won't exist yet. # However, in that case we haven't reached anything asynchronous # yet, so we can just let the exception propagate. if runner is not None: return runner.handle_exception(typ, value, tb) return False with ExceptionStackContext(handle_exception) as deactivate: try: result = func(*args, **kwargs) except (Return, StopIteration) as e: result = getattr(e, 'value', None) else: if isinstance(result, types.GeneratorType): def final_callback(value): if value is not None: raise ReturnValueIgnoredError( "@gen.engine functions cannot return values: " "%r" % (value,)) assert value is None deactivate() runner = Runner(result, final_callback) runner.run() return if result is not None: raise ReturnValueIgnoredError( "@gen.engine functions cannot return values: %r" % (result,)) deactivate() # no yield, so we're done return wrapper
[ "def", "engine", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "runner", "=", "None", "def", "handle_exception", "(", "typ", ",", "value", ",", "tb", ")", ":", "# if the function throws an exception before its first \"yield\"", "# (or is not a generator at all), the Runner won't exist yet.", "# However, in that case we haven't reached anything asynchronous", "# yet, so we can just let the exception propagate.", "if", "runner", "is", "not", "None", ":", "return", "runner", ".", "handle_exception", "(", "typ", ",", "value", ",", "tb", ")", "return", "False", "with", "ExceptionStackContext", "(", "handle_exception", ")", "as", "deactivate", ":", "try", ":", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "(", "Return", ",", "StopIteration", ")", "as", "e", ":", "result", "=", "getattr", "(", "e", ",", "'value'", ",", "None", ")", "else", ":", "if", "isinstance", "(", "result", ",", "types", ".", "GeneratorType", ")", ":", "def", "final_callback", "(", "value", ")", ":", "if", "value", "is", "not", "None", ":", "raise", "ReturnValueIgnoredError", "(", "\"@gen.engine functions cannot return values: \"", "\"%r\"", "%", "(", "value", ",", ")", ")", "assert", "value", "is", "None", "deactivate", "(", ")", "runner", "=", "Runner", "(", "result", ",", "final_callback", ")", "runner", ".", "run", "(", ")", "return", "if", "result", "is", "not", "None", ":", "raise", "ReturnValueIgnoredError", "(", "\"@gen.engine functions cannot return values: %r\"", "%", "(", "result", ",", ")", ")", "deactivate", "(", ")", "# no yield, so we're done", "return", "wrapper" ]
https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/openWrt/files/usr/lib/python2.7/site-packages/tornado/gen.py#L110-L162
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/mechanize/_useragent.py
python
UserAgentBase.set_handle_refresh
(self, handle, max_time=None, honor_time=True)
Set whether to handle HTTP Refresh headers.
Set whether to handle HTTP Refresh headers.
[ "Set", "whether", "to", "handle", "HTTP", "Refresh", "headers", "." ]
def set_handle_refresh(self, handle, max_time=None, honor_time=True): """Set whether to handle HTTP Refresh headers.""" self._set_handler("_refresh", handle, constructor_kwds= {"max_time": max_time, "honor_time": honor_time})
[ "def", "set_handle_refresh", "(", "self", ",", "handle", ",", "max_time", "=", "None", ",", "honor_time", "=", "True", ")", ":", "self", ".", "_set_handler", "(", "\"_refresh\"", ",", "handle", ",", "constructor_kwds", "=", "{", "\"max_time\"", ":", "max_time", ",", "\"honor_time\"", ":", "honor_time", "}", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/mechanize/_useragent.py#L249-L252
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
scripts/dataset_processing/get_hi-mia_data.py
python
__maybe_download_file
(destination: str, source: str)
return destination
Downloads source to destination if it doesn't exist. If exists, skips download Args: destination: local filepath source: url of resource Returns:
Downloads source to destination if it doesn't exist. If exists, skips download Args: destination: local filepath source: url of resource
[ "Downloads", "source", "to", "destination", "if", "it", "doesn", "t", "exist", ".", "If", "exists", "skips", "download", "Args", ":", "destination", ":", "local", "filepath", "source", ":", "url", "of", "resource" ]
def __maybe_download_file(destination: str, source: str): """ Downloads source to destination if it doesn't exist. If exists, skips download Args: destination: local filepath source: url of resource Returns: """ source = URL[source] if not os.path.exists(destination) and not os.path.exists(os.path.splitext(destination)[0]): logging.info("{0} does not exist. Downloading ...".format(destination)) __retrieve_with_progress(source, filename=destination + ".tmp") os.rename(destination + ".tmp", destination) logging.info("Downloaded {0}.".format(destination)) elif os.path.exists(destination): logging.info("Destination {0} exists. Skipping.".format(destination)) elif os.path.exists(os.path.splitext(destination)[0]): logging.warning( "Assuming extracted folder %s contains the extracted files from %s. Will not download.", os.path.basename(destination), destination, ) return destination
[ "def", "__maybe_download_file", "(", "destination", ":", "str", ",", "source", ":", "str", ")", ":", "source", "=", "URL", "[", "source", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "destination", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "splitext", "(", "destination", ")", "[", "0", "]", ")", ":", "logging", ".", "info", "(", "\"{0} does not exist. Downloading ...\"", ".", "format", "(", "destination", ")", ")", "__retrieve_with_progress", "(", "source", ",", "filename", "=", "destination", "+", "\".tmp\"", ")", "os", ".", "rename", "(", "destination", "+", "\".tmp\"", ",", "destination", ")", "logging", ".", "info", "(", "\"Downloaded {0}.\"", ".", "format", "(", "destination", ")", ")", "elif", "os", ".", "path", ".", "exists", "(", "destination", ")", ":", "logging", ".", "info", "(", "\"Destination {0} exists. Skipping.\"", ".", "format", "(", "destination", ")", ")", "elif", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "splitext", "(", "destination", ")", "[", "0", "]", ")", ":", "logging", ".", "warning", "(", "\"Assuming extracted folder %s contains the extracted files from %s. Will not download.\"", ",", "os", ".", "path", ".", "basename", "(", "destination", ")", ",", "destination", ",", ")", "return", "destination" ]
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/scripts/dataset_processing/get_hi-mia_data.py#L66-L91
heynemann/pyccuracy
0bbe3bcff4d13a6501bf77d5af9457f6a1491ab6
pyccuracy/django/management/commands/pyccuracy.py
python
Command.locate_resource_dirs
(self, complement, pattern="*.*", recursive=True, apps=[])
return dirs
[]
def locate_resource_dirs(self, complement, pattern="*.*", recursive=True, apps=[]): dirs = [] for app in settings.INSTALLED_APPS: fromlist = "" if len(app.split("."))>1: fromlist = ".".join(app.split(".")[1:]) if app.startswith('django'): continue if apps and not app in apps: continue module = __import__(app, fromlist=fromlist) app_dir = abspath("/" + "/".join(module.__file__.split("/")[1:-1])) resource_dir = join(app_dir, complement) if exists(resource_dir) and locate(pattern, resource_dir, recursive): dirs.append(resource_dir) return dirs
[ "def", "locate_resource_dirs", "(", "self", ",", "complement", ",", "pattern", "=", "\"*.*\"", ",", "recursive", "=", "True", ",", "apps", "=", "[", "]", ")", ":", "dirs", "=", "[", "]", "for", "app", "in", "settings", ".", "INSTALLED_APPS", ":", "fromlist", "=", "\"\"", "if", "len", "(", "app", ".", "split", "(", "\".\"", ")", ")", ">", "1", ":", "fromlist", "=", "\".\"", ".", "join", "(", "app", ".", "split", "(", "\".\"", ")", "[", "1", ":", "]", ")", "if", "app", ".", "startswith", "(", "'django'", ")", ":", "continue", "if", "apps", "and", "not", "app", "in", "apps", ":", "continue", "module", "=", "__import__", "(", "app", ",", "fromlist", "=", "fromlist", ")", "app_dir", "=", "abspath", "(", "\"/\"", "+", "\"/\"", ".", "join", "(", "module", ".", "__file__", ".", "split", "(", "\"/\"", ")", "[", "1", ":", "-", "1", "]", ")", ")", "resource_dir", "=", "join", "(", "app_dir", ",", "complement", ")", "if", "exists", "(", "resource_dir", ")", "and", "locate", "(", "pattern", ",", "resource_dir", ",", "recursive", ")", ":", "dirs", ".", "append", "(", "resource_dir", ")", "return", "dirs" ]
https://github.com/heynemann/pyccuracy/blob/0bbe3bcff4d13a6501bf77d5af9457f6a1491ab6/pyccuracy/django/management/commands/pyccuracy.py#L31-L54
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/astroprint/plugin/services/camera.py
python
CameraService.peerSession
(self,data,sendResponse)
[]
def peerSession(self,data,sendResponse): action = data['action'] if data and 'sessionId' in data: sessionId = data['sessionId'] if action == 'init_peer_session': #Initialize the peer session if cameraManager().startLocalVideoSession(sessionId): sendResponse({'success': 'no-error'}) else: sendResponse('error_init_peer_session',True) #elif request.method == 'DELETE': elif action == 'close_peer_session': #Close peer session if cameraManager().closeLocalVideoSession(sessionId): sendResponse({'success': 'no-error'}) else: sendResponse('error_close_peer_session',True) else: sendResponse('error_no_session_id',True)
[ "def", "peerSession", "(", "self", ",", "data", ",", "sendResponse", ")", ":", "action", "=", "data", "[", "'action'", "]", "if", "data", "and", "'sessionId'", "in", "data", ":", "sessionId", "=", "data", "[", "'sessionId'", "]", "if", "action", "==", "'init_peer_session'", ":", "#Initialize the peer session", "if", "cameraManager", "(", ")", ".", "startLocalVideoSession", "(", "sessionId", ")", ":", "sendResponse", "(", "{", "'success'", ":", "'no-error'", "}", ")", "else", ":", "sendResponse", "(", "'error_init_peer_session'", ",", "True", ")", "#elif request.method == 'DELETE':", "elif", "action", "==", "'close_peer_session'", ":", "#Close peer session", "if", "cameraManager", "(", ")", ".", "closeLocalVideoSession", "(", "sessionId", ")", ":", "sendResponse", "(", "{", "'success'", ":", "'no-error'", "}", ")", "else", ":", "sendResponse", "(", "'error_close_peer_session'", ",", "True", ")", "else", ":", "sendResponse", "(", "'error_no_session_id'", ",", "True", ")" ]
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/plugin/services/camera.py#L71-L95
brian-team/brian2
c212a57cb992b766786b5769ebb830ff12d8a8ad
brian2/spatialneuron/morphology.py
python
Morphology.length
(self)
The length of each compartment in this section.
The length of each compartment in this section.
[ "The", "length", "of", "each", "compartment", "in", "this", "section", "." ]
def length(self): """ The length of each compartment in this section. """ raise NotImplementedError()
[ "def", "length", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/brian-team/brian2/blob/c212a57cb992b766786b5769ebb830ff12d8a8ad/brian2/spatialneuron/morphology.py#L723-L727
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/protocols/amp.py
python
BinaryBoxProtocol._unlockFromSwitch
(self)
Unlock this locked binary protocol so that further boxes may be sent again. This is used after an attempt to switch protocols has failed for some reason.
Unlock this locked binary protocol so that further boxes may be sent again. This is used after an attempt to switch protocols has failed for some reason.
[ "Unlock", "this", "locked", "binary", "protocol", "so", "that", "further", "boxes", "may", "be", "sent", "again", ".", "This", "is", "used", "after", "an", "attempt", "to", "switch", "protocols", "has", "failed", "for", "some", "reason", "." ]
def _unlockFromSwitch(self): """ Unlock this locked binary protocol so that further boxes may be sent again. This is used after an attempt to switch protocols has failed for some reason. """ if self.innerProtocol is not None: raise ProtocolSwitched("Protocol already switched. Cannot unlock.") self._locked = False
[ "def", "_unlockFromSwitch", "(", "self", ")", ":", "if", "self", ".", "innerProtocol", "is", "not", "None", ":", "raise", "ProtocolSwitched", "(", "\"Protocol already switched. Cannot unlock.\"", ")", "self", ".", "_locked", "=", "False" ]
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/protocols/amp.py#L2267-L2275
debian-calibre/calibre
020fc81d3936a64b2ac51459ecb796666ab6a051
src/calibre/ebooks/pdf/reflow.py
python
Page.second_pass
(self)
Locate paragraph boundaries in each column
Locate paragraph boundaries in each column
[ "Locate", "paragraph", "boundaries", "in", "each", "column" ]
def second_pass(self): 'Locate paragraph boundaries in each column' for region in self.regions: region.collect_stats() region.linearize()
[ "def", "second_pass", "(", "self", ")", ":", "for", "region", "in", "self", ".", "regions", ":", "region", ".", "collect_stats", "(", ")", "region", ".", "linearize", "(", ")" ]
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/ebooks/pdf/reflow.py#L612-L616
Bigpig4396/Multi-Agent-Reinforcement-Learning-Environment
4f8b7adba04aa8b577669377029de9232438296c
env_Rescue/Python3/maze.py
python
Maze.solve
(self, position=(0,0))
return False
Uses backtracking to solve maze
Uses backtracking to solve maze
[ "Uses", "backtracking", "to", "solve", "maze" ]
def solve(self, position=(0,0)): ''' Uses backtracking to solve maze''' if self.is_done(): return True for direction in [self.LEFT, self.RIGHT, self.UP, self.DOWN]: # try a move, move will return false if no portal of backward progress if self.move(direction): # after move, set new test position to be current player position if self.solve(self.player): return True # if position changed if position != self.player: # move back from towards previos position self.move((position[0]-self.player[0], position[1]-self.player[1])) return False
[ "def", "solve", "(", "self", ",", "position", "=", "(", "0", ",", "0", ")", ")", ":", "if", "self", ".", "is_done", "(", ")", ":", "return", "True", "for", "direction", "in", "[", "self", ".", "LEFT", ",", "self", ".", "RIGHT", ",", "self", ".", "UP", ",", "self", ".", "DOWN", "]", ":", "# try a move, move will return false if no portal of backward progress\t\t\t", "if", "self", ".", "move", "(", "direction", ")", ":", "# after move, set new test position to be current player position", "if", "self", ".", "solve", "(", "self", ".", "player", ")", ":", "return", "True", "# if position changed ", "if", "position", "!=", "self", ".", "player", ":", "# move back from towards previos position", "self", ".", "move", "(", "(", "position", "[", "0", "]", "-", "self", ".", "player", "[", "0", "]", ",", "position", "[", "1", "]", "-", "self", ".", "player", "[", "1", "]", ")", ")", "return", "False" ]
https://github.com/Bigpig4396/Multi-Agent-Reinforcement-Learning-Environment/blob/4f8b7adba04aa8b577669377029de9232438296c/env_Rescue/Python3/maze.py#L352-L367
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/rings.py
python
PolyRing.index
(self, gen)
return i
Compute index of ``gen`` in ``self.gens``.
Compute index of ``gen`` in ``self.gens``.
[ "Compute", "index", "of", "gen", "in", "self", ".", "gens", "." ]
def index(self, gen): """Compute index of ``gen`` in ``self.gens``. """ if gen is None: i = 0 elif isinstance(gen, int): i = gen if 0 <= i and i < self.ngens: pass elif -self.ngens <= i and i <= -1: i = -i - 1 else: raise ValueError("invalid generator index: %s" % gen) elif isinstance(gen, self.dtype): try: i = self.gens.index(gen) except ValueError: raise ValueError("invalid generator: %s" % gen) elif isinstance(gen, string_types): try: i = self.symbols.index(gen) except ValueError: raise ValueError("invalid generator: %s" % gen) else: raise ValueError("expected a polynomial generator, an integer, a string or None, got %s" % gen) return i
[ "def", "index", "(", "self", ",", "gen", ")", ":", "if", "gen", "is", "None", ":", "i", "=", "0", "elif", "isinstance", "(", "gen", ",", "int", ")", ":", "i", "=", "gen", "if", "0", "<=", "i", "and", "i", "<", "self", ".", "ngens", ":", "pass", "elif", "-", "self", ".", "ngens", "<=", "i", "and", "i", "<=", "-", "1", ":", "i", "=", "-", "i", "-", "1", "else", ":", "raise", "ValueError", "(", "\"invalid generator index: %s\"", "%", "gen", ")", "elif", "isinstance", "(", "gen", ",", "self", ".", "dtype", ")", ":", "try", ":", "i", "=", "self", ".", "gens", ".", "index", "(", "gen", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"invalid generator: %s\"", "%", "gen", ")", "elif", "isinstance", "(", "gen", ",", "string_types", ")", ":", "try", ":", "i", "=", "self", ".", "symbols", ".", "index", "(", "gen", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"invalid generator: %s\"", "%", "gen", ")", "else", ":", "raise", "ValueError", "(", "\"expected a polynomial generator, an integer, a string or None, got %s\"", "%", "gen", ")", "return", "i" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/rings.py#L372-L398
kozec/syncthing-gtk
01eeeb9ed485232e145bf39d90142832e1c9751e
syncthing_gtk/daemon.py
python
Daemon._parse_dev_n_folders
(self, config)
Parses devices and folders from configuration and emits associated events.
Parses devices and folders from configuration and emits associated events.
[ "Parses", "devices", "and", "folders", "from", "configuration", "and", "emits", "associated", "events", "." ]
def _parse_dev_n_folders(self, config): """ Parses devices and folders from configuration and emits associated events. """ # Pre-parse folders to detect unused devices device_folders = {} for r in config["folders"]: rid = r["id"] for n in r["devices"]: nid = n["deviceID"] if not nid in device_folders : device_folders[nid] = [] device_folders[nid].append(rid) # Parse devices for n in sorted(config["devices"], key=lambda x : x["name"].lower()): nid = n["deviceID"] self._get_device_data(nid) # Creates dict with device data used = (nid in device_folders) and (len(device_folders[nid]) > 0) self.emit("device-added", nid, n["name"], used, n) # Parse folders for r in sorted(config["folders"], key=lambda x : x["id"].lower()): rid = r["id"] self._syncing_folders.add(rid) self._folder_devices[rid] = [ n["deviceID"] for n in r["devices"] ] self.emit("folder-added", rid, r) self._request_folder_data(rid)
[ "def", "_parse_dev_n_folders", "(", "self", ",", "config", ")", ":", "# Pre-parse folders to detect unused devices", "device_folders", "=", "{", "}", "for", "r", "in", "config", "[", "\"folders\"", "]", ":", "rid", "=", "r", "[", "\"id\"", "]", "for", "n", "in", "r", "[", "\"devices\"", "]", ":", "nid", "=", "n", "[", "\"deviceID\"", "]", "if", "not", "nid", "in", "device_folders", ":", "device_folders", "[", "nid", "]", "=", "[", "]", "device_folders", "[", "nid", "]", ".", "append", "(", "rid", ")", "# Parse devices", "for", "n", "in", "sorted", "(", "config", "[", "\"devices\"", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "\"name\"", "]", ".", "lower", "(", ")", ")", ":", "nid", "=", "n", "[", "\"deviceID\"", "]", "self", ".", "_get_device_data", "(", "nid", ")", "# Creates dict with device data", "used", "=", "(", "nid", "in", "device_folders", ")", "and", "(", "len", "(", "device_folders", "[", "nid", "]", ")", ">", "0", ")", "self", ".", "emit", "(", "\"device-added\"", ",", "nid", ",", "n", "[", "\"name\"", "]", ",", "used", ",", "n", ")", "# Parse folders", "for", "r", "in", "sorted", "(", "config", "[", "\"folders\"", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "\"id\"", "]", ".", "lower", "(", ")", ")", ":", "rid", "=", "r", "[", "\"id\"", "]", "self", ".", "_syncing_folders", ".", "add", "(", "rid", ")", "self", ".", "_folder_devices", "[", "rid", "]", "=", "[", "n", "[", "\"deviceID\"", "]", "for", "n", "in", "r", "[", "\"devices\"", "]", "]", "self", ".", "emit", "(", "\"folder-added\"", ",", "rid", ",", "r", ")", "self", ".", "_request_folder_data", "(", "rid", ")" ]
https://github.com/kozec/syncthing-gtk/blob/01eeeb9ed485232e145bf39d90142832e1c9751e/syncthing_gtk/daemon.py#L409-L436
RobotLocomotion/pytorch-dense-correspondence
76bf6499c325ad136a094fb341158a90eaa31d53
dense_correspondence/correspondence_tools/correspondence_augmentation.py
python
flip_vertical
(images, uv_pixel_positions)
return mutated_images, mutated_uv_pixel_positions
Fip the images and the pixel positions vertically (flip up/down) See random_image_and_indices_mutation() for documentation of args and return types.
Fip the images and the pixel positions vertically (flip up/down)
[ "Fip", "the", "images", "and", "the", "pixel", "positions", "vertically", "(", "flip", "up", "/", "down", ")" ]
def flip_vertical(images, uv_pixel_positions): """ Fip the images and the pixel positions vertically (flip up/down) See random_image_and_indices_mutation() for documentation of args and return types. """ mutated_images = [ImageOps.flip(image) for image in images] v_pixel_positions = uv_pixel_positions[1] mutated_v_pixel_positions = (image.height-1) - v_pixel_positions mutated_uv_pixel_positions = (uv_pixel_positions[0], mutated_v_pixel_positions) return mutated_images, mutated_uv_pixel_positions
[ "def", "flip_vertical", "(", "images", ",", "uv_pixel_positions", ")", ":", "mutated_images", "=", "[", "ImageOps", ".", "flip", "(", "image", ")", "for", "image", "in", "images", "]", "v_pixel_positions", "=", "uv_pixel_positions", "[", "1", "]", "mutated_v_pixel_positions", "=", "(", "image", ".", "height", "-", "1", ")", "-", "v_pixel_positions", "mutated_uv_pixel_positions", "=", "(", "uv_pixel_positions", "[", "0", "]", ",", "mutated_v_pixel_positions", ")", "return", "mutated_images", ",", "mutated_uv_pixel_positions" ]
https://github.com/RobotLocomotion/pytorch-dense-correspondence/blob/76bf6499c325ad136a094fb341158a90eaa31d53/dense_correspondence/correspondence_tools/correspondence_augmentation.py#L59-L70
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/maasserver/models/userprofile.py
python
UserProfile.modify_consumer_name
(self, token_key, consumer_name)
Modify consumer name of an existing token key. :param token_key: The key of the token to be deleted. :type token_key: string :param consumer_name: Name of the token consumer. :type consumer_name: string :raises: `django.http.Http404`
Modify consumer name of an existing token key.
[ "Modify", "consumer", "name", "of", "an", "existing", "token", "key", "." ]
def modify_consumer_name(self, token_key, consumer_name): """Modify consumer name of an existing token key. :param token_key: The key of the token to be deleted. :type token_key: string :param consumer_name: Name of the token consumer. :type consumer_name: string :raises: `django.http.Http404` """ token = get_object_or_404( Token, user=self.user, token_type=Token.ACCESS, key=token_key ) token.consumer.name = consumer_name token.consumer.save() token.save()
[ "def", "modify_consumer_name", "(", "self", ",", "token_key", ",", "consumer_name", ")", ":", "token", "=", "get_object_or_404", "(", "Token", ",", "user", "=", "self", ".", "user", ",", "token_type", "=", "Token", ".", "ACCESS", ",", "key", "=", "token_key", ")", "token", ".", "consumer", ".", "name", "=", "consumer_name", "token", ".", "consumer", ".", "save", "(", ")", "token", ".", "save", "(", ")" ]
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/maasserver/models/userprofile.py#L153-L167
dongrixinyu/JioNLP
2c5b11439915891f0f24955b7de4f637f38a4b44
jionlp/dictionary/dictionary_loader.py
python
negative_words_loader
()
return res
加载否定词典 negative_words.txt
加载否定词典 negative_words.txt
[ "加载否定词典", "negative_words", ".", "txt" ]
def negative_words_loader(): """ 加载否定词典 negative_words.txt """ res = read_file_by_line(os.path.join( GRAND_DIR_PATH, 'dictionary/negative_words.txt')) return res
[ "def", "negative_words_loader", "(", ")", ":", "res", "=", "read_file_by_line", "(", "os", ".", "path", ".", "join", "(", "GRAND_DIR_PATH", ",", "'dictionary/negative_words.txt'", ")", ")", "return", "res" ]
https://github.com/dongrixinyu/JioNLP/blob/2c5b11439915891f0f24955b7de4f637f38a4b44/jionlp/dictionary/dictionary_loader.py#L209-L214
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/distlib/_backport/tarfile.py
python
TarFile.makefile
(self, tarinfo, targetpath)
Make a file called targetpath.
Make a file called targetpath.
[ "Make", "a", "file", "called", "targetpath", "." ]
def makefile(self, tarinfo, targetpath): """Make a file called targetpath. """ source = self.fileobj source.seek(tarinfo.offset_data) target = bltn_open(targetpath, "wb") if tarinfo.sparse is not None: for offset, size in tarinfo.sparse: target.seek(offset) copyfileobj(source, target, size) else: copyfileobj(source, target, tarinfo.size) target.seek(tarinfo.size) target.truncate() target.close()
[ "def", "makefile", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "source", "=", "self", ".", "fileobj", "source", ".", "seek", "(", "tarinfo", ".", "offset_data", ")", "target", "=", "bltn_open", "(", "targetpath", ",", "\"wb\"", ")", "if", "tarinfo", ".", "sparse", "is", "not", "None", ":", "for", "offset", ",", "size", "in", "tarinfo", ".", "sparse", ":", "target", ".", "seek", "(", "offset", ")", "copyfileobj", "(", "source", ",", "target", ",", "size", ")", "else", ":", "copyfileobj", "(", "source", ",", "target", ",", "tarinfo", ".", "size", ")", "target", ".", "seek", "(", "tarinfo", ".", "size", ")", "target", ".", "truncate", "(", ")", "target", ".", "close", "(", ")" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/distlib/_backport/tarfile.py#L2296-L2310
openrazer/openrazer
1615f8516e8014bad7f78c781c91e6529679718f
daemon/openrazer_daemon/dbus_services/dbus_methods/all.py
python
get_device_type_keyboard
(self)
return 'keyboard'
Get the device's type :return: 'keyboard' :rtype: str
Get the device's type
[ "Get", "the", "device", "s", "type" ]
def get_device_type_keyboard(self): """ Get the device's type :return: 'keyboard' :rtype: str """ self.logger.debug("DBus call get_device_type") return 'keyboard'
[ "def", "get_device_type_keyboard", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"DBus call get_device_type\"", ")", "return", "'keyboard'" ]
https://github.com/openrazer/openrazer/blob/1615f8516e8014bad7f78c781c91e6529679718f/daemon/openrazer_daemon/dbus_services/dbus_methods/all.py#L105-L113
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/gdata/tlslite/utils/RSAKey.py
python
RSAKey.hashAndVerify
(self, sigBytes, bytes)
return self.verify(sigBytes, prefixedHashBytes)
Hash and verify the passed-in bytes with the signature. This verifies a PKCS1-SHA1 signature on the passed-in data. @type sigBytes: L{array.array} of unsigned bytes @param sigBytes: A PKCS1-SHA1 signature. @type bytes: str or L{array.array} of unsigned bytes @param bytes: The value which will be hashed and verified. @rtype: bool @return: Whether the signature matches the passed-in data.
Hash and verify the passed-in bytes with the signature.
[ "Hash", "and", "verify", "the", "passed", "-", "in", "bytes", "with", "the", "signature", "." ]
def hashAndVerify(self, sigBytes, bytes): """Hash and verify the passed-in bytes with the signature. This verifies a PKCS1-SHA1 signature on the passed-in data. @type sigBytes: L{array.array} of unsigned bytes @param sigBytes: A PKCS1-SHA1 signature. @type bytes: str or L{array.array} of unsigned bytes @param bytes: The value which will be hashed and verified. @rtype: bool @return: Whether the signature matches the passed-in data. """ if not isinstance(bytes, type("")): bytes = bytesToString(bytes) hashBytes = stringToBytes(sha1(bytes).digest()) prefixedHashBytes = self._addPKCS1SHA1Prefix(hashBytes) return self.verify(sigBytes, prefixedHashBytes)
[ "def", "hashAndVerify", "(", "self", ",", "sigBytes", ",", "bytes", ")", ":", "if", "not", "isinstance", "(", "bytes", ",", "type", "(", "\"\"", ")", ")", ":", "bytes", "=", "bytesToString", "(", "bytes", ")", "hashBytes", "=", "stringToBytes", "(", "sha1", "(", "bytes", ")", ".", "digest", "(", ")", ")", "prefixedHashBytes", "=", "self", ".", "_addPKCS1SHA1Prefix", "(", "hashBytes", ")", "return", "self", ".", "verify", "(", "sigBytes", ",", "prefixedHashBytes", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/gdata/tlslite/utils/RSAKey.py#L81-L99
lutris/lutris
66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a
lutris/util/wine/wine.py
python
get_lutris_wine_versions
()
return versions
Return the list of wine versions installed by lutris
Return the list of wine versions installed by lutris
[ "Return", "the", "list", "of", "wine", "versions", "installed", "by", "lutris" ]
def get_lutris_wine_versions(): """Return the list of wine versions installed by lutris""" versions = [] if system.path_exists(WINE_DIR): dirs = version_sort(os.listdir(WINE_DIR), reverse=True) for dirname in dirs: if is_version_installed(dirname): versions.append(dirname) return versions
[ "def", "get_lutris_wine_versions", "(", ")", ":", "versions", "=", "[", "]", "if", "system", ".", "path_exists", "(", "WINE_DIR", ")", ":", "dirs", "=", "version_sort", "(", "os", ".", "listdir", "(", "WINE_DIR", ")", ",", "reverse", "=", "True", ")", "for", "dirname", "in", "dirs", ":", "if", "is_version_installed", "(", "dirname", ")", ":", "versions", ".", "append", "(", "dirname", ")", "return", "versions" ]
https://github.com/lutris/lutris/blob/66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a/lutris/util/wine/wine.py#L165-L173
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/misc/repr.py
python
coeff_repr
(c, is_latex=False)
return s
r""" String representing coefficients in a linear combination. INPUT: - ``c`` -- a coefficient (i.e., an element of a ring) OUTPUT: A string EXAMPLES:: sage: from sage.misc.repr import coeff_repr sage: coeff_repr(QQ(1/2)) '1/2' sage: coeff_repr(-x^2) '(-x^2)' sage: coeff_repr(QQ(1/2), is_latex=True) '\\frac{1}{2}' sage: coeff_repr(-x^2, is_latex=True) '\\left(-x^{2}\\right)'
r""" String representing coefficients in a linear combination.
[ "r", "String", "representing", "coefficients", "in", "a", "linear", "combination", "." ]
def coeff_repr(c, is_latex=False): r""" String representing coefficients in a linear combination. INPUT: - ``c`` -- a coefficient (i.e., an element of a ring) OUTPUT: A string EXAMPLES:: sage: from sage.misc.repr import coeff_repr sage: coeff_repr(QQ(1/2)) '1/2' sage: coeff_repr(-x^2) '(-x^2)' sage: coeff_repr(QQ(1/2), is_latex=True) '\\frac{1}{2}' sage: coeff_repr(-x^2, is_latex=True) '\\left(-x^{2}\\right)' """ if not is_latex: try: return c._coeff_repr() except AttributeError: pass if isinstance(c, (int, float)): return str(c) if is_latex and hasattr(c, '_latex_'): s = c._latex_() else: s = str(c).replace(' ', '') if s.find("+") != -1 or s.find("-") != -1: if is_latex: return "\\left(%s\\right)" % s else: return "(%s)" % s return s
[ "def", "coeff_repr", "(", "c", ",", "is_latex", "=", "False", ")", ":", "if", "not", "is_latex", ":", "try", ":", "return", "c", ".", "_coeff_repr", "(", ")", "except", "AttributeError", ":", "pass", "if", "isinstance", "(", "c", ",", "(", "int", ",", "float", ")", ")", ":", "return", "str", "(", "c", ")", "if", "is_latex", "and", "hasattr", "(", "c", ",", "'_latex_'", ")", ":", "s", "=", "c", ".", "_latex_", "(", ")", "else", ":", "s", "=", "str", "(", "c", ")", ".", "replace", "(", "' '", ",", "''", ")", "if", "s", ".", "find", "(", "\"+\"", ")", "!=", "-", "1", "or", "s", ".", "find", "(", "\"-\"", ")", "!=", "-", "1", ":", "if", "is_latex", ":", "return", "\"\\\\left(%s\\\\right)\"", "%", "s", "else", ":", "return", "\"(%s)\"", "%", "s", "return", "s" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/misc/repr.py#L6-L46
WooYun/TangScan
f4fd60228ec09ad10bd3dd3ef3b67e58bcdd4aa5
tangscan/thirdparty/requests/exceptions.py
python
RequestException.__init__
(self, *args, **kwargs)
Initialize RequestException with `request` and `response` objects.
Initialize RequestException with `request` and `response` objects.
[ "Initialize", "RequestException", "with", "request", "and", "response", "objects", "." ]
def __init__(self, *args, **kwargs): """ Initialize RequestException with `request` and `response` objects. """ response = kwargs.pop('response', None) self.response = response self.request = kwargs.pop('request', None) if (response is not None and not self.request and hasattr(response, 'request')): self.request = self.response.request super(RequestException, self).__init__(*args, **kwargs)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "kwargs", ".", "pop", "(", "'response'", ",", "None", ")", "self", ".", "response", "=", "response", "self", ".", "request", "=", "kwargs", ".", "pop", "(", "'request'", ",", "None", ")", "if", "(", "response", "is", "not", "None", "and", "not", "self", ".", "request", "and", "hasattr", "(", "response", ",", "'request'", ")", ")", ":", "self", ".", "request", "=", "self", ".", "response", ".", "request", "super", "(", "RequestException", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/WooYun/TangScan/blob/f4fd60228ec09ad10bd3dd3ef3b67e58bcdd4aa5/tangscan/thirdparty/requests/exceptions.py#L17-L27
fooying/3102
0faee38c30b2e24154f41e68457cfd8f7a61c040
thirdparty/requests/adapters.py
python
HTTPAdapter.get_connection
(self, url, proxies=None)
return conn
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
[ "Returns", "a", "urllib3", "connection", "for", "the", "given", "URL", ".", "This", "should", "not", "be", "called", "from", "user", "code", "and", "is", "only", "exposed", "for", "use", "when", "subclassing", "the", ":", "class", ":", "HTTPAdapter", "<requests", ".", "adapters", ".", "HTTPAdapter", ">", "." ]
def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. """ proxies = proxies or {} proxy = proxies.get(urlparse(url.lower()).scheme) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn
[ "def", "get_connection", "(", "self", ",", "url", ",", "proxies", "=", "None", ")", ":", "proxies", "=", "proxies", "or", "{", "}", "proxy", "=", "proxies", ".", "get", "(", "urlparse", "(", "url", ".", "lower", "(", ")", ")", ".", "scheme", ")", "if", "proxy", ":", "proxy", "=", "prepend_scheme_if_needed", "(", "proxy", ",", "'http'", ")", "proxy_manager", "=", "self", ".", "proxy_manager_for", "(", "proxy", ")", "conn", "=", "proxy_manager", ".", "connection_from_url", "(", "url", ")", "else", ":", "# Only scheme should be lower case", "parsed", "=", "urlparse", "(", "url", ")", "url", "=", "parsed", ".", "geturl", "(", ")", "conn", "=", "self", ".", "poolmanager", ".", "connection_from_url", "(", "url", ")", "return", "conn" ]
https://github.com/fooying/3102/blob/0faee38c30b2e24154f41e68457cfd8f7a61c040/thirdparty/requests/adapters.py#L232-L253
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3translate.py
python
Strings.export_file
(self, langfile, modlist, filelist, filetype, all_template_flag)
Function to get the strings by module(s)/file(s), merge with those strings from existing w2p language file which are already translated and call the "write_xls()" method if the default filetype "xls" is chosen. If "po" is chosen, then the write_po()" method is called.
Function to get the strings by module(s)/file(s), merge with those strings from existing w2p language file which are already translated and call the "write_xls()" method if the default filetype "xls" is chosen. If "po" is chosen, then the write_po()" method is called.
[ "Function", "to", "get", "the", "strings", "by", "module", "(", "s", ")", "/", "file", "(", "s", ")", "merge", "with", "those", "strings", "from", "existing", "w2p", "language", "file", "which", "are", "already", "translated", "and", "call", "the", "write_xls", "()", "method", "if", "the", "default", "filetype", "xls", "is", "chosen", ".", "If", "po", "is", "chosen", "then", "the", "write_po", "()", "method", "is", "called", "." ]
def export_file(self, langfile, modlist, filelist, filetype, all_template_flag): """ Function to get the strings by module(s)/file(s), merge with those strings from existing w2p language file which are already translated and call the "write_xls()" method if the default filetype "xls" is chosen. If "po" is chosen, then the write_po()" method is called. """ request = current.request settings = current.deployment_settings folder = request.folder join = os.path.join langcode = langfile[:-3] langfile = join(folder, "languages", langfile) # If the language file doesn't exist, create it if not os.path.exists(langfile): f = open(langfile, "w") f.write("") f.close() NewStrings = [] A = TranslateAPI() if all_template_flag == 1: # Select All Templates A.grp.group_files(join(folder, "modules", "templates")) else: # Specific template(s) is selected templates = settings.get_template() if not isinstance(templates, (tuple, list)): templates = (templates,) group_files = A.grp.group_files for template in templates: if "." in template: template = template.split(".") template = join(*template) template_folder = join(folder, "modules", "templates", template) group_files(template_folder) R = TranslateReadFiles() ## Select Modules # Core Modules are always included core_modules = ("auth", "default") for mod in core_modules: modlist.append(mod) # appadmin and error are part of admin if "admin" in modlist: modlist.append("appadmin") modlist.append("error") # Select dependent modules models = current.models for mod in modlist: if hasattr(models, mod): obj = getattr(models, mod) if hasattr(obj, "depends"): for element in obj.depends: if element not in modlist: modlist.append(element) get_strings_by_module = A.get_strings_by_module for mod in modlist: NewStrings += get_strings_by_module(mod) # Retrieve strings in a file get_strings_by_file = A.get_strings_by_file for f in filelist: NewStrings += get_strings_by_file(f) # Remove quotes NewStrings = self.remove_quotes(NewStrings) # Add database strings NewStrings += R.get_database_strings(all_template_flag) # Add user-supplied strings NewStrings += R.get_user_strings() # Remove duplicates NewStrings = self.remove_duplicates(NewStrings) NewStrings.sort(key=lambda tup: tup[1]) # Retrieve strings from existing w2p language file OldStrings = self.read_w2p(langfile) OldStrings.sort(key=lambda tup: tup[0]) # Merge those strings which were already translated earlier Strings = [] sappend = Strings.append i = 0 lim = len(OldStrings) for (l, s) in NewStrings: while i < lim and OldStrings[i][0] < s: i += 1 if i != lim and OldStrings[i][0] == s and \ OldStrings[i][1].startswith("*** ") == False: sappend((l, s, OldStrings[i][1])) else: sappend((l, s, "")) if filetype == "xls": # Create excel file return self.write_xls(Strings, langcode) elif filetype == "po": # Create pootle file return self.write_po(Strings, langcode)
[ "def", "export_file", "(", "self", ",", "langfile", ",", "modlist", ",", "filelist", ",", "filetype", ",", "all_template_flag", ")", ":", "request", "=", "current", ".", "request", "settings", "=", "current", ".", "deployment_settings", "folder", "=", "request", ".", "folder", "join", "=", "os", ".", "path", ".", "join", "langcode", "=", "langfile", "[", ":", "-", "3", "]", "langfile", "=", "join", "(", "folder", ",", "\"languages\"", ",", "langfile", ")", "# If the language file doesn't exist, create it", "if", "not", "os", ".", "path", ".", "exists", "(", "langfile", ")", ":", "f", "=", "open", "(", "langfile", ",", "\"w\"", ")", "f", ".", "write", "(", "\"\"", ")", "f", ".", "close", "(", ")", "NewStrings", "=", "[", "]", "A", "=", "TranslateAPI", "(", ")", "if", "all_template_flag", "==", "1", ":", "# Select All Templates", "A", ".", "grp", ".", "group_files", "(", "join", "(", "folder", ",", "\"modules\"", ",", "\"templates\"", ")", ")", "else", ":", "# Specific template(s) is selected", "templates", "=", "settings", ".", "get_template", "(", ")", "if", "not", "isinstance", "(", "templates", ",", "(", "tuple", ",", "list", ")", ")", ":", "templates", "=", "(", "templates", ",", ")", "group_files", "=", "A", ".", "grp", ".", "group_files", "for", "template", "in", "templates", ":", "if", "\".\"", "in", "template", ":", "template", "=", "template", ".", "split", "(", "\".\"", ")", "template", "=", "join", "(", "*", "template", ")", "template_folder", "=", "join", "(", "folder", ",", "\"modules\"", ",", "\"templates\"", ",", "template", ")", "group_files", "(", "template_folder", ")", "R", "=", "TranslateReadFiles", "(", ")", "## Select Modules", "# Core Modules are always included", "core_modules", "=", "(", "\"auth\"", ",", "\"default\"", ")", "for", "mod", "in", "core_modules", ":", "modlist", ".", "append", "(", "mod", ")", "# appadmin and error are part of admin", "if", "\"admin\"", "in", "modlist", ":", "modlist", ".", "append", "(", "\"appadmin\"", ")", "modlist", ".", "append", "(", "\"error\"", ")", "# Select dependent modules", "models", "=", "current", ".", "models", "for", "mod", "in", "modlist", ":", "if", "hasattr", "(", "models", ",", "mod", ")", ":", "obj", "=", "getattr", "(", "models", ",", "mod", ")", "if", "hasattr", "(", "obj", ",", "\"depends\"", ")", ":", "for", "element", "in", "obj", ".", "depends", ":", "if", "element", "not", "in", "modlist", ":", "modlist", ".", "append", "(", "element", ")", "get_strings_by_module", "=", "A", ".", "get_strings_by_module", "for", "mod", "in", "modlist", ":", "NewStrings", "+=", "get_strings_by_module", "(", "mod", ")", "# Retrieve strings in a file", "get_strings_by_file", "=", "A", ".", "get_strings_by_file", "for", "f", "in", "filelist", ":", "NewStrings", "+=", "get_strings_by_file", "(", "f", ")", "# Remove quotes", "NewStrings", "=", "self", ".", "remove_quotes", "(", "NewStrings", ")", "# Add database strings", "NewStrings", "+=", "R", ".", "get_database_strings", "(", "all_template_flag", ")", "# Add user-supplied strings", "NewStrings", "+=", "R", ".", "get_user_strings", "(", ")", "# Remove duplicates", "NewStrings", "=", "self", ".", "remove_duplicates", "(", "NewStrings", ")", "NewStrings", ".", "sort", "(", "key", "=", "lambda", "tup", ":", "tup", "[", "1", "]", ")", "# Retrieve strings from existing w2p language file", "OldStrings", "=", "self", ".", "read_w2p", "(", "langfile", ")", "OldStrings", ".", "sort", "(", "key", "=", "lambda", "tup", ":", "tup", "[", "0", "]", ")", "# Merge those strings which were already translated earlier", "Strings", "=", "[", "]", "sappend", "=", "Strings", ".", "append", "i", "=", "0", "lim", "=", "len", "(", "OldStrings", ")", "for", "(", "l", ",", "s", ")", "in", "NewStrings", ":", "while", "i", "<", "lim", "and", "OldStrings", "[", "i", "]", "[", "0", "]", "<", "s", ":", "i", "+=", "1", "if", "i", "!=", "lim", "and", "OldStrings", "[", "i", "]", "[", "0", "]", "==", "s", "and", "OldStrings", "[", "i", "]", "[", "1", "]", ".", "startswith", "(", "\"*** \"", ")", "==", "False", ":", "sappend", "(", "(", "l", ",", "s", ",", "OldStrings", "[", "i", "]", "[", "1", "]", ")", ")", "else", ":", "sappend", "(", "(", "l", ",", "s", ",", "\"\"", ")", ")", "if", "filetype", "==", "\"xls\"", ":", "# Create excel file", "return", "self", ".", "write_xls", "(", "Strings", ",", "langcode", ")", "elif", "filetype", "==", "\"po\"", ":", "# Create pootle file", "return", "self", ".", "write_po", "(", "Strings", ",", "langcode", ")" ]
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3translate.py#L1038-L1150
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/plot/animate.py
python
Animation.png
(self, dir=None)
return dir
r""" Render PNG images of the frames in this animation, saving them in ``dir``. Return the absolute path to that directory. If the frames have been previously rendered and ``dir`` is ``None``, just return the directory in which they are stored. When ``dir`` is other than ``None``, force re-rendering of frames. INPUT: - ``dir`` -- Directory in which to store frames. Default ``None``; in this case, a temporary directory will be created for storing the frames. EXAMPLES:: sage: a = animate([plot(x^2 + n) for n in range(4)], ymin=0, ymax=4) sage: d = a.png(); v = os.listdir(d); v.sort(); v # long time ['00000000.png', '00000001.png', '00000002.png', '00000003.png']
r""" Render PNG images of the frames in this animation, saving them in ``dir``. Return the absolute path to that directory. If the frames have been previously rendered and ``dir`` is ``None``, just return the directory in which they are stored.
[ "r", "Render", "PNG", "images", "of", "the", "frames", "in", "this", "animation", "saving", "them", "in", "dir", ".", "Return", "the", "absolute", "path", "to", "that", "directory", ".", "If", "the", "frames", "have", "been", "previously", "rendered", "and", "dir", "is", "None", "just", "return", "the", "directory", "in", "which", "they", "are", "stored", "." ]
def png(self, dir=None): r""" Render PNG images of the frames in this animation, saving them in ``dir``. Return the absolute path to that directory. If the frames have been previously rendered and ``dir`` is ``None``, just return the directory in which they are stored. When ``dir`` is other than ``None``, force re-rendering of frames. INPUT: - ``dir`` -- Directory in which to store frames. Default ``None``; in this case, a temporary directory will be created for storing the frames. EXAMPLES:: sage: a = animate([plot(x^2 + n) for n in range(4)], ymin=0, ymax=4) sage: d = a.png(); v = os.listdir(d); v.sort(); v # long time ['00000000.png', '00000001.png', '00000002.png', '00000003.png'] """ if dir is None: try: return self._png_dir except AttributeError: pass dir = tmp_dir() i = 0 for frame in self._frames: filename = '%s/%08d.png'%(dir,i) try: save_image = frame.save_image except AttributeError: self.make_image(frame, filename, **self._kwds) else: save_image(filename, **self._kwds) i += 1 self._num_frames = i self._png_dir = dir return dir
[ "def", "png", "(", "self", ",", "dir", "=", "None", ")", ":", "if", "dir", "is", "None", ":", "try", ":", "return", "self", ".", "_png_dir", "except", "AttributeError", ":", "pass", "dir", "=", "tmp_dir", "(", ")", "i", "=", "0", "for", "frame", "in", "self", ".", "_frames", ":", "filename", "=", "'%s/%08d.png'", "%", "(", "dir", ",", "i", ")", "try", ":", "save_image", "=", "frame", ".", "save_image", "except", "AttributeError", ":", "self", ".", "make_image", "(", "frame", ",", "filename", ",", "*", "*", "self", ".", "_kwds", ")", "else", ":", "save_image", "(", "filename", ",", "*", "*", "self", ".", "_kwds", ")", "i", "+=", "1", "self", ".", "_num_frames", "=", "i", "self", ".", "_png_dir", "=", "dir", "return", "dir" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/plot/animate.py#L432-L472
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/gdata/src/atom/service.py
python
AtomService.Put
(self, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml')
return self.request('PUT', uri, data=data, headers=extra_headers, url_params=url_params)
Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the PUT request.
Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the PUT request.
[ "Updates", "an", "entry", "at", "the", "given", "URI", ".", "Args", ":", "data", ":", "string", "ElementTree", ".", "_Element", "or", "xml_wrapper", ".", "ElementWrapper", "The", "XML", "containing", "the", "updated", "data", ".", "uri", ":", "string", "A", "URI", "indicating", "entry", "to", "which", "the", "update", "will", "be", "applied", ".", "Example", ":", "/", "base", "/", "feeds", "/", "items", "/", "ITEM", "-", "ID", "extra_headers", ":", "dict", "(", "optional", ")", "HTTP", "headers", "which", "are", "to", "be", "included", ".", "The", "client", "automatically", "sets", "the", "Content", "-", "Type", "Authorization", "and", "Content", "-", "Length", "headers", ".", "url_params", ":", "dict", "(", "optional", ")", "Additional", "URL", "parameters", "to", "be", "included", "in", "the", "URI", ".", "These", "are", "translated", "into", "query", "arguments", "in", "the", "form", "&dict_key", "=", "value&", "...", ".", "Example", ":", "{", "max", "-", "results", ":", "250", "}", "becomes", "&max", "-", "results", "=", "250", "escape_params", ":", "boolean", "(", "optional", ")", "If", "false", "the", "calling", "code", "has", "already", "ensured", "that", "the", "query", "will", "form", "a", "valid", "URL", "(", "all", "reserved", "characters", "have", "been", "escaped", ")", ".", "If", "true", "this", "method", "will", "escape", "the", "query", "and", "any", "URL", "parameters", "provided", ".", "Returns", ":", "httplib", ".", "HTTPResponse", "Server", "s", "response", "to", "the", "PUT", "request", "." ]
def Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the PUT request. """ if extra_headers is None: extra_headers = {} if content_type: extra_headers['Content-Type'] = content_type return self.request('PUT', uri, data=data, headers=extra_headers, url_params=url_params)
[ "def", "Put", "(", "self", ",", "data", ",", "uri", ",", "extra_headers", "=", "None", ",", "url_params", "=", "None", ",", "escape_params", "=", "True", ",", "content_type", "=", "'application/atom+xml'", ")", ":", "if", "extra_headers", "is", "None", ":", "extra_headers", "=", "{", "}", "if", "content_type", ":", "extra_headers", "[", "'Content-Type'", "]", "=", "content_type", "return", "self", ".", "request", "(", "'PUT'", ",", "uri", ",", "data", "=", "data", ",", "headers", "=", "extra_headers", ",", "url_params", "=", "url_params", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/gdata/src/atom/service.py#L261-L291
mlrun/mlrun
4c120719d64327a34b7ee1ab08fb5e01b258b00a
mlrun/frameworks/pytorch/callbacks_handler.py
python
CallbacksHandler.on_scheduler_step_end
(self, callbacks: List[str] = None)
return self._run_callbacks( method_name=_CallbackInterface.ON_SCHEDULER_STEP_END, callbacks=self._parse_names(names=callbacks), )
Call the 'on_scheduler_step_end' method of every callback in the callbacks list. If the list is 'None' (not given), all callbacks will be called. :param callbacks: The callbacks names to use. If 'None', all of the callbacks will be used. :return: True if all of the callbacks called returned True and False if not.
Call the 'on_scheduler_step_end' method of every callback in the callbacks list. If the list is 'None' (not given), all callbacks will be called.
[ "Call", "the", "on_scheduler_step_end", "method", "of", "every", "callback", "in", "the", "callbacks", "list", ".", "If", "the", "list", "is", "None", "(", "not", "given", ")", "all", "callbacks", "will", "be", "called", "." ]
def on_scheduler_step_end(self, callbacks: List[str] = None) -> bool: """ Call the 'on_scheduler_step_end' method of every callback in the callbacks list. If the list is 'None' (not given), all callbacks will be called. :param callbacks: The callbacks names to use. If 'None', all of the callbacks will be used. :return: True if all of the callbacks called returned True and False if not. """ return self._run_callbacks( method_name=_CallbackInterface.ON_SCHEDULER_STEP_END, callbacks=self._parse_names(names=callbacks), )
[ "def", "on_scheduler_step_end", "(", "self", ",", "callbacks", ":", "List", "[", "str", "]", "=", "None", ")", "->", "bool", ":", "return", "self", ".", "_run_callbacks", "(", "method_name", "=", "_CallbackInterface", ".", "ON_SCHEDULER_STEP_END", ",", "callbacks", "=", "self", ".", "_parse_names", "(", "names", "=", "callbacks", ")", ",", ")" ]
https://github.com/mlrun/mlrun/blob/4c120719d64327a34b7ee1ab08fb5e01b258b00a/mlrun/frameworks/pytorch/callbacks_handler.py#L594-L606
GoogleCloudPlatform/deploymentmanager-samples
9cc562d7d048a9890572587ca299816c0cd3bb38
examples/v2/step_by_step_guide/step7_use_environment_variables/python/compute-engine-template.py
python
GenerateConfig
(unused_context)
return {'resources': resources}
Creates the Compute Engine with multiple templates.
Creates the Compute Engine with multiple templates.
[ "Creates", "the", "Compute", "Engine", "with", "multiple", "templates", "." ]
def GenerateConfig(unused_context): """Creates the Compute Engine with multiple templates.""" resources = [{ 'name': 'the-first-vm', 'type': 'vm-template.py', 'properties': { 'machineType': 'f1-micro', 'zone': 'us-central1-f', 'network': NETWORK_NAME } }, { 'name': 'the-second-vm', 'type': 'vm-template.py', 'properties': { 'machineType': 'f1-micro', 'zone': 'us-central1-f', 'network': NETWORK_NAME } }, { 'name': NETWORK_NAME, 'type': 'network-template.py' }, { 'name': NETWORK_NAME + '-firewall', 'type': 'firewall-template.py', 'properties': { 'network': NETWORK_NAME } }] return {'resources': resources}
[ "def", "GenerateConfig", "(", "unused_context", ")", ":", "resources", "=", "[", "{", "'name'", ":", "'the-first-vm'", ",", "'type'", ":", "'vm-template.py'", ",", "'properties'", ":", "{", "'machineType'", ":", "'f1-micro'", ",", "'zone'", ":", "'us-central1-f'", ",", "'network'", ":", "NETWORK_NAME", "}", "}", ",", "{", "'name'", ":", "'the-second-vm'", ",", "'type'", ":", "'vm-template.py'", ",", "'properties'", ":", "{", "'machineType'", ":", "'f1-micro'", ",", "'zone'", ":", "'us-central1-f'", ",", "'network'", ":", "NETWORK_NAME", "}", "}", ",", "{", "'name'", ":", "NETWORK_NAME", ",", "'type'", ":", "'network-template.py'", "}", ",", "{", "'name'", ":", "NETWORK_NAME", "+", "'-firewall'", ",", "'type'", ":", "'firewall-template.py'", ",", "'properties'", ":", "{", "'network'", ":", "NETWORK_NAME", "}", "}", "]", "return", "{", "'resources'", ":", "resources", "}" ]
https://github.com/GoogleCloudPlatform/deploymentmanager-samples/blob/9cc562d7d048a9890572587ca299816c0cd3bb38/examples/v2/step_by_step_guide/step7_use_environment_variables/python/compute-engine-template.py#L20-L49
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/aui/auibook.py
python
AuiTabContainer.GetIdxFromWindow
(self, wnd)
return wx.NOT_FOUND
Returns the tab index based on the window `wnd` associated with it. :param `wnd`: an instance of :class:`wx.Window`.
Returns the tab index based on the window `wnd` associated with it.
[ "Returns", "the", "tab", "index", "based", "on", "the", "window", "wnd", "associated", "with", "it", "." ]
def GetIdxFromWindow(self, wnd): """ Returns the tab index based on the window `wnd` associated with it. :param `wnd`: an instance of :class:`wx.Window`. """ for indx, page in enumerate(self._pages): if page.window == wnd: return indx return wx.NOT_FOUND
[ "def", "GetIdxFromWindow", "(", "self", ",", "wnd", ")", ":", "for", "indx", ",", "page", "in", "enumerate", "(", "self", ".", "_pages", ")", ":", "if", "page", ".", "window", "==", "wnd", ":", "return", "indx", "return", "wx", ".", "NOT_FOUND" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/aui/auibook.py#L1232-L1243
pyannote/pyannote-video
5aded79c52cf20a05d1e1f236b9bdd0fb3baa738
scripts/pyannote-face.py
python
pairwise
(iterable)
return zip(a, a)
s -> (s0,s1), (s2,s3), (s4, s5), ...
s -> (s0,s1), (s2,s3), (s4, s5), ...
[ "s", "-", ">", "(", "s0", "s1", ")", "(", "s2", "s3", ")", "(", "s4", "s5", ")", "..." ]
def pairwise(iterable): "s -> (s0,s1), (s2,s3), (s4, s5), ..." a = iter(iterable) return zip(a, a)
[ "def", "pairwise", "(", "iterable", ")", ":", "a", "=", "iter", "(", "iterable", ")", "return", "zip", "(", "a", ",", "a", ")" ]
https://github.com/pyannote/pyannote-video/blob/5aded79c52cf20a05d1e1f236b9bdd0fb3baa738/scripts/pyannote-face.py#L178-L181
pymc-devs/pymc
38867dd19e96afb0ceccc8ccd74a9795f118dfe3
pymc/variational/updates.py
python
adagrad
(loss_or_grads=None, params=None, learning_rate=1.0, epsilon=1e-6)
return updates
Adagrad updates Scale learning rates by dividing with the square root of accumulated squared gradients. See [1]_ for further description. Parameters ---------- loss_or_grads: symbolic expression or list of expressions A scalar loss expression, or a list of gradient expressions params: list of shared variables The variables to generate update expressions for learning_rate: float or symbolic scalar The learning rate controlling the size of update steps epsilon: float or symbolic scalar Small value added for numerical stability Returns ------- OrderedDict A dictionary mapping each parameter to its update expression Notes ----- Using step size eta Adagrad calculates the learning rate for feature i at time step t as: .. math:: \\eta_{t,i} = \\frac{\\eta} {\\sqrt{\\sum^t_{t^\\prime} g^2_{t^\\prime,i}+\\epsilon}} g_{t,i} as such the learning rate is monotonically decreasing. Epsilon is not included in the typical formula, see [2]_. Optimizer can be called without both loss_or_grads and params in that case partial function is returned References ---------- .. [1] Duchi, J., Hazan, E., & Singer, Y. (2011): Adaptive subgradient methods for online learning and stochastic optimization. JMLR, 12:2121-2159. .. [2] Chris Dyer: Notes on AdaGrad. http://www.ark.cs.cmu.edu/cdyer/adagrad.pdf Examples -------- >>> a = aesara.shared(1.) >>> b = a*2 >>> updates = adagrad(b, [a], learning_rate=.01) >>> isinstance(updates, dict) True >>> optimizer = adagrad(learning_rate=.01) >>> callable(optimizer) True >>> updates = optimizer(b, [a]) >>> isinstance(updates, dict) True
Adagrad updates
[ "Adagrad", "updates" ]
def adagrad(loss_or_grads=None, params=None, learning_rate=1.0, epsilon=1e-6): """Adagrad updates Scale learning rates by dividing with the square root of accumulated squared gradients. See [1]_ for further description. Parameters ---------- loss_or_grads: symbolic expression or list of expressions A scalar loss expression, or a list of gradient expressions params: list of shared variables The variables to generate update expressions for learning_rate: float or symbolic scalar The learning rate controlling the size of update steps epsilon: float or symbolic scalar Small value added for numerical stability Returns ------- OrderedDict A dictionary mapping each parameter to its update expression Notes ----- Using step size eta Adagrad calculates the learning rate for feature i at time step t as: .. math:: \\eta_{t,i} = \\frac{\\eta} {\\sqrt{\\sum^t_{t^\\prime} g^2_{t^\\prime,i}+\\epsilon}} g_{t,i} as such the learning rate is monotonically decreasing. Epsilon is not included in the typical formula, see [2]_. Optimizer can be called without both loss_or_grads and params in that case partial function is returned References ---------- .. [1] Duchi, J., Hazan, E., & Singer, Y. (2011): Adaptive subgradient methods for online learning and stochastic optimization. JMLR, 12:2121-2159. .. [2] Chris Dyer: Notes on AdaGrad. http://www.ark.cs.cmu.edu/cdyer/adagrad.pdf Examples -------- >>> a = aesara.shared(1.) >>> b = a*2 >>> updates = adagrad(b, [a], learning_rate=.01) >>> isinstance(updates, dict) True >>> optimizer = adagrad(learning_rate=.01) >>> callable(optimizer) True >>> updates = optimizer(b, [a]) >>> isinstance(updates, dict) True """ if loss_or_grads is None and params is None: return partial(adagrad, **_get_call_kwargs(locals())) elif loss_or_grads is None or params is None: raise ValueError("Please provide both `loss_or_grads` and `params` to get updates") grads = get_or_compute_grads(loss_or_grads, params) updates = OrderedDict() for param, grad in zip(params, grads): value = param.get_value(borrow=True) accu = aesara.shared( np.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadcastable ) accu_new = accu + grad ** 2 updates[accu] = accu_new updates[param] = param - (learning_rate * grad / at.sqrt(accu_new + epsilon)) return updates
[ "def", "adagrad", "(", "loss_or_grads", "=", "None", ",", "params", "=", "None", ",", "learning_rate", "=", "1.0", ",", "epsilon", "=", "1e-6", ")", ":", "if", "loss_or_grads", "is", "None", "and", "params", "is", "None", ":", "return", "partial", "(", "adagrad", ",", "*", "*", "_get_call_kwargs", "(", "locals", "(", ")", ")", ")", "elif", "loss_or_grads", "is", "None", "or", "params", "is", "None", ":", "raise", "ValueError", "(", "\"Please provide both `loss_or_grads` and `params` to get updates\"", ")", "grads", "=", "get_or_compute_grads", "(", "loss_or_grads", ",", "params", ")", "updates", "=", "OrderedDict", "(", ")", "for", "param", ",", "grad", "in", "zip", "(", "params", ",", "grads", ")", ":", "value", "=", "param", ".", "get_value", "(", "borrow", "=", "True", ")", "accu", "=", "aesara", ".", "shared", "(", "np", ".", "zeros", "(", "value", ".", "shape", ",", "dtype", "=", "value", ".", "dtype", ")", ",", "broadcastable", "=", "param", ".", "broadcastable", ")", "accu_new", "=", "accu", "+", "grad", "**", "2", "updates", "[", "accu", "]", "=", "accu_new", "updates", "[", "param", "]", "=", "param", "-", "(", "learning_rate", "*", "grad", "/", "at", ".", "sqrt", "(", "accu_new", "+", "epsilon", ")", ")", "return", "updates" ]
https://github.com/pymc-devs/pymc/blob/38867dd19e96afb0ceccc8ccd74a9795f118dfe3/pymc/variational/updates.py#L468-L544
truenas/middleware
b11ec47d6340324f5a32287ffb4012e5d709b934
src/middlewared/middlewared/plugins/pool.py
python
PoolService.online
(self, oid, options)
return True
Online a disk from pool of id `id`. `label` is the vdev guid or device name. .. examples(websocket):: Online ZFS device. :::javascript { "id": "6841f242-840a-11e6-a437-00e04d680384", "msg": "method", "method": "pool.online, "params": [1, { "label": "80802394992848654" }] }
Online a disk from pool of id `id`.
[ "Online", "a", "disk", "from", "pool", "of", "id", "id", "." ]
async def online(self, oid, options): """ Online a disk from pool of id `id`. `label` is the vdev guid or device name. .. examples(websocket):: Online ZFS device. :::javascript { "id": "6841f242-840a-11e6-a437-00e04d680384", "msg": "method", "method": "pool.online, "params": [1, { "label": "80802394992848654" }] } """ pool = await self.get_instance(oid) verrors = ValidationErrors() found = await self.middleware.call('pool.find_disk_from_topology', options['label'], pool) if not found: verrors.add('options.label', f'Label {options["label"]} not found on this pool.') verrors.check() await self.middleware.call('zfs.pool.online', pool['name'], found[1]['guid']) disk = await self.middleware.call( 'disk.label_to_disk', found[1]['path'].replace('/dev/', '') ) if disk: asyncio.ensure_future(self.middleware.call('disk.swaps_configure')) return True
[ "async", "def", "online", "(", "self", ",", "oid", ",", "options", ")", ":", "pool", "=", "await", "self", ".", "get_instance", "(", "oid", ")", "verrors", "=", "ValidationErrors", "(", ")", "found", "=", "await", "self", ".", "middleware", ".", "call", "(", "'pool.find_disk_from_topology'", ",", "options", "[", "'label'", "]", ",", "pool", ")", "if", "not", "found", ":", "verrors", ".", "add", "(", "'options.label'", ",", "f'Label {options[\"label\"]} not found on this pool.'", ")", "verrors", ".", "check", "(", ")", "await", "self", ".", "middleware", ".", "call", "(", "'zfs.pool.online'", ",", "pool", "[", "'name'", "]", ",", "found", "[", "1", "]", "[", "'guid'", "]", ")", "disk", "=", "await", "self", ".", "middleware", ".", "call", "(", "'disk.label_to_disk'", ",", "found", "[", "1", "]", "[", "'path'", "]", ".", "replace", "(", "'/dev/'", ",", "''", ")", ")", "if", "disk", ":", "asyncio", ".", "ensure_future", "(", "self", ".", "middleware", ".", "call", "(", "'disk.swaps_configure'", ")", ")", "return", "True" ]
https://github.com/truenas/middleware/blob/b11ec47d6340324f5a32287ffb4012e5d709b934/src/middlewared/middlewared/plugins/pool.py#L1147-L1184
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/github/GitRelease.py
python
GitRelease.url
(self)
return self._url.value
:type: string
:type: string
[ ":", "type", ":", "string" ]
def url(self): """ :type: string """ self._completeIfNotSet(self._url) return self._url.value
[ "def", "url", "(", "self", ")", ":", "self", ".", "_completeIfNotSet", "(", "self", ".", "_url", ")", "return", "self", ".", "_url", ".", "value" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/GitRelease.py#L138-L143
johntruckenbrodt/pyroSAR
efac51134ba42d20120b259f968afe5a4ddcc46a
pyroSAR/gamma/parser_demo.py
python
par_ASF_RSAT_SS
(CEOS_leader, CEOS_data, GRD_par, GRD, logpath=None, outdir=None, shellscript=None)
| ISP parameter file for ASF Radarsat-1 SCANSAR images | Copyright 2004, Gamma Remote Sensing, v1.0 27-Aug-2004 clw/uw Parameters ---------- CEOS_leader: (input) CEOS leader file (Radarsat-1 SCANSAR) CEOS_data: (input) CEOS data file (Radarsat-1 SCANSAR) GRD_par: (output) ISP image parameter file (example <orbit>.mli.par) GRD: (output) ISP image (example <orbit>.mli) (enter - for none, short integer) logpath: str or None a directory to write command logfiles to outdir: str or None the directory to execute the command in shellscript: str or None a file to write the Gamma commands to in shell format
| ISP parameter file for ASF Radarsat-1 SCANSAR images | Copyright 2004, Gamma Remote Sensing, v1.0 27-Aug-2004 clw/uw
[ "|", "ISP", "parameter", "file", "for", "ASF", "Radarsat", "-", "1", "SCANSAR", "images", "|", "Copyright", "2004", "Gamma", "Remote", "Sensing", "v1", ".", "0", "27", "-", "Aug", "-", "2004", "clw", "/", "uw" ]
def par_ASF_RSAT_SS(CEOS_leader, CEOS_data, GRD_par, GRD, logpath=None, outdir=None, shellscript=None): """ | ISP parameter file for ASF Radarsat-1 SCANSAR images | Copyright 2004, Gamma Remote Sensing, v1.0 27-Aug-2004 clw/uw Parameters ---------- CEOS_leader: (input) CEOS leader file (Radarsat-1 SCANSAR) CEOS_data: (input) CEOS data file (Radarsat-1 SCANSAR) GRD_par: (output) ISP image parameter file (example <orbit>.mli.par) GRD: (output) ISP image (example <orbit>.mli) (enter - for none, short integer) logpath: str or None a directory to write command logfiles to outdir: str or None the directory to execute the command in shellscript: str or None a file to write the Gamma commands to in shell format """ process(['/usr/local/GAMMA_SOFTWARE-20180703/ISP/bin/par_ASF_RSAT_SS', CEOS_leader, CEOS_data, GRD_par, GRD], logpath=logpath, outdir=outdir, shellscript=shellscript)
[ "def", "par_ASF_RSAT_SS", "(", "CEOS_leader", ",", "CEOS_data", ",", "GRD_par", ",", "GRD", ",", "logpath", "=", "None", ",", "outdir", "=", "None", ",", "shellscript", "=", "None", ")", ":", "process", "(", "[", "'/usr/local/GAMMA_SOFTWARE-20180703/ISP/bin/par_ASF_RSAT_SS'", ",", "CEOS_leader", ",", "CEOS_data", ",", "GRD_par", ",", "GRD", "]", ",", "logpath", "=", "logpath", ",", "outdir", "=", "outdir", ",", "shellscript", "=", "shellscript", ")" ]
https://github.com/johntruckenbrodt/pyroSAR/blob/efac51134ba42d20120b259f968afe5a4ddcc46a/pyroSAR/gamma/parser_demo.py#L2591-L2614
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/scatter/marker/_colorbar.py
python
ColorBar.bgcolor
(self)
return self["bgcolor"]
Sets the color of padded area. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str
Sets the color of padded area. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen
[ "Sets", "the", "color", "of", "padded", "area", ".", "The", "bgcolor", "property", "is", "a", "color", "and", "may", "be", "specified", "as", ":", "-", "A", "hex", "string", "(", "e", ".", "g", ".", "#ff0000", ")", "-", "An", "rgb", "/", "rgba", "string", "(", "e", ".", "g", ".", "rgb", "(", "255", "0", "0", ")", ")", "-", "An", "hsl", "/", "hsla", "string", "(", "e", ".", "g", ".", "hsl", "(", "0", "100%", "50%", ")", ")", "-", "An", "hsv", "/", "hsva", "string", "(", "e", ".", "g", ".", "hsv", "(", "0", "100%", "100%", ")", ")", "-", "A", "named", "CSS", "color", ":", "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgrey", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgrey", "lightgreen", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "rebeccapurple", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen" ]
def bgcolor(self): """ Sets the color of padded area. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["bgcolor"]
[ "def", "bgcolor", "(", "self", ")", ":", "return", "self", "[", "\"bgcolor\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/scatter/marker/_colorbar.py#L64-L114
facelessuser/BracketHighlighter
223ffd4ceafd58686503e3328934c039e959a88c
bh_swapping.py
python
SwapBrackets.wrap
(self, wrap_entry)
Setup for wrapping.
Setup for wrapping.
[ "Setup", "for", "wrapping", "." ]
def wrap(self, wrap_entry): """Setup for wrapping.""" if wrap_entry < 0: return self._style = ["inline"] self.brackets = self._brackets[wrap_entry] self.wrap_brackets(0)
[ "def", "wrap", "(", "self", ",", "wrap_entry", ")", ":", "if", "wrap_entry", "<", "0", ":", "return", "self", ".", "_style", "=", "[", "\"inline\"", "]", "self", ".", "brackets", "=", "self", ".", "_brackets", "[", "wrap_entry", "]", "self", ".", "wrap_brackets", "(", "0", ")" ]
https://github.com/facelessuser/BracketHighlighter/blob/223ffd4ceafd58686503e3328934c039e959a88c/bh_swapping.py#L19-L28
OmkarPathak/pygorithm
be35813729a0151da1ac9ba013453a61ffa249b8
pygorithm/geometry/extrapolated_intersection.py
python
calculate_one_moving_one_stationary_distancelimit
(poly1, poly1_offset, poly1_velocity, poly2, poly2_offset, max_distance)
Determine if the moving polygon will intersect the stationary polygon within some distance. This is a step up, and very similar to the actual problem many any-angle pathfinding algorithms run into. Given two polygons, 1 moving and 1 stationary, determine if the first polygon will intersect the second polygon before moving a specified total distance. :param poly1: the geometry of the polygon that is moving :type poly1: :class:`pygorithm.geometry.polygon2.Polygon2` :param poly1_offset: the starting location of the moving polygon :type poly1_offset: :class:`pygorithm.geometry.vector2.Vector2` :param poly1_velocity: the velocity of the moving polygon :type poly1_velocity: :class:`pygorithm.geometry.vector2.Vector2` :param poly2: the geometry of the stationary polygon :type poly2: :class:`pygorithm.geometry.polygon2.Polygon2` :param poly2_offset: the offset of the stationary polygon :type poly2_offset: :class:`pygorithm.geometry.vector2.Vector2` :param max_distance: the max distance that poly1 can go :type max_distance: :class:`numbers.Number` :returns: if they will intersect :rtype: bool
Determine if the moving polygon will intersect the stationary polygon within some distance. This is a step up, and very similar to the actual problem many any-angle pathfinding algorithms run into. Given two polygons, 1 moving and 1 stationary, determine if the first polygon will intersect the second polygon before moving a specified total distance. :param poly1: the geometry of the polygon that is moving :type poly1: :class:`pygorithm.geometry.polygon2.Polygon2` :param poly1_offset: the starting location of the moving polygon :type poly1_offset: :class:`pygorithm.geometry.vector2.Vector2` :param poly1_velocity: the velocity of the moving polygon :type poly1_velocity: :class:`pygorithm.geometry.vector2.Vector2` :param poly2: the geometry of the stationary polygon :type poly2: :class:`pygorithm.geometry.polygon2.Polygon2` :param poly2_offset: the offset of the stationary polygon :type poly2_offset: :class:`pygorithm.geometry.vector2.Vector2` :param max_distance: the max distance that poly1 can go :type max_distance: :class:`numbers.Number` :returns: if they will intersect :rtype: bool
[ "Determine", "if", "the", "moving", "polygon", "will", "intersect", "the", "stationary", "polygon", "within", "some", "distance", ".", "This", "is", "a", "step", "up", "and", "very", "similar", "to", "the", "actual", "problem", "many", "any", "-", "angle", "pathfinding", "algorithms", "run", "into", ".", "Given", "two", "polygons", "1", "moving", "and", "1", "stationary", "determine", "if", "the", "first", "polygon", "will", "intersect", "the", "second", "polygon", "before", "moving", "a", "specified", "total", "distance", ".", ":", "param", "poly1", ":", "the", "geometry", "of", "the", "polygon", "that", "is", "moving", ":", "type", "poly1", ":", ":", "class", ":", "pygorithm", ".", "geometry", ".", "polygon2", ".", "Polygon2", ":", "param", "poly1_offset", ":", "the", "starting", "location", "of", "the", "moving", "polygon", ":", "type", "poly1_offset", ":", ":", "class", ":", "pygorithm", ".", "geometry", ".", "vector2", ".", "Vector2", ":", "param", "poly1_velocity", ":", "the", "velocity", "of", "the", "moving", "polygon", ":", "type", "poly1_velocity", ":", ":", "class", ":", "pygorithm", ".", "geometry", ".", "vector2", ".", "Vector2", ":", "param", "poly2", ":", "the", "geometry", "of", "the", "stationary", "polygon", ":", "type", "poly2", ":", ":", "class", ":", "pygorithm", ".", "geometry", ".", "polygon2", ".", "Polygon2", ":", "param", "poly2_offset", ":", "the", "offset", "of", "the", "stationary", "polygon", ":", "type", "poly2_offset", ":", ":", "class", ":", "pygorithm", ".", "geometry", ".", "vector2", ".", "Vector2", ":", "param", "max_distance", ":", "the", "max", "distance", "that", "poly1", "can", "go", ":", "type", "max_distance", ":", ":", "class", ":", "numbers", ".", "Number", ":", "returns", ":", "if", "they", "will", "intersect", ":", "rtype", ":", "bool" ]
def calculate_one_moving_one_stationary_distancelimit(poly1, poly1_offset, poly1_velocity, poly2, poly2_offset, max_distance): """ Determine if the moving polygon will intersect the stationary polygon within some distance. This is a step up, and very similar to the actual problem many any-angle pathfinding algorithms run into. Given two polygons, 1 moving and 1 stationary, determine if the first polygon will intersect the second polygon before moving a specified total distance. :param poly1: the geometry of the polygon that is moving :type poly1: :class:`pygorithm.geometry.polygon2.Polygon2` :param poly1_offset: the starting location of the moving polygon :type poly1_offset: :class:`pygorithm.geometry.vector2.Vector2` :param poly1_velocity: the velocity of the moving polygon :type poly1_velocity: :class:`pygorithm.geometry.vector2.Vector2` :param poly2: the geometry of the stationary polygon :type poly2: :class:`pygorithm.geometry.polygon2.Polygon2` :param poly2_offset: the offset of the stationary polygon :type poly2_offset: :class:`pygorithm.geometry.vector2.Vector2` :param max_distance: the max distance that poly1 can go :type max_distance: :class:`numbers.Number` :returns: if they will intersect :rtype: bool """ pass
[ "def", "calculate_one_moving_one_stationary_distancelimit", "(", "poly1", ",", "poly1_offset", ",", "poly1_velocity", ",", "poly2", ",", "poly2_offset", ",", "max_distance", ")", ":", "pass" ]
https://github.com/OmkarPathak/pygorithm/blob/be35813729a0151da1ac9ba013453a61ffa249b8/pygorithm/geometry/extrapolated_intersection.py#L91-L116
zhaoyingjun/TensorFlow-Coding
1ff292e5d659aa98e7bf6d9cc3986ef07ac2ca81
lessonTwo/chinese_seq2seq_chatbot/execute.py
python
create_model
(session, forward_only)
return model
Create model and initialize or load parameters
Create model and initialize or load parameters
[ "Create", "model", "and", "initialize", "or", "load", "parameters" ]
def create_model(session, forward_only): """Create model and initialize or load parameters""" model = seq2seq_model.Seq2SeqModel( gConfig['enc_vocab_size'], gConfig['dec_vocab_size'], _buckets, gConfig['layer_size'], gConfig['num_layers'], gConfig['max_gradient_norm'], gConfig['batch_size'], gConfig['learning_rate'], gConfig['learning_rate_decay_factor'], forward_only=forward_only) if 'pretrained_model' in gConfig: model.saver.restore(session,gConfig['pretrained_model']) return model ckpt = tf.train.get_checkpoint_state(gConfig['working_directory']) """if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path):""" if ckpt and ckpt.model_checkpoint_path: print("Reading model parameters from %s" % ckpt.model_checkpoint_path) model.saver.restore(session, ckpt.model_checkpoint_path) else: print("Created model with fresh parameters.") session.run(tf.global_variables_initializer()) return model
[ "def", "create_model", "(", "session", ",", "forward_only", ")", ":", "model", "=", "seq2seq_model", ".", "Seq2SeqModel", "(", "gConfig", "[", "'enc_vocab_size'", "]", ",", "gConfig", "[", "'dec_vocab_size'", "]", ",", "_buckets", ",", "gConfig", "[", "'layer_size'", "]", ",", "gConfig", "[", "'num_layers'", "]", ",", "gConfig", "[", "'max_gradient_norm'", "]", ",", "gConfig", "[", "'batch_size'", "]", ",", "gConfig", "[", "'learning_rate'", "]", ",", "gConfig", "[", "'learning_rate_decay_factor'", "]", ",", "forward_only", "=", "forward_only", ")", "if", "'pretrained_model'", "in", "gConfig", ":", "model", ".", "saver", ".", "restore", "(", "session", ",", "gConfig", "[", "'pretrained_model'", "]", ")", "return", "model", "ckpt", "=", "tf", ".", "train", ".", "get_checkpoint_state", "(", "gConfig", "[", "'working_directory'", "]", ")", "\"\"\"if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path):\"\"\"", "if", "ckpt", "and", "ckpt", ".", "model_checkpoint_path", ":", "print", "(", "\"Reading model parameters from %s\"", "%", "ckpt", ".", "model_checkpoint_path", ")", "model", ".", "saver", ".", "restore", "(", "session", ",", "ckpt", ".", "model_checkpoint_path", ")", "else", ":", "print", "(", "\"Created model with fresh parameters.\"", ")", "session", ".", "run", "(", "tf", ".", "global_variables_initializer", "(", ")", ")", "return", "model" ]
https://github.com/zhaoyingjun/TensorFlow-Coding/blob/1ff292e5d659aa98e7bf6d9cc3986ef07ac2ca81/lessonTwo/chinese_seq2seq_chatbot/execute.py#L91-L108
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/requests/models.py
python
Response.apparent_encoding
(self)
return chardet.detect(self.content)['encoding']
The apparent encoding, provided by the chardet library
The apparent encoding, provided by the chardet library
[ "The", "apparent", "encoding", "provided", "by", "the", "chardet", "library" ]
def apparent_encoding(self): """The apparent encoding, provided by the chardet library""" return chardet.detect(self.content)['encoding']
[ "def", "apparent_encoding", "(", "self", ")", ":", "return", "chardet", ".", "detect", "(", "self", ".", "content", ")", "[", "'encoding'", "]" ]
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/requests/models.py#L669-L671
facebookarchive/sparts
c03df928677444ad638d10fa96f4144ca4d644e1
sparts/tasks/file.py
python
DirectoryWatcherTask.stat
(self, path)
return os.stat(path)
Wrapper for making unittesting/mocking easier
Wrapper for making unittesting/mocking easier
[ "Wrapper", "for", "making", "unittesting", "/", "mocking", "easier" ]
def stat(self, path): """Wrapper for making unittesting/mocking easier""" return os.stat(path)
[ "def", "stat", "(", "self", ",", "path", ")", ":", "return", "os", ".", "stat", "(", "path", ")" ]
https://github.com/facebookarchive/sparts/blob/c03df928677444ad638d10fa96f4144ca4d644e1/sparts/tasks/file.py#L95-L97
ma1co/Sony-PMCA-RE
d4da4882e4d59b35f59e4ac919a866e2daf4bbdd
pmca/usb/sony.py
python
SonyExtCmdCamera.getMultiWifiAPInfo
(self)
Returns the live streaming multi access point configuration
Returns the live streaming multi access point configuration
[ "Returns", "the", "live", "streaming", "multi", "access", "point", "configuration" ]
def getMultiWifiAPInfo(self): """Returns the live streaming multi access point configuration""" for ap in self._parseAPs(BytesIO(self._sendCommand(self.SONY_CMD_NetworkServiceInfo_GetMultiWifiAPInfo))): yield ap
[ "def", "getMultiWifiAPInfo", "(", "self", ")", ":", "for", "ap", "in", "self", ".", "_parseAPs", "(", "BytesIO", "(", "self", ".", "_sendCommand", "(", "self", ".", "SONY_CMD_NetworkServiceInfo_GetMultiWifiAPInfo", ")", ")", ")", ":", "yield", "ap" ]
https://github.com/ma1co/Sony-PMCA-RE/blob/d4da4882e4d59b35f59e4ac919a866e2daf4bbdd/pmca/usb/sony.py#L402-L405
Net-ng/kansha
85b5816da126b1c7098707c98f217d8b2e524ff2
kansha/card_addons/vote/models.py
python
DataVote.has_voted
(cls, card, user)
return cls.get_vote(card, user) is not None
Return if a user has voted for a given card In: - ``card`` -- DataCard instance - ``user`` -- DataUser instance Return: - True if a vote is found, False otherwise
Return if a user has voted for a given card
[ "Return", "if", "a", "user", "has", "voted", "for", "a", "given", "card" ]
def has_voted(cls, card, user): '''Return if a user has voted for a given card In: - ``card`` -- DataCard instance - ``user`` -- DataUser instance Return: - True if a vote is found, False otherwise ''' return cls.get_vote(card, user) is not None
[ "def", "has_voted", "(", "cls", ",", "card", ",", "user", ")", ":", "return", "cls", ".", "get_vote", "(", "card", ",", "user", ")", "is", "not", "None" ]
https://github.com/Net-ng/kansha/blob/85b5816da126b1c7098707c98f217d8b2e524ff2/kansha/card_addons/vote/models.py#L46-L55
IdentityPython/pysaml2
6badb32d212257bd83ffcc816f9b625f68281b47
src/saml2/sdb.py
python
SessionStorage.get_assertion
(self, cid)
return self.assertion[cid]
[]
def get_assertion(self, cid): return self.assertion[cid]
[ "def", "get_assertion", "(", "self", ",", "cid", ")", ":", "return", "self", ".", "assertion", "[", "cid", "]" ]
https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/sdb.py#L34-L35
roytseng-tw/Detectron.pytorch
1b1c4ba58428b7277a45b0dce6cc1bce3744b86a
lib/modeling/fast_rcnn_heads.py
python
fast_rcnn_outputs._init_weights
(self)
[]
def _init_weights(self): init.normal_(self.cls_score.weight, std=0.01) init.constant_(self.cls_score.bias, 0) init.normal_(self.bbox_pred.weight, std=0.001) init.constant_(self.bbox_pred.bias, 0)
[ "def", "_init_weights", "(", "self", ")", ":", "init", ".", "normal_", "(", "self", ".", "cls_score", ".", "weight", ",", "std", "=", "0.01", ")", "init", ".", "constant_", "(", "self", ".", "cls_score", ".", "bias", ",", "0", ")", "init", ".", "normal_", "(", "self", ".", "bbox_pred", ".", "weight", ",", "std", "=", "0.001", ")", "init", ".", "constant_", "(", "self", ".", "bbox_pred", ".", "bias", ",", "0", ")" ]
https://github.com/roytseng-tw/Detectron.pytorch/blob/1b1c4ba58428b7277a45b0dce6cc1bce3744b86a/lib/modeling/fast_rcnn_heads.py#L23-L27
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/conch/ssh/connection.py
python
SSHConnection.sendExtendedData
(self, channel, dataType, data)
Send extended data to a channel. This should not normally be used: instead use channel.writeExtendedData(data, dataType) as it manages the window automatically. @type channel: subclass of L{SSHChannel} @type dataType: C{int} @type data: C{str}
Send extended data to a channel. This should not normally be used: instead use channel.writeExtendedData(data, dataType) as it manages the window automatically.
[ "Send", "extended", "data", "to", "a", "channel", ".", "This", "should", "not", "normally", "be", "used", ":", "instead", "use", "channel", ".", "writeExtendedData", "(", "data", "dataType", ")", "as", "it", "manages", "the", "window", "automatically", "." ]
def sendExtendedData(self, channel, dataType, data): """ Send extended data to a channel. This should not normally be used: instead use channel.writeExtendedData(data, dataType) as it manages the window automatically. @type channel: subclass of L{SSHChannel} @type dataType: C{int} @type data: C{str} """ if channel.localClosed: return # we're already closed self.transport.sendPacket(MSG_CHANNEL_EXTENDED_DATA, struct.pack('>2L', self.channelsToRemoteChannel[channel],dataType) \ + common.NS(data))
[ "def", "sendExtendedData", "(", "self", ",", "channel", ",", "dataType", ",", "data", ")", ":", "if", "channel", ".", "localClosed", ":", "return", "# we're already closed", "self", ".", "transport", ".", "sendPacket", "(", "MSG_CHANNEL_EXTENDED_DATA", ",", "struct", ".", "pack", "(", "'>2L'", ",", "self", ".", "channelsToRemoteChannel", "[", "channel", "]", ",", "dataType", ")", "+", "common", ".", "NS", "(", "data", ")", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/conch/ssh/connection.py#L473-L487
kamens/gae_bingo
f5285b9ad17dde72991fe123f23095520a554cbf
instance_cache.py
python
increment
(key, expiry=DEFAULT_CACHING_TIME)
Increments key (setting the result to 1 if key isn't present). Also resets the expiry for this key.
Increments key (setting the result to 1 if key isn't present). Also resets the expiry for this key.
[ "Increments", "key", "(", "setting", "the", "result", "to", "1", "if", "key", "isn", "t", "present", ")", ".", "Also", "resets", "the", "expiry", "for", "this", "key", "." ]
def increment(key, expiry=DEFAULT_CACHING_TIME): """ Increments key (setting the result to 1 if key isn't present). Also resets the expiry for this key. """ if ACTIVE is False: return None if expiry != None: expiry = time.time() + int(expiry) try: with _CACHE_LOCK: (old_value, _) = _CACHE.get(key, (0, None)) _CACHE[key] = (old_value + 1, expiry) except TypeError: logging.error("Cannot increment instance-cache key '%s': value '%s' " "is not an integer" % (key, old_value)) except MemoryError: # It doesn't seems to catch the exception, something in the # GAE's python runtime probably. logging.info("%s memory error setting key '%s'" % (__name__, key))
[ "def", "increment", "(", "key", ",", "expiry", "=", "DEFAULT_CACHING_TIME", ")", ":", "if", "ACTIVE", "is", "False", ":", "return", "None", "if", "expiry", "!=", "None", ":", "expiry", "=", "time", ".", "time", "(", ")", "+", "int", "(", "expiry", ")", "try", ":", "with", "_CACHE_LOCK", ":", "(", "old_value", ",", "_", ")", "=", "_CACHE", ".", "get", "(", "key", ",", "(", "0", ",", "None", ")", ")", "_CACHE", "[", "key", "]", "=", "(", "old_value", "+", "1", ",", "expiry", ")", "except", "TypeError", ":", "logging", ".", "error", "(", "\"Cannot increment instance-cache key '%s': value '%s' \"", "\"is not an integer\"", "%", "(", "key", ",", "old_value", ")", ")", "except", "MemoryError", ":", "# It doesn't seems to catch the exception, something in the", "# GAE's python runtime probably.", "logging", ".", "info", "(", "\"%s memory error setting key '%s'\"", "%", "(", "__name__", ",", "key", ")", ")" ]
https://github.com/kamens/gae_bingo/blob/f5285b9ad17dde72991fe123f23095520a554cbf/instance_cache.py#L122-L143
pynag/pynag
e72cf7ce2395263e2b3080cae0ece2b03dbbfa27
pynag/Control/Command/autogenerated_commands.py
python
enable_svc_flap_detection
( host_name, service_description, command_file=None, timestamp=0 )
return send_command("ENABLE_SVC_FLAP_DETECTION", command_file, timestamp, host_name, service_description)
Enables flap detection for the specified service. In order for the flap detection algorithms to be run for the service, flap detection must be enabled on a program-wide basis as well.
Enables flap detection for the specified service. In order for the flap detection algorithms to be run for the service, flap detection must be enabled on a program-wide basis as well.
[ "Enables", "flap", "detection", "for", "the", "specified", "service", ".", "In", "order", "for", "the", "flap", "detection", "algorithms", "to", "be", "run", "for", "the", "service", "flap", "detection", "must", "be", "enabled", "on", "a", "program", "-", "wide", "basis", "as", "well", "." ]
def enable_svc_flap_detection( host_name, service_description, command_file=None, timestamp=0 ): """ Enables flap detection for the specified service. In order for the flap detection algorithms to be run for the service, flap detection must be enabled on a program-wide basis as well. """ return send_command("ENABLE_SVC_FLAP_DETECTION", command_file, timestamp, host_name, service_description)
[ "def", "enable_svc_flap_detection", "(", "host_name", ",", "service_description", ",", "command_file", "=", "None", ",", "timestamp", "=", "0", ")", ":", "return", "send_command", "(", "\"ENABLE_SVC_FLAP_DETECTION\"", ",", "command_file", ",", "timestamp", ",", "host_name", ",", "service_description", ")" ]
https://github.com/pynag/pynag/blob/e72cf7ce2395263e2b3080cae0ece2b03dbbfa27/pynag/Control/Command/autogenerated_commands.py#L2520-L2535
OpenEIT/OpenEIT
0448694e8092361ae5ccb45fba81dee543a6244b
OpenEIT/backend/bluetooth/old/build/dlib/Adafruit_BluefruitLE/interfaces/device.py
python
Device.find_service
(self, uuid)
return None
Return the first child service found that has the specified UUID. Will return None if no service that matches is found.
Return the first child service found that has the specified UUID. Will return None if no service that matches is found.
[ "Return", "the", "first", "child", "service", "found", "that", "has", "the", "specified", "UUID", ".", "Will", "return", "None", "if", "no", "service", "that", "matches", "is", "found", "." ]
def find_service(self, uuid): """Return the first child service found that has the specified UUID. Will return None if no service that matches is found. """ for service in self.list_services(): if service.uuid == uuid: return service return None
[ "def", "find_service", "(", "self", ",", "uuid", ")", ":", "for", "service", "in", "self", ".", "list_services", "(", ")", ":", "if", "service", ".", "uuid", "==", "uuid", ":", "return", "service", "return", "None" ]
https://github.com/OpenEIT/OpenEIT/blob/0448694e8092361ae5ccb45fba81dee543a6244b/OpenEIT/backend/bluetooth/old/build/dlib/Adafruit_BluefruitLE/interfaces/device.py#L87-L94
tahoe-lafs/tahoe-lafs
766a53b5208c03c45ca0a98e97eee76870276aa1
src/allmydata/util/iputil.py
python
get_local_addresses_sync
()
return list( native_str(address[native_str("addr")]) for iface_name in interfaces() for address in ifaddresses(iface_name).get(socket.AF_INET, []) )
Get locally assigned addresses as dotted-quad native strings. :return [str]: A list of IPv4 addresses which are assigned to interfaces on the local system.
Get locally assigned addresses as dotted-quad native strings.
[ "Get", "locally", "assigned", "addresses", "as", "dotted", "-", "quad", "native", "strings", "." ]
def get_local_addresses_sync(): """ Get locally assigned addresses as dotted-quad native strings. :return [str]: A list of IPv4 addresses which are assigned to interfaces on the local system. """ return list( native_str(address[native_str("addr")]) for iface_name in interfaces() for address in ifaddresses(iface_name).get(socket.AF_INET, []) )
[ "def", "get_local_addresses_sync", "(", ")", ":", "return", "list", "(", "native_str", "(", "address", "[", "native_str", "(", "\"addr\"", ")", "]", ")", "for", "iface_name", "in", "interfaces", "(", ")", "for", "address", "in", "ifaddresses", "(", "iface_name", ")", ".", "get", "(", "socket", ".", "AF_INET", ",", "[", "]", ")", ")" ]
https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/util/iputil.py#L105-L118
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/urllib3/_collections.py
python
HTTPHeaderDict.pop
(self, key, default=__marker)
D.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.
D.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.
[ "D", ".", "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", "." ]
def pop(self, key, default=__marker): '''D.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. ''' # Using the MutableMapping function directly fails due to the private marker. # Using ordinary dict.pop would expose the internal structures. # So let's reinvent the wheel. try: value = self[key] except KeyError: if default is self.__marker: raise return default else: del self[key] return value
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "__marker", ")", ":", "# Using the MutableMapping function directly fails due to the private marker.", "# Using ordinary dict.pop would expose the internal structures.", "# So let's reinvent the wheel.", "try", ":", "value", "=", "self", "[", "key", "]", "except", "KeyError", ":", "if", "default", "is", "self", ".", "__marker", ":", "raise", "return", "default", "else", ":", "del", "self", "[", "key", "]", "return", "value" ]
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/urllib3/_collections.py#L186-L201
adafruit/Adafruit_Python_SSD1306
dfa8717cb7a2d8706bef5e1ed6c49763748cd1c3
Adafruit_SSD1306/SSD1306.py
python
SSD1306Base.set_contrast
(self, contrast)
Sets the contrast of the display. Contrast should be a value between 0 and 255.
Sets the contrast of the display. Contrast should be a value between 0 and 255.
[ "Sets", "the", "contrast", "of", "the", "display", ".", "Contrast", "should", "be", "a", "value", "between", "0", "and", "255", "." ]
def set_contrast(self, contrast): """Sets the contrast of the display. Contrast should be a value between 0 and 255.""" if contrast < 0 or contrast > 255: raise ValueError('Contrast must be a value from 0 to 255 (inclusive).') self.command(SSD1306_SETCONTRAST) self.command(contrast)
[ "def", "set_contrast", "(", "self", ",", "contrast", ")", ":", "if", "contrast", "<", "0", "or", "contrast", ">", "255", ":", "raise", "ValueError", "(", "'Contrast must be a value from 0 to 255 (inclusive).'", ")", "self", ".", "command", "(", "SSD1306_SETCONTRAST", ")", "self", ".", "command", "(", "contrast", ")" ]
https://github.com/adafruit/Adafruit_Python_SSD1306/blob/dfa8717cb7a2d8706bef5e1ed6c49763748cd1c3/Adafruit_SSD1306/SSD1306.py#L215-L221
IntelAI/nauta
bbedb114a755cf1f43b834a58fc15fb6e3a4b291
applications/cli/commands/common/logs_utils.py
python
save_logs_to_file
(logs_generator: Generator[LogEntry, None, None], instance_name: str, instance_type: str)
[]
def save_logs_to_file(logs_generator: Generator[LogEntry, None, None], instance_name: str, instance_type: str): filename = instance_name + ".log" confirmation_message = Texts.LOGS_STORING_CONF.format(filename=filename, instance_name=instance_name, instance_type=instance_type) if os.path.isfile(filename): confirmation_message = Texts.LOGS_STORING_CONF_FILE_EXISTS.format(filename=filename, instance_name=instance_name, instance_type=instance_type) if click.get_current_context().obj.force or click.confirm(confirmation_message, default=True): try: with open(filename, 'w') as file, spinner(spinner=NctlSpinner, text=Texts.SAVING_LOGS_TO_FILE_PROGRESS_MSG, color=SPINNER_COLOR): for log_entry in logs_generator: if not log_entry.content.isspace(): formatted_date = format_log_date(log_entry.date) file.write(f'{formatted_date} {log_entry.pod_name} {log_entry.content}') click.echo(Texts.LOGS_STORING_FINAL_MESSAGE) except Exception: handle_error(logger, Texts.LOGS_STORING_ERROR, Texts.LOGS_STORING_ERROR) exit(1) else: click.echo(Texts.LOGS_STORING_CANCEL_MESSAGE)
[ "def", "save_logs_to_file", "(", "logs_generator", ":", "Generator", "[", "LogEntry", ",", "None", ",", "None", "]", ",", "instance_name", ":", "str", ",", "instance_type", ":", "str", ")", ":", "filename", "=", "instance_name", "+", "\".log\"", "confirmation_message", "=", "Texts", ".", "LOGS_STORING_CONF", ".", "format", "(", "filename", "=", "filename", ",", "instance_name", "=", "instance_name", ",", "instance_type", "=", "instance_type", ")", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "confirmation_message", "=", "Texts", ".", "LOGS_STORING_CONF_FILE_EXISTS", ".", "format", "(", "filename", "=", "filename", ",", "instance_name", "=", "instance_name", ",", "instance_type", "=", "instance_type", ")", "if", "click", ".", "get_current_context", "(", ")", ".", "obj", ".", "force", "or", "click", ".", "confirm", "(", "confirmation_message", ",", "default", "=", "True", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "file", ",", "spinner", "(", "spinner", "=", "NctlSpinner", ",", "text", "=", "Texts", ".", "SAVING_LOGS_TO_FILE_PROGRESS_MSG", ",", "color", "=", "SPINNER_COLOR", ")", ":", "for", "log_entry", "in", "logs_generator", ":", "if", "not", "log_entry", ".", "content", ".", "isspace", "(", ")", ":", "formatted_date", "=", "format_log_date", "(", "log_entry", ".", "date", ")", "file", ".", "write", "(", "f'{formatted_date} {log_entry.pod_name} {log_entry.content}'", ")", "click", ".", "echo", "(", "Texts", ".", "LOGS_STORING_FINAL_MESSAGE", ")", "except", "Exception", ":", "handle_error", "(", "logger", ",", "Texts", ".", "LOGS_STORING_ERROR", ",", "Texts", ".", "LOGS_STORING_ERROR", ")", "exit", "(", "1", ")", "else", ":", "click", ".", "echo", "(", "Texts", ".", "LOGS_STORING_CANCEL_MESSAGE", ")" ]
https://github.com/IntelAI/nauta/blob/bbedb114a755cf1f43b834a58fc15fb6e3a4b291/applications/cli/commands/common/logs_utils.py#L119-L145
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/lobotomy/core/include/androguard/androguard/core/bytecodes/apk.py
python
APK.get_file
(self, filename)
Return the raw data of the specified filename :rtype: string
Return the raw data of the specified filename
[ "Return", "the", "raw", "data", "of", "the", "specified", "filename" ]
def get_file(self, filename): """ Return the raw data of the specified filename :rtype: string """ try: return self.zip.read(filename) except KeyError: return ""
[ "def", "get_file", "(", "self", ",", "filename", ")", ":", "try", ":", "return", "self", ".", "zip", ".", "read", "(", "filename", ")", "except", "KeyError", ":", "return", "\"\"" ]
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/lobotomy/core/include/androguard/androguard/core/bytecodes/apk.py#L351-L360
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
tools/compile_tf_graph.py
python
init
(config_filename, log_verbosity)
:param str config_filename: filename to config-file :param int log_verbosity:
:param str config_filename: filename to config-file :param int log_verbosity:
[ ":", "param", "str", "config_filename", ":", "filename", "to", "config", "-", "file", ":", "param", "int", "log_verbosity", ":" ]
def init(config_filename, log_verbosity): """ :param str config_filename: filename to config-file :param int log_verbosity: """ rnn.init_better_exchook() rnn.init_thread_join_hack() print("Using config file %r." % config_filename) assert os.path.exists(config_filename) rnn.init_config(config_filename=config_filename, extra_updates={ "use_tensorflow": True, "log": None, "log_verbosity": log_verbosity, "task": __file__, # just extra info for the config }) global config config = rnn.config rnn.init_log() print("Returnn compile-tf-graph starting up.", file=log.v1) rnn.returnn_greeting() rnn.init_backend_engine() assert util.BackendEngine.is_tensorflow_selected(), "this is only for TensorFlow" rnn.init_faulthandler() rnn.init_config_json_network()
[ "def", "init", "(", "config_filename", ",", "log_verbosity", ")", ":", "rnn", ".", "init_better_exchook", "(", ")", "rnn", ".", "init_thread_join_hack", "(", ")", "print", "(", "\"Using config file %r.\"", "%", "config_filename", ")", "assert", "os", ".", "path", ".", "exists", "(", "config_filename", ")", "rnn", ".", "init_config", "(", "config_filename", "=", "config_filename", ",", "extra_updates", "=", "{", "\"use_tensorflow\"", ":", "True", ",", "\"log\"", ":", "None", ",", "\"log_verbosity\"", ":", "log_verbosity", ",", "\"task\"", ":", "__file__", ",", "# just extra info for the config", "}", ")", "global", "config", "config", "=", "rnn", ".", "config", "rnn", ".", "init_log", "(", ")", "print", "(", "\"Returnn compile-tf-graph starting up.\"", ",", "file", "=", "log", ".", "v1", ")", "rnn", ".", "returnn_greeting", "(", ")", "rnn", ".", "init_backend_engine", "(", ")", "assert", "util", ".", "BackendEngine", ".", "is_tensorflow_selected", "(", ")", ",", "\"this is only for TensorFlow\"", "rnn", ".", "init_faulthandler", "(", ")", "rnn", ".", "init_config_json_network", "(", ")" ]
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/tools/compile_tf_graph.py#L37-L60
Xilinx/finn
d1cc9cf94f1c33354cc169c5a6517314d0e94e3b
src/finn/custom_op/fpgadataflow/lookup.py
python
Lookup.get_input_datatype
(self)
return ret
[]
def get_input_datatype(self): ret = DataType[self.get_nodeattr("InputType")] return ret
[ "def", "get_input_datatype", "(", "self", ")", ":", "ret", "=", "DataType", "[", "self", ".", "get_nodeattr", "(", "\"InputType\"", ")", "]", "return", "ret" ]
https://github.com/Xilinx/finn/blob/d1cc9cf94f1c33354cc169c5a6517314d0e94e3b/src/finn/custom_op/fpgadataflow/lookup.py#L113-L115