nwo
stringlengths
5
91
sha
stringlengths
40
40
path
stringlengths
5
174
language
stringclasses
1 value
identifier
stringlengths
1
120
parameters
stringlengths
0
3.15k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
24.1k
docstring
stringlengths
0
27.3k
docstring_summary
stringlengths
0
13.8k
docstring_tokens
sequence
function
stringlengths
22
139k
function_tokens
sequence
url
stringlengths
87
283
sdispater/orator
0666e522be914db285b6936e3c36801fc1a9c2e7
orator/dbal/table.py
python
Table.rename_index
(self, old_name, new_name=None)
return self.add_index(old_index.get_columns(), new_name, old_index.get_flags())
Renames an index. :param old_name: The name of the index to rename from. :type old_name: str :param new_name: The name of the index to rename to. :type new_name: str or None :rtype: Table
Renames an index.
[ "Renames", "an", "index", "." ]
def rename_index(self, old_name, new_name=None): """ Renames an index. :param old_name: The name of the index to rename from. :type old_name: str :param new_name: The name of the index to rename to. :type new_name: str or None :rtype: Table """ old_name = self._normalize_identifier(old_name) normalized_new_name = self._normalize_identifier(new_name) if old_name == normalized_new_name: return self if not self.has_index(old_name): raise IndexDoesNotExist(old_name, self._name) if self.has_index(normalized_new_name): raise IndexAlreadyExists(normalized_new_name, self._name) old_index = self._indexes[old_name] if old_index.is_primary(): self.drop_primary_key() return self.set_primary_key(old_index.get_columns(), new_name) del self._indexes[old_name] if old_index.is_unique(): return self.add_unique_index(old_index.get_columns(), new_name) return self.add_index(old_index.get_columns(), new_name, old_index.get_flags())
[ "def", "rename_index", "(", "self", ",", "old_name", ",", "new_name", "=", "None", ")", ":", "old_name", "=", "self", ".", "_normalize_identifier", "(", "old_name", ")", "normalized_new_name", "=", "self", ".", "_normalize_identifier", "(", "new_name", ")", "if", "old_name", "==", "normalized_new_name", ":", "return", "self", "if", "not", "self", ".", "has_index", "(", "old_name", ")", ":", "raise", "IndexDoesNotExist", "(", "old_name", ",", "self", ".", "_name", ")", "if", "self", ".", "has_index", "(", "normalized_new_name", ")", ":", "raise", "IndexAlreadyExists", "(", "normalized_new_name", ",", "self", ".", "_name", ")", "old_index", "=", "self", ".", "_indexes", "[", "old_name", "]", "if", "old_index", ".", "is_primary", "(", ")", ":", "self", ".", "drop_primary_key", "(", ")", "return", "self", ".", "set_primary_key", "(", "old_index", ".", "get_columns", "(", ")", ",", "new_name", ")", "del", "self", ".", "_indexes", "[", "old_name", "]", "if", "old_index", ".", "is_unique", "(", ")", ":", "return", "self", ".", "add_unique_index", "(", "old_index", ".", "get_columns", "(", ")", ",", "new_name", ")", "return", "self", ".", "add_index", "(", "old_index", ".", "get_columns", "(", ")", ",", "new_name", ",", "old_index", ".", "get_flags", "(", ")", ")" ]
https://github.com/sdispater/orator/blob/0666e522be914db285b6936e3c36801fc1a9c2e7/orator/dbal/table.py#L114-L150
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/fourwaysplitter.py
python
FourWaySplitter.MoveSplit
(self, x, y)
Moves the split accordingly to user action. :param `x`: the new splitter `x` coordinate; :param `y`: the new splitter `y` coordinate.
Moves the split accordingly to user action.
[ "Moves", "the", "split", "accordingly", "to", "user", "action", "." ]
def MoveSplit(self, x, y): """ Moves the split accordingly to user action. :param `x`: the new splitter `x` coordinate; :param `y`: the new splitter `y` coordinate. """ width, height = self.GetSize() barSize = self._GetSashSize() if x < 0: x = 0 if y < 0: y = 0 if x > width - barSize: x = width - barSize if y > height - barSize: y = height - barSize self._splitx = x self._splity = y
[ "def", "MoveSplit", "(", "self", ",", "x", ",", "y", ")", ":", "width", ",", "height", "=", "self", ".", "GetSize", "(", ")", "barSize", "=", "self", ".", "_GetSashSize", "(", ")", "if", "x", "<", "0", ":", "x", "=", "0", "if", "y", "<", "0", ":", "y", "=", "0", "if", "x", ">", "width", "-", "barSize", ":", "x", "=", "width", "-", "barSize", "if", "y", ">", "height", "-", "barSize", ":", "y", "=", "height", "-", "barSize", "self", ".", "_splitx", "=", "x", "self", ".", "_splity", "=", "y" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/fourwaysplitter.py#L648-L665
axi0mX/ipwndfu
0e28932ec6a2a570b10fd77e50bda4216418cd98
usb/control.py
python
set_interface
(dev, bInterfaceNumber, bAlternateSetting)
r"""Set the alternate setting of the interface. dev is the Device object to which the request will be sent to.
r"""Set the alternate setting of the interface.
[ "r", "Set", "the", "alternate", "setting", "of", "the", "interface", "." ]
def set_interface(dev, bInterfaceNumber, bAlternateSetting): r"""Set the alternate setting of the interface. dev is the Device object to which the request will be sent to. """ dev.set_interface_altsetting(bInterfaceNumber, bAlternateSetting)
[ "def", "set_interface", "(", "dev", ",", "bInterfaceNumber", ",", "bAlternateSetting", ")", ":", "dev", ".", "set_interface_altsetting", "(", "bInterfaceNumber", ",", "bAlternateSetting", ")" ]
https://github.com/axi0mX/ipwndfu/blob/0e28932ec6a2a570b10fd77e50bda4216418cd98/usb/control.py#L246-L252
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/simplejson/encoder.py
python
JSONEncoder.default
(self, o)
Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o)
Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``).
[ "Implement", "this", "method", "in", "a", "subclass", "such", "that", "it", "returns", "a", "serializable", "object", "for", "o", "or", "calls", "the", "base", "implementation", "(", "to", "raise", "a", "TypeError", ")", "." ]
def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError('Object of type %s is not JSON serializable' % o.__class__.__name__)
[ "def", "default", "(", "self", ",", "o", ")", ":", "raise", "TypeError", "(", "'Object of type %s is not JSON serializable'", "%", "o", ".", "__class__", ".", "__name__", ")" ]
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/simplejson/encoder.py#L254-L273
OpenMDAO/OpenMDAO1
791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317
openmdao/core/data_transfer.py
python
DataTransfer.transfer
(self, srcvec, tgtvec, mode='fwd', deriv=False)
Performs data transfer between a source vector and a target vector. Args ---- srcvec : `VecWrapper` Variables that are the source of the transfer in fwd mode and the destination of the transfer in rev mode. tgtvec : `VecWrapper` Variables that are the destination of the transfer in fwd mode and the source of the transfer in rev mode. mode : 'fwd' or 'rev', optional Direction of the data transfer, source to target ('fwd', the default) or target to source ('rev'). deriv : bool, optional If True, this is a derivative data transfer, so no pass_by_obj variables will be transferred.
Performs data transfer between a source vector and a target vector.
[ "Performs", "data", "transfer", "between", "a", "source", "vector", "and", "a", "target", "vector", "." ]
def transfer(self, srcvec, tgtvec, mode='fwd', deriv=False): """ Performs data transfer between a source vector and a target vector. Args ---- srcvec : `VecWrapper` Variables that are the source of the transfer in fwd mode and the destination of the transfer in rev mode. tgtvec : `VecWrapper` Variables that are the destination of the transfer in fwd mode and the source of the transfer in rev mode. mode : 'fwd' or 'rev', optional Direction of the data transfer, source to target ('fwd', the default) or target to source ('rev'). deriv : bool, optional If True, this is a derivative data transfer, so no pass_by_obj variables will be transferred. """ if mode == 'rev': # in reverse mode, srcvec and tgtvec are switched. Note, we only # run in reverse for derivatives, and derivatives accumulate from # all targets. byobjs are never scattered in reverse for isrcs, itgts, src_unique in self.scatters: if src_unique: srcvec.vec[isrcs] += tgtvec.vec[itgts] else: np.add.at(srcvec.vec, isrcs, tgtvec.vec[itgts]) else: if tgtvec._probdata.in_complex_step: for isrcs, itgts, _ in self.scatters: tgtvec.vec[itgts] = srcvec.vec[isrcs] tgtvec.imag_vec[itgts] = srcvec.imag_vec[isrcs] else: for isrcs, itgts, _ in self.scatters: tgtvec.vec[itgts] = srcvec.vec[isrcs] # forward, include byobjs if not a deriv scatter if not deriv: for tgt, src in self.byobj_conns: if isinstance(srcvec[src], FileRef): tgtvec[tgt]._assign_to(srcvec[src]) else: tgtvec[tgt] = srcvec[src]
[ "def", "transfer", "(", "self", ",", "srcvec", ",", "tgtvec", ",", "mode", "=", "'fwd'", ",", "deriv", "=", "False", ")", ":", "if", "mode", "==", "'rev'", ":", "# in reverse mode, srcvec and tgtvec are switched. Note, we only", "# run in reverse for derivatives, and derivatives accumulate from", "# all targets. byobjs are never scattered in reverse", "for", "isrcs", ",", "itgts", ",", "src_unique", "in", "self", ".", "scatters", ":", "if", "src_unique", ":", "srcvec", ".", "vec", "[", "isrcs", "]", "+=", "tgtvec", ".", "vec", "[", "itgts", "]", "else", ":", "np", ".", "add", ".", "at", "(", "srcvec", ".", "vec", ",", "isrcs", ",", "tgtvec", ".", "vec", "[", "itgts", "]", ")", "else", ":", "if", "tgtvec", ".", "_probdata", ".", "in_complex_step", ":", "for", "isrcs", ",", "itgts", ",", "_", "in", "self", ".", "scatters", ":", "tgtvec", ".", "vec", "[", "itgts", "]", "=", "srcvec", ".", "vec", "[", "isrcs", "]", "tgtvec", ".", "imag_vec", "[", "itgts", "]", "=", "srcvec", ".", "imag_vec", "[", "isrcs", "]", "else", ":", "for", "isrcs", ",", "itgts", ",", "_", "in", "self", ".", "scatters", ":", "tgtvec", ".", "vec", "[", "itgts", "]", "=", "srcvec", ".", "vec", "[", "isrcs", "]", "# forward, include byobjs if not a deriv scatter", "if", "not", "deriv", ":", "for", "tgt", ",", "src", "in", "self", ".", "byobj_conns", ":", "if", "isinstance", "(", "srcvec", "[", "src", "]", ",", "FileRef", ")", ":", "tgtvec", "[", "tgt", "]", ".", "_assign_to", "(", "srcvec", "[", "src", "]", ")", "else", ":", "tgtvec", "[", "tgt", "]", "=", "srcvec", "[", "src", "]" ]
https://github.com/OpenMDAO/OpenMDAO1/blob/791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317/openmdao/core/data_transfer.py#L88-L134
phaethon/kamene
bf679a65d456411942ee4a907818ba3d6a183bfe
kamene/utils.py
python
corrupt_bytes
(s, p=0.01, n=None)
return s.tobytes()
Corrupt a given percentage or number of bytes from bytes
Corrupt a given percentage or number of bytes from bytes
[ "Corrupt", "a", "given", "percentage", "or", "number", "of", "bytes", "from", "bytes" ]
def corrupt_bytes(s, p=0.01, n=None): """Corrupt a given percentage or number of bytes from bytes""" s = bytes(s) s = array.array("B",s) l = len(s) if n is None: n = max(1,int(l*p)) for i in random.sample(range(l), n): s[i] = (s[i]+random.randint(1,255))%256 return s.tobytes()
[ "def", "corrupt_bytes", "(", "s", ",", "p", "=", "0.01", ",", "n", "=", "None", ")", ":", "s", "=", "bytes", "(", "s", ")", "s", "=", "array", ".", "array", "(", "\"B\"", ",", "s", ")", "l", "=", "len", "(", "s", ")", "if", "n", "is", "None", ":", "n", "=", "max", "(", "1", ",", "int", "(", "l", "*", "p", ")", ")", "for", "i", "in", "random", ".", "sample", "(", "range", "(", "l", ")", ",", "n", ")", ":", "s", "[", "i", "]", "=", "(", "s", "[", "i", "]", "+", "random", ".", "randint", "(", "1", ",", "255", ")", ")", "%", "256", "return", "s", ".", "tobytes", "(", ")" ]
https://github.com/phaethon/kamene/blob/bf679a65d456411942ee4a907818ba3d6a183bfe/kamene/utils.py#L516-L525
mozilla/telemetry-airflow
8162470e6eaad5688715ee53f32336ebc00bf352
dags/utils/patched/dataproc_hook.py
python
DataprocHook.diagnose_cluster
( self, region: str, cluster_name: str, project_id: str, retry: Optional[Retry] = None, timeout: Optional[float] = None, metadata: Optional[Sequence[Tuple[str, str]]] = None, )
return gcs_uri
Gets cluster diagnostic information. After the operation completes GCS uri to diagnose is returned :param project_id: Required. The ID of the Google Cloud project that the cluster belongs to. :type project_id: str :param region: Required. The Cloud Dataproc region in which to handle the request. :type region: str :param cluster_name: Required. The cluster name. :type cluster_name: str :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be retried. :type retry: google.api_core.retry.Retry :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :type timeout: float :param metadata: Additional metadata that is provided to the method. :type metadata: Sequence[Tuple[str, str]]
Gets cluster diagnostic information. After the operation completes GCS uri to diagnose is returned
[ "Gets", "cluster", "diagnostic", "information", ".", "After", "the", "operation", "completes", "GCS", "uri", "to", "diagnose", "is", "returned" ]
def diagnose_cluster( self, region: str, cluster_name: str, project_id: str, retry: Optional[Retry] = None, timeout: Optional[float] = None, metadata: Optional[Sequence[Tuple[str, str]]] = None, ): """ Gets cluster diagnostic information. After the operation completes GCS uri to diagnose is returned :param project_id: Required. The ID of the Google Cloud project that the cluster belongs to. :type project_id: str :param region: Required. The Cloud Dataproc region in which to handle the request. :type region: str :param cluster_name: Required. The cluster name. :type cluster_name: str :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be retried. :type retry: google.api_core.retry.Retry :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :type timeout: float :param metadata: Additional metadata that is provided to the method. :type metadata: Sequence[Tuple[str, str]] """ client = self.get_cluster_client(region=region) operation = client.diagnose_cluster( request={'project_id': project_id, 'region': region, 'cluster_name': cluster_name}, retry=retry, timeout=timeout, metadata=metadata, ) operation.result() gcs_uri = str(operation.operation.response.value) return gcs_uri
[ "def", "diagnose_cluster", "(", "self", ",", "region", ":", "str", ",", "cluster_name", ":", "str", ",", "project_id", ":", "str", ",", "retry", ":", "Optional", "[", "Retry", "]", "=", "None", ",", "timeout", ":", "Optional", "[", "float", "]", "=", "None", ",", "metadata", ":", "Optional", "[", "Sequence", "[", "Tuple", "[", "str", ",", "str", "]", "]", "]", "=", "None", ",", ")", ":", "client", "=", "self", ".", "get_cluster_client", "(", "region", "=", "region", ")", "operation", "=", "client", ".", "diagnose_cluster", "(", "request", "=", "{", "'project_id'", ":", "project_id", ",", "'region'", ":", "region", ",", "'cluster_name'", ":", "cluster_name", "}", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")", "operation", ".", "result", "(", ")", "gcs_uri", "=", "str", "(", "operation", ".", "operation", ".", "response", ".", "value", ")", "return", "gcs_uri" ]
https://github.com/mozilla/telemetry-airflow/blob/8162470e6eaad5688715ee53f32336ebc00bf352/dags/utils/patched/dataproc_hook.py#L405-L442
ni/nidaqmx-python
62fc6b48cbbb330fe1bcc9aedadc86610a1269b6
nidaqmx/_task_modules/triggering/start_trigger.py
python
StartTrigger.cfg_anlg_edge_start_trig
( self, trigger_source="", trigger_slope=Slope.RISING, trigger_level=0.0)
Configures the task to start acquiring or generating samples when an analog signal crosses the level you specify. Args: trigger_source (Optional[str]): Is the name of a virtual channel or terminal where there is an analog signal to use as the source of the trigger. trigger_slope (Optional[nidaqmx.constants.Slope]): Specifies on which slope of the signal to start acquiring or generating samples when the signal crosses **trigger_level**. trigger_level (Optional[float]): Specifies at what threshold to start acquiring or generating samples. Specify this value in the units of the measurement or generation. Use **trigger_slope** to specify on which slope to trigger at this threshold.
Configures the task to start acquiring or generating samples when an analog signal crosses the level you specify.
[ "Configures", "the", "task", "to", "start", "acquiring", "or", "generating", "samples", "when", "an", "analog", "signal", "crosses", "the", "level", "you", "specify", "." ]
def cfg_anlg_edge_start_trig( self, trigger_source="", trigger_slope=Slope.RISING, trigger_level=0.0): """ Configures the task to start acquiring or generating samples when an analog signal crosses the level you specify. Args: trigger_source (Optional[str]): Is the name of a virtual channel or terminal where there is an analog signal to use as the source of the trigger. trigger_slope (Optional[nidaqmx.constants.Slope]): Specifies on which slope of the signal to start acquiring or generating samples when the signal crosses **trigger_level**. trigger_level (Optional[float]): Specifies at what threshold to start acquiring or generating samples. Specify this value in the units of the measurement or generation. Use **trigger_slope** to specify on which slope to trigger at this threshold. """ cfunc = lib_importer.windll.DAQmxCfgAnlgEdgeStartTrig if cfunc.argtypes is None: with cfunc.arglock: if cfunc.argtypes is None: cfunc.argtypes = [ lib_importer.task_handle, ctypes_byte_str, ctypes.c_int, ctypes.c_double] error_code = cfunc( self._handle, trigger_source, trigger_slope.value, trigger_level) check_for_error(error_code)
[ "def", "cfg_anlg_edge_start_trig", "(", "self", ",", "trigger_source", "=", "\"\"", ",", "trigger_slope", "=", "Slope", ".", "RISING", ",", "trigger_level", "=", "0.0", ")", ":", "cfunc", "=", "lib_importer", ".", "windll", ".", "DAQmxCfgAnlgEdgeStartTrig", "if", "cfunc", ".", "argtypes", "is", "None", ":", "with", "cfunc", ".", "arglock", ":", "if", "cfunc", ".", "argtypes", "is", "None", ":", "cfunc", ".", "argtypes", "=", "[", "lib_importer", ".", "task_handle", ",", "ctypes_byte_str", ",", "ctypes", ".", "c_int", ",", "ctypes", ".", "c_double", "]", "error_code", "=", "cfunc", "(", "self", ".", "_handle", ",", "trigger_source", ",", "trigger_slope", ".", "value", ",", "trigger_level", ")", "check_for_error", "(", "error_code", ")" ]
https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/_task_modules/triggering/start_trigger.py#L1853-L1884
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/datetime.py
python
time.__hash__
(self)
return self._hashcode
Hash.
Hash.
[ "Hash", "." ]
def __hash__(self): """Hash.""" if self._hashcode == -1: if self.fold: t = self.replace(fold=0) else: t = self tzoff = t.utcoffset() if not tzoff: # zero or None self._hashcode = hash(t._getstate()[0]) else: h, m = divmod(timedelta(hours=self.hour, minutes=self.minute) - tzoff, timedelta(hours=1)) assert not m % timedelta(minutes=1), "whole minute" m //= timedelta(minutes=1) if 0 <= h < 24: self._hashcode = hash(time(h, m, self.second, self.microsecond)) else: self._hashcode = hash((h, m, self.second, self.microsecond)) return self._hashcode
[ "def", "__hash__", "(", "self", ")", ":", "if", "self", ".", "_hashcode", "==", "-", "1", ":", "if", "self", ".", "fold", ":", "t", "=", "self", ".", "replace", "(", "fold", "=", "0", ")", "else", ":", "t", "=", "self", "tzoff", "=", "t", ".", "utcoffset", "(", ")", "if", "not", "tzoff", ":", "# zero or None", "self", ".", "_hashcode", "=", "hash", "(", "t", ".", "_getstate", "(", ")", "[", "0", "]", ")", "else", ":", "h", ",", "m", "=", "divmod", "(", "timedelta", "(", "hours", "=", "self", ".", "hour", ",", "minutes", "=", "self", ".", "minute", ")", "-", "tzoff", ",", "timedelta", "(", "hours", "=", "1", ")", ")", "assert", "not", "m", "%", "timedelta", "(", "minutes", "=", "1", ")", ",", "\"whole minute\"", "m", "//=", "timedelta", "(", "minutes", "=", "1", ")", "if", "0", "<=", "h", "<", "24", ":", "self", ".", "_hashcode", "=", "hash", "(", "time", "(", "h", ",", "m", ",", "self", ".", "second", ",", "self", ".", "microsecond", ")", ")", "else", ":", "self", ".", "_hashcode", "=", "hash", "(", "(", "h", ",", "m", ",", "self", ".", "second", ",", "self", ".", "microsecond", ")", ")", "return", "self", ".", "_hashcode" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/datetime.py#L1169-L1188
hubblestack/hubble
763142474edcecdec5fd25591dc29c3536e8f969
hubblestack/returners/__init__.py
python
_fetch_profile_opts
( cfg, virtualname, __mods__, _options, profile_attr, profile_attrs )
return dict( (pattr, creds.get("{0}.{1}".format(virtualname, profile_attrs[pattr]))) for pattr in profile_attrs )
Fetches profile specific options if applicable @see :func:`get_returner_options` :return: a options dict
Fetches profile specific options if applicable
[ "Fetches", "profile", "specific", "options", "if", "applicable" ]
def _fetch_profile_opts( cfg, virtualname, __mods__, _options, profile_attr, profile_attrs ): """ Fetches profile specific options if applicable @see :func:`get_returner_options` :return: a options dict """ if (not profile_attr) or (profile_attr not in _options): return {} # Using a profile and it is in _options creds = {} profile = _options[profile_attr] if profile: log.info("Using profile %s", profile) if "config.option" in __mods__: creds = cfg(profile) else: creds = cfg.get(profile) if not creds: return {} return dict( (pattr, creds.get("{0}.{1}".format(virtualname, profile_attrs[pattr]))) for pattr in profile_attrs )
[ "def", "_fetch_profile_opts", "(", "cfg", ",", "virtualname", ",", "__mods__", ",", "_options", ",", "profile_attr", ",", "profile_attrs", ")", ":", "if", "(", "not", "profile_attr", ")", "or", "(", "profile_attr", "not", "in", "_options", ")", ":", "return", "{", "}", "# Using a profile and it is in _options", "creds", "=", "{", "}", "profile", "=", "_options", "[", "profile_attr", "]", "if", "profile", ":", "log", ".", "info", "(", "\"Using profile %s\"", ",", "profile", ")", "if", "\"config.option\"", "in", "__mods__", ":", "creds", "=", "cfg", "(", "profile", ")", "else", ":", "creds", "=", "cfg", ".", "get", "(", "profile", ")", "if", "not", "creds", ":", "return", "{", "}", "return", "dict", "(", "(", "pattr", ",", "creds", ".", "get", "(", "\"{0}.{1}\"", ".", "format", "(", "virtualname", ",", "profile_attrs", "[", "pattr", "]", ")", ")", ")", "for", "pattr", "in", "profile_attrs", ")" ]
https://github.com/hubblestack/hubble/blob/763142474edcecdec5fd25591dc29c3536e8f969/hubblestack/returners/__init__.py#L153-L183
buildbot/buildbot
b9c558217c72e4c2463eedc7ec6d56736f7b01a8
master/buildbot/changes/mail.py
python
CVSMaildirSource.parse
(self, m, prefix=None)
return ('cvs', dict(author=author, committer=None, files=files, comments=comments, isdir=isdir, when=when, branch=branch, revision=rev, category=category, repository=cvsroot, project=project, properties=self.properties))
Parse messages sent by the 'buildbot-cvs-mail' program.
Parse messages sent by the 'buildbot-cvs-mail' program.
[ "Parse", "messages", "sent", "by", "the", "buildbot", "-", "cvs", "-", "mail", "program", "." ]
def parse(self, m, prefix=None): """Parse messages sent by the 'buildbot-cvs-mail' program. """ # The mail is sent from the person doing the checkin. Assume that the # local username is enough to identify them (this assumes a one-server # cvs-over-rsh environment rather than the server-dirs-shared-over-NFS # model) name, addr = parseaddr(m["from"]) if not addr: # no From means this message isn't from buildbot-cvs-mail return None at = addr.find("@") if at == -1: author = addr # might still be useful else: author = addr[:at] author = util.bytes2unicode(author, encoding="ascii") # CVS accepts RFC822 dates. buildbot-cvs-mail adds the date as # part of the mail header, so use that. # This assumes cvs is being access via ssh or pserver, so the time # will be the CVS server's time. # calculate a "revision" based on that timestamp, or the current time # if we're unable to parse the date. log.msg('Processing CVS mail') dateTuple = parsedate_tz(m["date"]) if dateTuple is None: when = util.now() else: when = mktime_tz(dateTuple) theTime = datetime.datetime.utcfromtimestamp(float(when)) rev = theTime.strftime('%Y-%m-%d %H:%M:%S') catRE = re.compile(r'^Category:\s*(\S.*)') cvsRE = re.compile(r'^CVSROOT:\s*(\S.*)') cvsmodeRE = re.compile(r'^Cvsmode:\s*(\S.*)') filesRE = re.compile(r'^Files:\s*(\S.*)') modRE = re.compile(r'^Module:\s*(\S.*)') pathRE = re.compile(r'^Path:\s*(\S.*)') projRE = re.compile(r'^Project:\s*(\S.*)') singleFileRE = re.compile(r'(.*) (NONE|\d(\.|\d)+) (NONE|\d(\.|\d)+)') tagRE = re.compile(r'^\s+Tag:\s*(\S.*)') updateRE = re.compile(r'^Update of:\s*(\S.*)') comments = "" branch = None cvsroot = None fileList = None files = [] isdir = 0 path = None project = None lines = list(body_line_iterator(m)) while lines: line = lines.pop(0) m = catRE.match(line) if m: category = m.group(1) continue m = cvsRE.match(line) if m: cvsroot = m.group(1) continue m = cvsmodeRE.match(line) if m: cvsmode = m.group(1) continue m = filesRE.match(line) if m: fileList = m.group(1) continue m = modRE.match(line) if m: # We don't actually use this # module = m.group(1) continue m = pathRE.match(line) if m: path = m.group(1) continue m = projRE.match(line) if m: project = m.group(1) continue m = tagRE.match(line) if m: branch = m.group(1) continue m = updateRE.match(line) if m: # We don't actually use this # updateof = m.group(1) continue if line == "Log Message:\n": break # CVS 1.11 lists files as: # repo/path file,old-version,new-version file2,old-version,new-version # Version 1.12 lists files as: # file1 old-version new-version file2 old-version new-version # # files consists of tuples of 'file-name old-version new-version' # The versions are either dotted-decimal version numbers, ie 1.1 # or NONE. New files are of the form 'NONE NUMBER', while removed # files are 'NUMBER NONE'. 'NONE' is a literal string # Parsing this instead of files list in 'Added File:' etc # makes it possible to handle files with embedded spaces, though # it could fail if the filename was 'bad 1.1 1.2' # For cvs version 1.11, we expect # my_module new_file.c,NONE,1.1 # my_module removed.txt,1.2,NONE # my_module modified_file.c,1.1,1.2 # While cvs version 1.12 gives us # new_file.c NONE 1.1 # removed.txt 1.2 NONE # modified_file.c 1.1,1.2 if fileList is None: log.msg('CVSMaildirSource Mail with no files. Ignoring') return None # We don't have any files. Email not from CVS if cvsmode == '1.11': # Please, no repo paths with spaces! m = re.search('([^ ]*) ', fileList) if m: path = m.group(1) else: log.msg( 'CVSMaildirSource can\'t get path from file list. Ignoring mail') return None fileList = fileList[len(path):].strip() singleFileRE = re.compile( r'(.+?),(NONE|(?:\d+\.(?:\d+\.\d+\.)*\d+)),(NONE|(?:\d+\.(?:\d+\.\d+\.)*\d+))(?: |$)') # noqa pylint: disable=line-too-long elif cvsmode == '1.12': singleFileRE = re.compile( r'(.+?) (NONE|(?:\d+\.(?:\d+\.\d+\.)*\d+)) (NONE|(?:\d+\.(?:\d+\.\d+\.)*\d+))(?: |$)') # noqa pylint: disable=line-too-long if path is None: raise ValueError( 'CVSMaildirSource cvs 1.12 require path. Check cvs loginfo config') else: raise ValueError('Expected cvsmode 1.11 or 1.12. got: {}'.format(cvsmode)) log.msg("CVSMaildirSource processing filelist: {}".format(fileList)) while(fileList): m = singleFileRE.match(fileList) if m: curFile = path + '/' + m.group(1) files.append(curFile) fileList = fileList[m.end():] else: log.msg('CVSMaildirSource no files matched regex. Ignoring') return None # bail - we couldn't parse the files that changed # Now get comments while lines: line = lines.pop(0) comments += line comments = comments.rstrip() + "\n" if comments == '\n': comments = None return ('cvs', dict(author=author, committer=None, files=files, comments=comments, isdir=isdir, when=when, branch=branch, revision=rev, category=category, repository=cvsroot, project=project, properties=self.properties))
[ "def", "parse", "(", "self", ",", "m", ",", "prefix", "=", "None", ")", ":", "# The mail is sent from the person doing the checkin. Assume that the", "# local username is enough to identify them (this assumes a one-server", "# cvs-over-rsh environment rather than the server-dirs-shared-over-NFS", "# model)", "name", ",", "addr", "=", "parseaddr", "(", "m", "[", "\"from\"", "]", ")", "if", "not", "addr", ":", "# no From means this message isn't from buildbot-cvs-mail", "return", "None", "at", "=", "addr", ".", "find", "(", "\"@\"", ")", "if", "at", "==", "-", "1", ":", "author", "=", "addr", "# might still be useful", "else", ":", "author", "=", "addr", "[", ":", "at", "]", "author", "=", "util", ".", "bytes2unicode", "(", "author", ",", "encoding", "=", "\"ascii\"", ")", "# CVS accepts RFC822 dates. buildbot-cvs-mail adds the date as", "# part of the mail header, so use that.", "# This assumes cvs is being access via ssh or pserver, so the time", "# will be the CVS server's time.", "# calculate a \"revision\" based on that timestamp, or the current time", "# if we're unable to parse the date.", "log", ".", "msg", "(", "'Processing CVS mail'", ")", "dateTuple", "=", "parsedate_tz", "(", "m", "[", "\"date\"", "]", ")", "if", "dateTuple", "is", "None", ":", "when", "=", "util", ".", "now", "(", ")", "else", ":", "when", "=", "mktime_tz", "(", "dateTuple", ")", "theTime", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "float", "(", "when", ")", ")", "rev", "=", "theTime", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", "catRE", "=", "re", ".", "compile", "(", "r'^Category:\\s*(\\S.*)'", ")", "cvsRE", "=", "re", ".", "compile", "(", "r'^CVSROOT:\\s*(\\S.*)'", ")", "cvsmodeRE", "=", "re", ".", "compile", "(", "r'^Cvsmode:\\s*(\\S.*)'", ")", "filesRE", "=", "re", ".", "compile", "(", "r'^Files:\\s*(\\S.*)'", ")", "modRE", "=", "re", ".", "compile", "(", "r'^Module:\\s*(\\S.*)'", ")", "pathRE", "=", "re", ".", "compile", "(", "r'^Path:\\s*(\\S.*)'", ")", "projRE", "=", "re", ".", "compile", "(", "r'^Project:\\s*(\\S.*)'", ")", "singleFileRE", "=", "re", ".", "compile", "(", "r'(.*) (NONE|\\d(\\.|\\d)+) (NONE|\\d(\\.|\\d)+)'", ")", "tagRE", "=", "re", ".", "compile", "(", "r'^\\s+Tag:\\s*(\\S.*)'", ")", "updateRE", "=", "re", ".", "compile", "(", "r'^Update of:\\s*(\\S.*)'", ")", "comments", "=", "\"\"", "branch", "=", "None", "cvsroot", "=", "None", "fileList", "=", "None", "files", "=", "[", "]", "isdir", "=", "0", "path", "=", "None", "project", "=", "None", "lines", "=", "list", "(", "body_line_iterator", "(", "m", ")", ")", "while", "lines", ":", "line", "=", "lines", ".", "pop", "(", "0", ")", "m", "=", "catRE", ".", "match", "(", "line", ")", "if", "m", ":", "category", "=", "m", ".", "group", "(", "1", ")", "continue", "m", "=", "cvsRE", ".", "match", "(", "line", ")", "if", "m", ":", "cvsroot", "=", "m", ".", "group", "(", "1", ")", "continue", "m", "=", "cvsmodeRE", ".", "match", "(", "line", ")", "if", "m", ":", "cvsmode", "=", "m", ".", "group", "(", "1", ")", "continue", "m", "=", "filesRE", ".", "match", "(", "line", ")", "if", "m", ":", "fileList", "=", "m", ".", "group", "(", "1", ")", "continue", "m", "=", "modRE", ".", "match", "(", "line", ")", "if", "m", ":", "# We don't actually use this", "# module = m.group(1)", "continue", "m", "=", "pathRE", ".", "match", "(", "line", ")", "if", "m", ":", "path", "=", "m", ".", "group", "(", "1", ")", "continue", "m", "=", "projRE", ".", "match", "(", "line", ")", "if", "m", ":", "project", "=", "m", ".", "group", "(", "1", ")", "continue", "m", "=", "tagRE", ".", "match", "(", "line", ")", "if", "m", ":", "branch", "=", "m", ".", "group", "(", "1", ")", "continue", "m", "=", "updateRE", ".", "match", "(", "line", ")", "if", "m", ":", "# We don't actually use this", "# updateof = m.group(1)", "continue", "if", "line", "==", "\"Log Message:\\n\"", ":", "break", "# CVS 1.11 lists files as:", "# repo/path file,old-version,new-version file2,old-version,new-version", "# Version 1.12 lists files as:", "# file1 old-version new-version file2 old-version new-version", "#", "# files consists of tuples of 'file-name old-version new-version'", "# The versions are either dotted-decimal version numbers, ie 1.1", "# or NONE. New files are of the form 'NONE NUMBER', while removed", "# files are 'NUMBER NONE'. 'NONE' is a literal string", "# Parsing this instead of files list in 'Added File:' etc", "# makes it possible to handle files with embedded spaces, though", "# it could fail if the filename was 'bad 1.1 1.2'", "# For cvs version 1.11, we expect", "# my_module new_file.c,NONE,1.1", "# my_module removed.txt,1.2,NONE", "# my_module modified_file.c,1.1,1.2", "# While cvs version 1.12 gives us", "# new_file.c NONE 1.1", "# removed.txt 1.2 NONE", "# modified_file.c 1.1,1.2", "if", "fileList", "is", "None", ":", "log", ".", "msg", "(", "'CVSMaildirSource Mail with no files. Ignoring'", ")", "return", "None", "# We don't have any files. Email not from CVS", "if", "cvsmode", "==", "'1.11'", ":", "# Please, no repo paths with spaces!", "m", "=", "re", ".", "search", "(", "'([^ ]*) '", ",", "fileList", ")", "if", "m", ":", "path", "=", "m", ".", "group", "(", "1", ")", "else", ":", "log", ".", "msg", "(", "'CVSMaildirSource can\\'t get path from file list. Ignoring mail'", ")", "return", "None", "fileList", "=", "fileList", "[", "len", "(", "path", ")", ":", "]", ".", "strip", "(", ")", "singleFileRE", "=", "re", ".", "compile", "(", "r'(.+?),(NONE|(?:\\d+\\.(?:\\d+\\.\\d+\\.)*\\d+)),(NONE|(?:\\d+\\.(?:\\d+\\.\\d+\\.)*\\d+))(?: |$)'", ")", "# noqa pylint: disable=line-too-long", "elif", "cvsmode", "==", "'1.12'", ":", "singleFileRE", "=", "re", ".", "compile", "(", "r'(.+?) (NONE|(?:\\d+\\.(?:\\d+\\.\\d+\\.)*\\d+)) (NONE|(?:\\d+\\.(?:\\d+\\.\\d+\\.)*\\d+))(?: |$)'", ")", "# noqa pylint: disable=line-too-long", "if", "path", "is", "None", ":", "raise", "ValueError", "(", "'CVSMaildirSource cvs 1.12 require path. Check cvs loginfo config'", ")", "else", ":", "raise", "ValueError", "(", "'Expected cvsmode 1.11 or 1.12. got: {}'", ".", "format", "(", "cvsmode", ")", ")", "log", ".", "msg", "(", "\"CVSMaildirSource processing filelist: {}\"", ".", "format", "(", "fileList", ")", ")", "while", "(", "fileList", ")", ":", "m", "=", "singleFileRE", ".", "match", "(", "fileList", ")", "if", "m", ":", "curFile", "=", "path", "+", "'/'", "+", "m", ".", "group", "(", "1", ")", "files", ".", "append", "(", "curFile", ")", "fileList", "=", "fileList", "[", "m", ".", "end", "(", ")", ":", "]", "else", ":", "log", ".", "msg", "(", "'CVSMaildirSource no files matched regex. Ignoring'", ")", "return", "None", "# bail - we couldn't parse the files that changed", "# Now get comments", "while", "lines", ":", "line", "=", "lines", ".", "pop", "(", "0", ")", "comments", "+=", "line", "comments", "=", "comments", ".", "rstrip", "(", ")", "+", "\"\\n\"", "if", "comments", "==", "'\\n'", ":", "comments", "=", "None", "return", "(", "'cvs'", ",", "dict", "(", "author", "=", "author", ",", "committer", "=", "None", ",", "files", "=", "files", ",", "comments", "=", "comments", ",", "isdir", "=", "isdir", ",", "when", "=", "when", ",", "branch", "=", "branch", ",", "revision", "=", "rev", ",", "category", "=", "category", ",", "repository", "=", "cvsroot", ",", "project", "=", "project", ",", "properties", "=", "self", ".", "properties", ")", ")" ]
https://github.com/buildbot/buildbot/blob/b9c558217c72e4c2463eedc7ec6d56736f7b01a8/master/buildbot/changes/mail.py#L87-L253
awslabs/aws-lambda-powertools-python
0c6ac0fe183476140ee1df55fe9fa1cc20925577
aws_lambda_powertools/utilities/data_classes/api_gateway_proxy_event.py
python
APIGatewayProxyEventV2.http_method
(self)
return self.request_context.http.method
The HTTP method used. Valid values include: DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT.
The HTTP method used. Valid values include: DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT.
[ "The", "HTTP", "method", "used", ".", "Valid", "values", "include", ":", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "and", "PUT", "." ]
def http_method(self) -> str: """The HTTP method used. Valid values include: DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT.""" return self.request_context.http.method
[ "def", "http_method", "(", "self", ")", "->", "str", ":", "return", "self", ".", "request_context", ".", "http", ".", "method" ]
https://github.com/awslabs/aws-lambda-powertools-python/blob/0c6ac0fe183476140ee1df55fe9fa1cc20925577/aws_lambda_powertools/utilities/data_classes/api_gateway_proxy_event.py#L245-L247
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/api/resources/v0_4.py
python
SingleSignOnResource.get_detail
(self, bundle, **kwargs)
return HttpResponseForbidden()
[]
def get_detail(self, bundle, **kwargs): return HttpResponseForbidden()
[ "def", "get_detail", "(", "self", ",", "bundle", ",", "*", "*", "kwargs", ")", ":", "return", "HttpResponseForbidden", "(", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/api/resources/v0_4.py#L361-L362
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/codeintel2/oop/driver.py
python
CoreHandler.do_set_environment
(self, request, driver)
[]
def do_set_environment(self, request, driver): try: env = request["env"] except KeyError: pass else: driver.env.override_env(env) try: prefs = request["prefs"] except KeyError: pass else: driver.env.override_prefs(prefs) driver.send()
[ "def", "do_set_environment", "(", "self", ",", "request", ",", "driver", ")", ":", "try", ":", "env", "=", "request", "[", "\"env\"", "]", "except", "KeyError", ":", "pass", "else", ":", "driver", ".", "env", ".", "override_env", "(", "env", ")", "try", ":", "prefs", "=", "request", "[", "\"prefs\"", "]", "except", "KeyError", ":", "pass", "else", ":", "driver", ".", "env", ".", "override_prefs", "(", "prefs", ")", "driver", ".", "send", "(", ")" ]
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/codeintel2/oop/driver.py#L774-L787
ros/ros_comm
52b0556dadf3ec0c0bc72df4fc202153a53b539e
tools/roslaunch/src/roslaunch/parent.py
python
ROSLaunchParent.spin_once
(self)
Run the parent roslaunch event loop once
Run the parent roslaunch event loop once
[ "Run", "the", "parent", "roslaunch", "event", "loop", "once" ]
def spin_once(self): """ Run the parent roslaunch event loop once """ if self.runner: self.runner.spin_once()
[ "def", "spin_once", "(", "self", ")", ":", "if", "self", ".", "runner", ":", "self", ".", "runner", ".", "spin_once", "(", ")" ]
https://github.com/ros/ros_comm/blob/52b0556dadf3ec0c0bc72df4fc202153a53b539e/tools/roslaunch/src/roslaunch/parent.py#L330-L335
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/api/taskqueue/taskqueue.py
python
QueueStatistics.__init__
(self, queue, tasks, oldest_eta_usec=None, executed_last_minute=None, in_flight=None, enforced_rate=None)
Constructor. Args: queue: The Queue instance this QueueStatistics is for. tasks: The number of tasks left. oldest_eta_usec: The eta of the oldest non-completed task for the queue; None if unknown. executed_last_minute: The number of tasks executed in the last minute. in_flight: The number of tasks that are currently executing. enforced_rate: The current enforced rate. In tasks/second.
Constructor.
[ "Constructor", "." ]
def __init__(self, queue, tasks, oldest_eta_usec=None, executed_last_minute=None, in_flight=None, enforced_rate=None): """Constructor. Args: queue: The Queue instance this QueueStatistics is for. tasks: The number of tasks left. oldest_eta_usec: The eta of the oldest non-completed task for the queue; None if unknown. executed_last_minute: The number of tasks executed in the last minute. in_flight: The number of tasks that are currently executing. enforced_rate: The current enforced rate. In tasks/second. """ self.queue = queue self.tasks = tasks self.oldest_eta_usec = oldest_eta_usec self.executed_last_minute = executed_last_minute self.in_flight = in_flight self.enforced_rate = enforced_rate
[ "def", "__init__", "(", "self", ",", "queue", ",", "tasks", ",", "oldest_eta_usec", "=", "None", ",", "executed_last_minute", "=", "None", ",", "in_flight", "=", "None", ",", "enforced_rate", "=", "None", ")", ":", "self", ".", "queue", "=", "queue", "self", ".", "tasks", "=", "tasks", "self", ".", "oldest_eta_usec", "=", "oldest_eta_usec", "self", ".", "executed_last_minute", "=", "executed_last_minute", "self", ".", "in_flight", "=", "in_flight", "self", ".", "enforced_rate", "=", "enforced_rate" ]
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/api/taskqueue/taskqueue.py#L1194-L1217
tcgoetz/GarminDB
55796eb621df9f6ecd92f16b3a53393d23c0b4dc
garmindb/garmin_json_data.py
python
GarminJsonSummaryData._process_hiking
(self, sub_sport, activity_id, activity_summary)
[]
def _process_hiking(self, sub_sport, activity_id, activity_summary): root_logger.debug("process_hiking for %s", activity_id) self._process_steps_activity(activity_id, activity_summary)
[ "def", "_process_hiking", "(", "self", ",", "sub_sport", ",", "activity_id", ",", "activity_summary", ")", ":", "root_logger", ".", "debug", "(", "\"process_hiking for %s\"", ",", "activity_id", ")", "self", ".", "_process_steps_activity", "(", "activity_id", ",", "activity_summary", ")" ]
https://github.com/tcgoetz/GarminDB/blob/55796eb621df9f6ecd92f16b3a53393d23c0b4dc/garmindb/garmin_json_data.py#L152-L154
yaohungt/Multimodal-Transformer
a670936824ee722c8494fd98d204977a1d663c7a
modules/transformer.py
python
TransformerEncoder.forward
(self, x_in, x_in_k = None, x_in_v = None)
return x
Args: x_in (FloatTensor): embedded input of shape `(src_len, batch, embed_dim)` x_in_k (FloatTensor): embedded input of shape `(src_len, batch, embed_dim)` x_in_v (FloatTensor): embedded input of shape `(src_len, batch, embed_dim)` Returns: dict: - **encoder_out** (Tensor): the last encoder layer's output of shape `(src_len, batch, embed_dim)` - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch, src_len)`
Args: x_in (FloatTensor): embedded input of shape `(src_len, batch, embed_dim)` x_in_k (FloatTensor): embedded input of shape `(src_len, batch, embed_dim)` x_in_v (FloatTensor): embedded input of shape `(src_len, batch, embed_dim)` Returns: dict: - **encoder_out** (Tensor): the last encoder layer's output of shape `(src_len, batch, embed_dim)` - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch, src_len)`
[ "Args", ":", "x_in", "(", "FloatTensor", ")", ":", "embedded", "input", "of", "shape", "(", "src_len", "batch", "embed_dim", ")", "x_in_k", "(", "FloatTensor", ")", ":", "embedded", "input", "of", "shape", "(", "src_len", "batch", "embed_dim", ")", "x_in_v", "(", "FloatTensor", ")", ":", "embedded", "input", "of", "shape", "(", "src_len", "batch", "embed_dim", ")", "Returns", ":", "dict", ":", "-", "**", "encoder_out", "**", "(", "Tensor", ")", ":", "the", "last", "encoder", "layer", "s", "output", "of", "shape", "(", "src_len", "batch", "embed_dim", ")", "-", "**", "encoder_padding_mask", "**", "(", "ByteTensor", ")", ":", "the", "positions", "of", "padding", "elements", "of", "shape", "(", "batch", "src_len", ")" ]
def forward(self, x_in, x_in_k = None, x_in_v = None): """ Args: x_in (FloatTensor): embedded input of shape `(src_len, batch, embed_dim)` x_in_k (FloatTensor): embedded input of shape `(src_len, batch, embed_dim)` x_in_v (FloatTensor): embedded input of shape `(src_len, batch, embed_dim)` Returns: dict: - **encoder_out** (Tensor): the last encoder layer's output of shape `(src_len, batch, embed_dim)` - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch, src_len)` """ # embed tokens and positions x = self.embed_scale * x_in if self.embed_positions is not None: x += self.embed_positions(x_in.transpose(0, 1)[:, :, 0]).transpose(0, 1) # Add positional embedding x = F.dropout(x, p=self.dropout, training=self.training) if x_in_k is not None and x_in_v is not None: # embed tokens and positions x_k = self.embed_scale * x_in_k x_v = self.embed_scale * x_in_v if self.embed_positions is not None: x_k += self.embed_positions(x_in_k.transpose(0, 1)[:, :, 0]).transpose(0, 1) # Add positional embedding x_v += self.embed_positions(x_in_v.transpose(0, 1)[:, :, 0]).transpose(0, 1) # Add positional embedding x_k = F.dropout(x_k, p=self.dropout, training=self.training) x_v = F.dropout(x_v, p=self.dropout, training=self.training) # encoder layers intermediates = [x] for layer in self.layers: if x_in_k is not None and x_in_v is not None: x = layer(x, x_k, x_v) else: x = layer(x) intermediates.append(x) if self.normalize: x = self.layer_norm(x) return x
[ "def", "forward", "(", "self", ",", "x_in", ",", "x_in_k", "=", "None", ",", "x_in_v", "=", "None", ")", ":", "# embed tokens and positions", "x", "=", "self", ".", "embed_scale", "*", "x_in", "if", "self", ".", "embed_positions", "is", "not", "None", ":", "x", "+=", "self", ".", "embed_positions", "(", "x_in", ".", "transpose", "(", "0", ",", "1", ")", "[", ":", ",", ":", ",", "0", "]", ")", ".", "transpose", "(", "0", ",", "1", ")", "# Add positional embedding", "x", "=", "F", ".", "dropout", "(", "x", ",", "p", "=", "self", ".", "dropout", ",", "training", "=", "self", ".", "training", ")", "if", "x_in_k", "is", "not", "None", "and", "x_in_v", "is", "not", "None", ":", "# embed tokens and positions ", "x_k", "=", "self", ".", "embed_scale", "*", "x_in_k", "x_v", "=", "self", ".", "embed_scale", "*", "x_in_v", "if", "self", ".", "embed_positions", "is", "not", "None", ":", "x_k", "+=", "self", ".", "embed_positions", "(", "x_in_k", ".", "transpose", "(", "0", ",", "1", ")", "[", ":", ",", ":", ",", "0", "]", ")", ".", "transpose", "(", "0", ",", "1", ")", "# Add positional embedding", "x_v", "+=", "self", ".", "embed_positions", "(", "x_in_v", ".", "transpose", "(", "0", ",", "1", ")", "[", ":", ",", ":", ",", "0", "]", ")", ".", "transpose", "(", "0", ",", "1", ")", "# Add positional embedding", "x_k", "=", "F", ".", "dropout", "(", "x_k", ",", "p", "=", "self", ".", "dropout", ",", "training", "=", "self", ".", "training", ")", "x_v", "=", "F", ".", "dropout", "(", "x_v", ",", "p", "=", "self", ".", "dropout", ",", "training", "=", "self", ".", "training", ")", "# encoder layers", "intermediates", "=", "[", "x", "]", "for", "layer", "in", "self", ".", "layers", ":", "if", "x_in_k", "is", "not", "None", "and", "x_in_v", "is", "not", "None", ":", "x", "=", "layer", "(", "x", ",", "x_k", ",", "x_v", ")", "else", ":", "x", "=", "layer", "(", "x", ")", "intermediates", ".", "append", "(", "x", ")", "if", "self", ".", "normalize", ":", "x", "=", "self", ".", "layer_norm", "(", "x", ")", "return", "x" ]
https://github.com/yaohungt/Multimodal-Transformer/blob/a670936824ee722c8494fd98d204977a1d663c7a/modules/transformer.py#L49-L90
atomistic-machine-learning/schnetpack
dacf6076d43509dfd8b6694a846ac8453ae39b5e
src/schnetpack/md/parsers/orca_parser.py
python
OrcaPropertyParser.parse_line
(self, line)
Parses a line in the output file and updates the main container. Args: line (str): line of Orca output file
Parses a line in the output file and updates the main container.
[ "Parses", "a", "line", "in", "the", "output", "file", "and", "updates", "the", "main", "container", "." ]
def parse_line(self, line): """ Parses a line in the output file and updates the main container. Args: line (str): line of Orca output file """ line = line.strip() if line.startswith("---------") or len(line) == 0: pass # if line.startswith("*********") or len(line) == 0: # pass elif line.startswith(self.start): # Avoid double reading and restart for multiple files and repeated instances of data. self.parsed = [] self.read = True # For single line output if self.stop is None: self.parsed.append(line) self.read = False elif self.read: # Check for stops if isinstance(self.stop, list): for stop in self.stop: if self.read and line.startswith(stop): self.read = False if self.read: self.parsed.append(line) else: if line.startswith(self.stop): self.read = False else: self.parsed.append(line)
[ "def", "parse_line", "(", "self", ",", "line", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "\"---------\"", ")", "or", "len", "(", "line", ")", "==", "0", ":", "pass", "# if line.startswith(\"*********\") or len(line) == 0:", "# pass", "elif", "line", ".", "startswith", "(", "self", ".", "start", ")", ":", "# Avoid double reading and restart for multiple files and repeated instances of data.", "self", ".", "parsed", "=", "[", "]", "self", ".", "read", "=", "True", "# For single line output", "if", "self", ".", "stop", "is", "None", ":", "self", ".", "parsed", ".", "append", "(", "line", ")", "self", ".", "read", "=", "False", "elif", "self", ".", "read", ":", "# Check for stops", "if", "isinstance", "(", "self", ".", "stop", ",", "list", ")", ":", "for", "stop", "in", "self", ".", "stop", ":", "if", "self", ".", "read", "and", "line", ".", "startswith", "(", "stop", ")", ":", "self", ".", "read", "=", "False", "if", "self", ".", "read", ":", "self", ".", "parsed", ".", "append", "(", "line", ")", "else", ":", "if", "line", ".", "startswith", "(", "self", ".", "stop", ")", ":", "self", ".", "read", "=", "False", "else", ":", "self", ".", "parsed", ".", "append", "(", "line", ")" ]
https://github.com/atomistic-machine-learning/schnetpack/blob/dacf6076d43509dfd8b6694a846ac8453ae39b5e/src/schnetpack/md/parsers/orca_parser.py#L555-L587
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/yunjing/v20180228/models.py
python
OpenProVersionPrepaidRequest.__init__
(self)
r""" :param ChargePrepaid: 购买相关参数。 :type ChargePrepaid: :class:`tencentcloud.yunjing.v20180228.models.ChargePrepaid` :param Machines: 需要开通专业版主机信息数组。 :type Machines: list of ProVersionMachine
r""" :param ChargePrepaid: 购买相关参数。 :type ChargePrepaid: :class:`tencentcloud.yunjing.v20180228.models.ChargePrepaid` :param Machines: 需要开通专业版主机信息数组。 :type Machines: list of ProVersionMachine
[ "r", ":", "param", "ChargePrepaid", ":", "购买相关参数。", ":", "type", "ChargePrepaid", ":", ":", "class", ":", "tencentcloud", ".", "yunjing", ".", "v20180228", ".", "models", ".", "ChargePrepaid", ":", "param", "Machines", ":", "需要开通专业版主机信息数组。", ":", "type", "Machines", ":", "list", "of", "ProVersionMachine" ]
def __init__(self): r""" :param ChargePrepaid: 购买相关参数。 :type ChargePrepaid: :class:`tencentcloud.yunjing.v20180228.models.ChargePrepaid` :param Machines: 需要开通专业版主机信息数组。 :type Machines: list of ProVersionMachine """ self.ChargePrepaid = None self.Machines = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ChargePrepaid", "=", "None", "self", ".", "Machines", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/yunjing/v20180228/models.py#L6286-L6294
deanishe/zothero
5b057ef080ee730d82d5dd15e064d2a4730c2b11
src/lib/workflow/web.py
python
post
(url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=60, allow_redirects=False, stream=False)
return request('POST', url, params, data, headers, cookies, files, auth, timeout, allow_redirects, stream)
Initiate a POST request. Arguments as for :func:`request`. :returns: :class:`Response` instance
Initiate a POST request. Arguments as for :func:`request`.
[ "Initiate", "a", "POST", "request", ".", "Arguments", "as", "for", ":", "func", ":", "request", "." ]
def post(url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=60, allow_redirects=False, stream=False): """Initiate a POST request. Arguments as for :func:`request`. :returns: :class:`Response` instance """ return request('POST', url, params, data, headers, cookies, files, auth, timeout, allow_redirects, stream)
[ "def", "post", "(", "url", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "files", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "60", ",", "allow_redirects", "=", "False", ",", "stream", "=", "False", ")", ":", "return", "request", "(", "'POST'", ",", "url", ",", "params", ",", "data", ",", "headers", ",", "cookies", ",", "files", ",", "auth", ",", "timeout", ",", "allow_redirects", ",", "stream", ")" ]
https://github.com/deanishe/zothero/blob/5b057ef080ee730d82d5dd15e064d2a4730c2b11/src/lib/workflow/web.py#L594-L602
paulwinex/pw_MultiScriptEditor
e447e99f87cb07e238baf693b7e124e50efdbc51
multi_script_editor/managers/nuke/main.py
python
localisationEnabled
(knob)
return True
localisationEnabled(knob) -> bool rief Checks if localisation is enabled on a given Read_File_Knob. @param knob: The Read_File_Knob to check. @return: true if enabled, false otherwise
localisationEnabled(knob) -> bool
[ "localisationEnabled", "(", "knob", ")", "-", ">", "bool" ]
def localisationEnabled(knob): """localisationEnabled(knob) -> bool rief Checks if localisation is enabled on a given Read_File_Knob. @param knob: The Read_File_Knob to check. @return: true if enabled, false otherwise""" return True
[ "def", "localisationEnabled", "(", "knob", ")", ":", "return", "True" ]
https://github.com/paulwinex/pw_MultiScriptEditor/blob/e447e99f87cb07e238baf693b7e124e50efdbc51/multi_script_editor/managers/nuke/main.py#L5507-L5515
yuanxiaosc/BERT-for-Sequence-Labeling-and-Text-Classification
2a6d2f9c732a362458030643e131540e7d1cdcca
bert/run_pretraining.py
python
input_fn_builder
(input_files, max_seq_length, max_predictions_per_seq, is_training, num_cpu_threads=4)
return input_fn
Creates an `input_fn` closure to be passed to TPUEstimator.
Creates an `input_fn` closure to be passed to TPUEstimator.
[ "Creates", "an", "input_fn", "closure", "to", "be", "passed", "to", "TPUEstimator", "." ]
def input_fn_builder(input_files, max_seq_length, max_predictions_per_seq, is_training, num_cpu_threads=4): """Creates an `input_fn` closure to be passed to TPUEstimator.""" def input_fn(params): """The actual input function.""" batch_size = params["batch_size"] name_to_features = { "input_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "input_mask": tf.FixedLenFeature([max_seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "masked_lm_positions": tf.FixedLenFeature([max_predictions_per_seq], tf.int64), "masked_lm_ids": tf.FixedLenFeature([max_predictions_per_seq], tf.int64), "masked_lm_weights": tf.FixedLenFeature([max_predictions_per_seq], tf.float32), "next_sentence_labels": tf.FixedLenFeature([1], tf.int64), } # For training, we want a lot of parallel reading and shuffling. # For eval, we want no shuffling and parallel reading doesn't matter. if is_training: d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files)) d = d.repeat() d = d.shuffle(buffer_size=len(input_files)) # `cycle_length` is the number of parallel files that get read. cycle_length = min(num_cpu_threads, len(input_files)) # `sloppy` mode means that the interleaving is not exact. This adds # even more randomness to the training pipeline. d = d.apply( tf.contrib.data.parallel_interleave( tf.data.TFRecordDataset, sloppy=is_training, cycle_length=cycle_length)) d = d.shuffle(buffer_size=100) else: d = tf.data.TFRecordDataset(input_files) # Since we evaluate for a fixed number of steps we don't want to encounter # out-of-range exceptions. d = d.repeat() # We must `drop_remainder` on training because the TPU requires fixed # size dimensions. For eval, we assume we are evaluating on the CPU or GPU # and we *don't* want to drop the remainder, otherwise we wont cover # every sample. d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, num_parallel_batches=num_cpu_threads, drop_remainder=True)) return d return input_fn
[ "def", "input_fn_builder", "(", "input_files", ",", "max_seq_length", ",", "max_predictions_per_seq", ",", "is_training", ",", "num_cpu_threads", "=", "4", ")", ":", "def", "input_fn", "(", "params", ")", ":", "\"\"\"The actual input function.\"\"\"", "batch_size", "=", "params", "[", "\"batch_size\"", "]", "name_to_features", "=", "{", "\"input_ids\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "max_seq_length", "]", ",", "tf", ".", "int64", ")", ",", "\"input_mask\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "max_seq_length", "]", ",", "tf", ".", "int64", ")", ",", "\"segment_ids\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "max_seq_length", "]", ",", "tf", ".", "int64", ")", ",", "\"masked_lm_positions\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "max_predictions_per_seq", "]", ",", "tf", ".", "int64", ")", ",", "\"masked_lm_ids\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "max_predictions_per_seq", "]", ",", "tf", ".", "int64", ")", ",", "\"masked_lm_weights\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "max_predictions_per_seq", "]", ",", "tf", ".", "float32", ")", ",", "\"next_sentence_labels\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "1", "]", ",", "tf", ".", "int64", ")", ",", "}", "# For training, we want a lot of parallel reading and shuffling.", "# For eval, we want no shuffling and parallel reading doesn't matter.", "if", "is_training", ":", "d", "=", "tf", ".", "data", ".", "Dataset", ".", "from_tensor_slices", "(", "tf", ".", "constant", "(", "input_files", ")", ")", "d", "=", "d", ".", "repeat", "(", ")", "d", "=", "d", ".", "shuffle", "(", "buffer_size", "=", "len", "(", "input_files", ")", ")", "# `cycle_length` is the number of parallel files that get read.", "cycle_length", "=", "min", "(", "num_cpu_threads", ",", "len", "(", "input_files", ")", ")", "# `sloppy` mode means that the interleaving is not exact. This adds", "# even more randomness to the training pipeline.", "d", "=", "d", ".", "apply", "(", "tf", ".", "contrib", ".", "data", ".", "parallel_interleave", "(", "tf", ".", "data", ".", "TFRecordDataset", ",", "sloppy", "=", "is_training", ",", "cycle_length", "=", "cycle_length", ")", ")", "d", "=", "d", ".", "shuffle", "(", "buffer_size", "=", "100", ")", "else", ":", "d", "=", "tf", ".", "data", ".", "TFRecordDataset", "(", "input_files", ")", "# Since we evaluate for a fixed number of steps we don't want to encounter", "# out-of-range exceptions.", "d", "=", "d", ".", "repeat", "(", ")", "# We must `drop_remainder` on training because the TPU requires fixed", "# size dimensions. For eval, we assume we are evaluating on the CPU or GPU", "# and we *don't* want to drop the remainder, otherwise we wont cover", "# every sample.", "d", "=", "d", ".", "apply", "(", "tf", ".", "contrib", ".", "data", ".", "map_and_batch", "(", "lambda", "record", ":", "_decode_record", "(", "record", ",", "name_to_features", ")", ",", "batch_size", "=", "batch_size", ",", "num_parallel_batches", "=", "num_cpu_threads", ",", "drop_remainder", "=", "True", ")", ")", "return", "d", "return", "input_fn" ]
https://github.com/yuanxiaosc/BERT-for-Sequence-Labeling-and-Text-Classification/blob/2a6d2f9c732a362458030643e131540e7d1cdcca/bert/run_pretraining.py#L324-L388
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/rlcompleter.py
python
Completer.attr_matches
(self, text)
return matches
Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluable in self.namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated.
Compute matches when text contains a dot.
[ "Compute", "matches", "when", "text", "contains", "a", "dot", "." ]
def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluable in self.namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ import re m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return [] expr, attr = m.group(1, 3) try: thisobject = eval(expr, self.namespace) except Exception: return [] # get the content of the object, except __builtins__ words = dir(thisobject) if "__builtins__" in words: words.remove("__builtins__") if hasattr(thisobject, '__class__'): words.append('__class__') words.extend(get_class_members(thisobject.__class__)) matches = [] n = len(attr) for word in words: if word[:n] == attr and hasattr(thisobject, word): val = getattr(thisobject, word) word = self._callable_postfix(val, "%s.%s" % (expr, word)) matches.append(word) return matches
[ "def", "attr_matches", "(", "self", ",", "text", ")", ":", "import", "re", "m", "=", "re", ".", "match", "(", "r\"(\\w+(\\.\\w+)*)\\.(\\w*)\"", ",", "text", ")", "if", "not", "m", ":", "return", "[", "]", "expr", ",", "attr", "=", "m", ".", "group", "(", "1", ",", "3", ")", "try", ":", "thisobject", "=", "eval", "(", "expr", ",", "self", ".", "namespace", ")", "except", "Exception", ":", "return", "[", "]", "# get the content of the object, except __builtins__", "words", "=", "dir", "(", "thisobject", ")", "if", "\"__builtins__\"", "in", "words", ":", "words", ".", "remove", "(", "\"__builtins__\"", ")", "if", "hasattr", "(", "thisobject", ",", "'__class__'", ")", ":", "words", ".", "append", "(", "'__class__'", ")", "words", ".", "extend", "(", "get_class_members", "(", "thisobject", ".", "__class__", ")", ")", "matches", "=", "[", "]", "n", "=", "len", "(", "attr", ")", "for", "word", "in", "words", ":", "if", "word", "[", ":", "n", "]", "==", "attr", "and", "hasattr", "(", "thisobject", ",", "word", ")", ":", "val", "=", "getattr", "(", "thisobject", ",", "word", ")", "word", "=", "self", ".", "_callable_postfix", "(", "val", ",", "\"%s.%s\"", "%", "(", "expr", ",", "word", ")", ")", "matches", ".", "append", "(", "word", ")", "return", "matches" ]
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/rlcompleter.py#L115-L152
django-denorm/django-denorm
57bd310ad2f97aebb51794f59c60f342ccacab33
denorm/dependencies.py
python
CallbackDependOnRelated.__init__
(self, othermodel, foreign_key=None, type=None, skip=None)
Attaches a dependency to a callable, indicating the return value depends on fields in an other model that is related to the model the callable belongs to either through a ForeignKey in either direction or a ManyToManyField. **Arguments:** othermodel (required) Either a model class or a string naming a model class. foreign_key The name of the ForeignKey or ManyToManyField that creates the relation between the two models. Only necessary if there is more than one relationship between the two models. type One of 'forward', 'backward', 'forward_m2m' or 'backward_m2m'. If there are relations in both directions specify which one to use. skip Use this to specify what fields change on every save(). These fields will not be checked and will not make a model dirty when they change, to prevent infinite loops.
Attaches a dependency to a callable, indicating the return value depends on fields in an other model that is related to the model the callable belongs to either through a ForeignKey in either direction or a ManyToManyField.
[ "Attaches", "a", "dependency", "to", "a", "callable", "indicating", "the", "return", "value", "depends", "on", "fields", "in", "an", "other", "model", "that", "is", "related", "to", "the", "model", "the", "callable", "belongs", "to", "either", "through", "a", "ForeignKey", "in", "either", "direction", "or", "a", "ManyToManyField", "." ]
def __init__(self, othermodel, foreign_key=None, type=None, skip=None): """ Attaches a dependency to a callable, indicating the return value depends on fields in an other model that is related to the model the callable belongs to either through a ForeignKey in either direction or a ManyToManyField. **Arguments:** othermodel (required) Either a model class or a string naming a model class. foreign_key The name of the ForeignKey or ManyToManyField that creates the relation between the two models. Only necessary if there is more than one relationship between the two models. type One of 'forward', 'backward', 'forward_m2m' or 'backward_m2m'. If there are relations in both directions specify which one to use. skip Use this to specify what fields change on every save(). These fields will not be checked and will not make a model dirty when they change, to prevent infinite loops. """ super(CallbackDependOnRelated, self).__init__(othermodel, foreign_key, type, skip)
[ "def", "__init__", "(", "self", ",", "othermodel", ",", "foreign_key", "=", "None", ",", "type", "=", "None", ",", "skip", "=", "None", ")", ":", "super", "(", "CallbackDependOnRelated", ",", "self", ")", ".", "__init__", "(", "othermodel", ",", "foreign_key", ",", "type", ",", "skip", ")" ]
https://github.com/django-denorm/django-denorm/blob/57bd310ad2f97aebb51794f59c60f342ccacab33/denorm/dependencies.py#L248-L272
lukalabs/cakechat
844507281b30d81b3fe3674895fe27826dba8438
cakechat/api/utils.py
python
parse_dataset_param
(params, param_name, required=True)
return dataset
[]
def parse_dataset_param(params, param_name, required=True): if not required and params.get(param_name) is None: return None dataset = params[param_name] if not _is_list_of_unicode_strings(dataset): raise ValueError('`{}` should be non-empty list of unicode strings'.format(param_name)) if not all(dataset): raise ValueError('`{}` should not contain empty strings'.format(param_name)) return dataset
[ "def", "parse_dataset_param", "(", "params", ",", "param_name", ",", "required", "=", "True", ")", ":", "if", "not", "required", "and", "params", ".", "get", "(", "param_name", ")", "is", "None", ":", "return", "None", "dataset", "=", "params", "[", "param_name", "]", "if", "not", "_is_list_of_unicode_strings", "(", "dataset", ")", ":", "raise", "ValueError", "(", "'`{}` should be non-empty list of unicode strings'", ".", "format", "(", "param_name", ")", ")", "if", "not", "all", "(", "dataset", ")", ":", "raise", "ValueError", "(", "'`{}` should not contain empty strings'", ".", "format", "(", "param_name", ")", ")", "return", "dataset" ]
https://github.com/lukalabs/cakechat/blob/844507281b30d81b3fe3674895fe27826dba8438/cakechat/api/utils.py#L13-L23
mypaint/mypaint
90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33
lib/brush.py
python
BrushInfo.load_defaults
(self)
Load default brush settings, dropping all current settings.
Load default brush settings, dropping all current settings.
[ "Load", "default", "brush", "settings", "dropping", "all", "current", "settings", "." ]
def load_defaults(self): """Load default brush settings, dropping all current settings.""" self.begin_atomic() self.settings = {} for s in brushsettings.settings: self.reset_setting(s.cname) self.end_atomic()
[ "def", "load_defaults", "(", "self", ")", ":", "self", ".", "begin_atomic", "(", ")", "self", ".", "settings", "=", "{", "}", "for", "s", "in", "brushsettings", ".", "settings", ":", "self", ".", "reset_setting", "(", "s", ".", "cname", ")", "self", ".", "end_atomic", "(", ")" ]
https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/lib/brush.py#L216-L222
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/distlib/metadata.py
python
LegacyMetadata.__getitem__
(self, name)
return self.get(name)
[]
def __getitem__(self, name): return self.get(name)
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "return", "self", ".", "get", "(", "name", ")" ]
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/distlib/metadata.py#L270-L271
SySS-Research/outis
ef9b720fa12e8e0748a826354f138eabc33747fe
syhelpers/dataqueue.py
python
DataQueue.length
(self)
return self.memorybio.pending
returns the length of the data in the queue :return: length of the data in the queue
returns the length of the data in the queue :return: length of the data in the queue
[ "returns", "the", "length", "of", "the", "data", "in", "the", "queue", ":", "return", ":", "length", "of", "the", "data", "in", "the", "queue" ]
def length(self): """ returns the length of the data in the queue :return: length of the data in the queue """ return self.memorybio.pending
[ "def", "length", "(", "self", ")", ":", "return", "self", ".", "memorybio", ".", "pending" ]
https://github.com/SySS-Research/outis/blob/ef9b720fa12e8e0748a826354f138eabc33747fe/syhelpers/dataqueue.py#L24-L30
urwid/urwid
e2423b5069f51d318ea1ac0f355a0efe5448f7eb
examples/tour.py
python
main
()
[]
def main(): text_header = (u"Welcome to the urwid tour! " u"UP / DOWN / PAGE UP / PAGE DOWN scroll. F8 exits.") text_intro = [('important', u"Text"), u" widgets are the most common in " u"any urwid program. This Text widget was created " u"without setting the wrap or align mode, so it " u"defaults to left alignment with wrapping on space " u"characters. ", ('important', u"Change the window width"), u" to see how the widgets on this page react. " u"This Text widget is wrapped with a ", ('important', u"Padding"), u" widget to keep it indented on the left and right."] text_right = (u"This Text widget is right aligned. Wrapped " u"words stay to the right as well. ") text_center = u"This one is center aligned." text_clip = (u"Text widgets may be clipped instead of wrapped.\n" u"Extra text is discarded instead of wrapped to the next line. " u"65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n" u"Newlines embedded in the string are still respected.") text_right_clip = (u"This is a right aligned and clipped Text widget.\n" u"<100 <-95 <-90 <-85 <-80 <-75 <-70 <-65 " u"Text will be cut off at the left of this widget.") text_center_clip = (u"Center aligned and clipped widgets will have " u"text cut off both sides.") text_ellipsis = (u"Text can be clipped using the ellipsis character (…)\n" u"Extra text is discarded and a … mark is shown." u"50-> 55-> 60-> 65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n" ) text_any = (u"The 'any' wrap mode will wrap on any character. This " u"mode will not collapse space characters at the end of the " u"line but it still honors embedded newline characters.\n" u"Like this one.") text_padding = (u"Padding widgets have many options. This " u"is a standard Text widget wrapped with a Padding widget " u"with the alignment set to relative 20% and with its width " u"fixed at 40.") text_divider = [u"The ", ('important', u"Divider"), u" widget repeats the same character across the whole line. " u"It can also add blank lines above and below."] text_edit = [u"The ", ('important', u"Edit"), u" widget is a simple text editing widget. It supports cursor " u"movement and tries to maintain the current column when focus " u"moves to another edit widget. It wraps and aligns the same " u"way as Text widgets." ] text_edit_cap1 = ('editcp', u"This is a caption. Edit here: ") text_edit_text1 = u"editable stuff" text_edit_cap2 = ('editcp', u"This one supports newlines: ") text_edit_text2 = (u"line one starts them all\n" u"== line 2 == with some more text to edit.. words.. whee..\n" u"LINE III, the line to end lines one and two, unless you " u"change something.") text_edit_cap3 = ('editcp', u"This one is clipped, try " u"editing past the edge: ") text_edit_text3 = u"add some text here -> -> -> ...." text_edit_alignments = u"Different Alignments:" text_edit_left = u"left aligned (default)" text_edit_center = u"center aligned" text_edit_right = u"right aligned" text_intedit = ('editcp', [('important', u"IntEdit"), u" allows only numbers: "]) text_edit_padding = ('editcp', u"Edit widget within a Padding widget ") text_columns1 = [('important', u"Columns"), u" are used to share horizontal screen space. " u"This one splits the space into two parts with " u"three characters between each column. The " u"contents of each column is a single widget."] text_columns2 = [u"When you need to put more than one " u"widget into a column you can use a ",('important', u"Pile"), u" to combine two or more widgets."] text_col_columns = u"Columns may be placed inside other columns." text_col_21 = u"Col 2.1" text_col_22 = u"Col 2.2" text_col_23 = u"Col 2.3" text_column_widths = (u"Columns may also have uneven relative " u"weights or fixed widths. Use a minimum width so that " u"columns don't become too small.") text_weight = u"Weight %d" text_fixed_9 = u"<Fixed 9>" # should be 9 columns wide text_fixed_14 = u"<--Fixed 14-->" # should be 14 columns wide text_edit_col_cap1 = ('editcp', u"Edit widget within Columns") text_edit_col_text1 = u"here's\nsome\ninfo" text_edit_col_cap2 = ('editcp', u"and within Pile ") text_edit_col_text2 = u"more" text_edit_col_cap3 = ('editcp', u"another ") text_edit_col_text3 = u"still more" text_gridflow = [u"A ",('important', u"GridFlow"), u" widget " u"may be used to display a list of flow widgets with equal " u"widths. Widgets that don't fit on the first line will " u"flow to the next. This is useful for small widgets that " u"you want to keep together such as ", ('important', u"Button"), u", ",('important', u"CheckBox"), u" and ", ('important', u"RadioButton"), u" widgets." ] text_button_list = [u"Yes", u"No", u"Perhaps", u"Certainly", u"Partially", u"Tuesdays Only", u"Help"] text_cb_list = [u"Wax", u"Wash", u"Buff", u"Clear Coat", u"Dry", u"Racing Stripe"] text_rb_list = [u"Morning", u"Afternoon", u"Evening", u"Weekend"] text_listbox = [u"All these widgets have been displayed " u"with the help of a ", ('important', u"ListBox"), u" widget. " u"ListBox widgets handle scrolling and changing focus. A ", ('important', u"Frame"), u" widget is used to keep the " u"instructions at the top of the screen."] def button_press(button): frame.footer = urwid.AttrWrap(urwid.Text( [u"Pressed: ", button.get_label()]), 'header') radio_button_group = [] blank = urwid.Divider() listbox_content = [ blank, urwid.Padding(urwid.Text(text_intro), left=2, right=2, min_width=20), blank, urwid.Text(text_right, align='right'), blank, urwid.Text(text_center, align='center'), blank, urwid.Text(text_clip, wrap='clip'), blank, urwid.Text(text_right_clip, align='right', wrap='clip'), blank, urwid.Text(text_center_clip, align='center', wrap='clip'), blank, urwid.Text(text_ellipsis, wrap='ellipsis'), blank, urwid.Text(text_any, wrap='any'), blank, urwid.Padding(urwid.Text(text_padding), ('relative', 20), 40), blank, urwid.AttrWrap(urwid.Divider("=", 1), 'bright'), urwid.Padding(urwid.Text(text_divider), left=2, right=2, min_width=20), urwid.AttrWrap(urwid.Divider("-", 0, 1), 'bright'), blank, urwid.Padding(urwid.Text(text_edit), left=2, right=2, min_width=20), blank, urwid.AttrWrap(urwid.Edit(text_edit_cap1, text_edit_text1), 'editbx', 'editfc'), blank, urwid.AttrWrap(urwid.Edit(text_edit_cap2, text_edit_text2, multiline=True ), 'editbx', 'editfc'), blank, urwid.AttrWrap(urwid.Edit(text_edit_cap3, text_edit_text3, wrap='clip' ), 'editbx', 'editfc'), blank, urwid.Text(text_edit_alignments), urwid.AttrWrap(urwid.Edit("", text_edit_left, align='left'), 'editbx', 'editfc' ), urwid.AttrWrap(urwid.Edit("", text_edit_center, align='center'), 'editbx', 'editfc' ), urwid.AttrWrap(urwid.Edit("", text_edit_right, align='right'), 'editbx', 'editfc' ), blank, urwid.AttrWrap(urwid.IntEdit(text_intedit, 123), 'editbx', 'editfc' ), blank, urwid.Padding(urwid.AttrWrap(urwid.Edit(text_edit_padding, ""), 'editbx','editfc' ), left=10, width=50), blank, blank, urwid.AttrWrap(urwid.Columns([ urwid.Divider("."), urwid.Divider(","), urwid.Divider("."), ]), 'bright'), blank, urwid.Columns([ urwid.Padding(urwid.Text(text_columns1), left=2, right=0, min_width=20), urwid.Pile([ urwid.Divider("~"), urwid.Text(text_columns2), urwid.Divider("_")]) ], 3), blank, blank, urwid.Columns([ urwid.Text(text_col_columns), urwid.Columns([ urwid.Text(text_col_21), urwid.Text(text_col_22), urwid.Text(text_col_23), ], 1), ], 2), blank, urwid.Padding(urwid.Text(text_column_widths), left=2, right=2, min_width=20), blank, urwid.Columns( [ urwid.AttrWrap(urwid.Text(text_weight % 1),'reverse'), ('weight', 2, urwid.Text(text_weight % 2)), ('weight', 3, urwid.AttrWrap(urwid.Text( text_weight % 3), 'reverse')), ('weight', 4, urwid.Text(text_weight % 4)), ('weight', 5, urwid.AttrWrap(urwid.Text( text_weight % 5), 'reverse')), ('weight', 6, urwid.Text(text_weight % 6)), ], 0, min_width=8), blank, urwid.Columns([ ('weight', 2, urwid.AttrWrap(urwid.Text( text_weight % 2), 'reverse')), ('fixed', 9, urwid.Text(text_fixed_9)), ('weight', 3, urwid.AttrWrap(urwid.Text( text_weight % 3), 'reverse')), ('fixed', 14, urwid.Text(text_fixed_14)), ], 0, min_width=8), blank, urwid.Columns([ urwid.AttrWrap(urwid.Edit(text_edit_col_cap1, text_edit_col_text1, multiline=True), 'editbx','editfc'), urwid.Pile([ urwid.AttrWrap(urwid.Edit( text_edit_col_cap2, text_edit_col_text2), 'editbx','editfc'), blank, urwid.AttrWrap(urwid.Edit( text_edit_col_cap3, text_edit_col_text3), 'editbx','editfc'), ]), ], 1), blank, urwid.AttrWrap(urwid.Columns([ urwid.Divider("'"), urwid.Divider('"'), urwid.Divider("~"), urwid.Divider('"'), urwid.Divider("'"), ]), 'bright'), blank, blank, urwid.Padding(urwid.Text(text_gridflow), left=2, right=2, min_width=20), blank, urwid.Padding(urwid.GridFlow( [urwid.AttrWrap(urwid.Button(txt, button_press), 'buttn','buttnf') for txt in text_button_list], 13, 3, 1, 'left'), left=4, right=3, min_width=13), blank, urwid.Padding(urwid.GridFlow( [urwid.AttrWrap(urwid.CheckBox(txt),'buttn','buttnf') for txt in text_cb_list], 10, 3, 1, 'left') , left=4, right=3, min_width=10), blank, urwid.Padding(urwid.GridFlow( [urwid.AttrWrap(urwid.RadioButton(radio_button_group, txt), 'buttn','buttnf') for txt in text_rb_list], 13, 3, 1, 'left') , left=4, right=3, min_width=13), blank, blank, urwid.Padding(urwid.Text(text_listbox), left=2, right=2, min_width=20), blank, blank, ] header = urwid.AttrWrap(urwid.Text(text_header), 'header') listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content)) frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header) palette = [ ('body','black','light gray', 'standout'), ('reverse','light gray','black'), ('header','white','dark red', 'bold'), ('important','dark blue','light gray',('standout','underline')), ('editfc','white', 'dark blue', 'bold'), ('editbx','light gray', 'dark blue'), ('editcp','black','light gray', 'standout'), ('bright','dark gray','light gray', ('bold','standout')), ('buttn','black','dark cyan'), ('buttnf','white','dark blue','bold'), ] # use appropriate Screen class if urwid.web_display.is_web_request(): screen = urwid.web_display.Screen() else: screen = urwid.raw_display.Screen() def unhandled(key): if key == 'f8': raise urwid.ExitMainLoop() urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled).run()
[ "def", "main", "(", ")", ":", "text_header", "=", "(", "u\"Welcome to the urwid tour! \"", "u\"UP / DOWN / PAGE UP / PAGE DOWN scroll. F8 exits.\"", ")", "text_intro", "=", "[", "(", "'important'", ",", "u\"Text\"", ")", ",", "u\" widgets are the most common in \"", "u\"any urwid program. This Text widget was created \"", "u\"without setting the wrap or align mode, so it \"", "u\"defaults to left alignment with wrapping on space \"", "u\"characters. \"", ",", "(", "'important'", ",", "u\"Change the window width\"", ")", ",", "u\" to see how the widgets on this page react. \"", "u\"This Text widget is wrapped with a \"", ",", "(", "'important'", ",", "u\"Padding\"", ")", ",", "u\" widget to keep it indented on the left and right.\"", "]", "text_right", "=", "(", "u\"This Text widget is right aligned. Wrapped \"", "u\"words stay to the right as well. \"", ")", "text_center", "=", "u\"This one is center aligned.\"", "text_clip", "=", "(", "u\"Text widgets may be clipped instead of wrapped.\\n\"", "u\"Extra text is discarded instead of wrapped to the next line. \"", "u\"65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\\n\"", "u\"Newlines embedded in the string are still respected.\"", ")", "text_right_clip", "=", "(", "u\"This is a right aligned and clipped Text widget.\\n\"", "u\"<100 <-95 <-90 <-85 <-80 <-75 <-70 <-65 \"", "u\"Text will be cut off at the left of this widget.\"", ")", "text_center_clip", "=", "(", "u\"Center aligned and clipped widgets will have \"", "u\"text cut off both sides.\"", ")", "text_ellipsis", "=", "(", "u\"Text can be clipped using the ellipsis character (…)\\n\"", "u\"Extra text is discarded and a … mark is shown.\"", "u\"50-> 55-> 60-> 65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\\n\"", ")", "text_any", "=", "(", "u\"The 'any' wrap mode will wrap on any character. This \"", "u\"mode will not collapse space characters at the end of the \"", "u\"line but it still honors embedded newline characters.\\n\"", "u\"Like this one.\"", ")", "text_padding", "=", "(", "u\"Padding widgets have many options. This \"", "u\"is a standard Text widget wrapped with a Padding widget \"", "u\"with the alignment set to relative 20% and with its width \"", "u\"fixed at 40.\"", ")", "text_divider", "=", "[", "u\"The \"", ",", "(", "'important'", ",", "u\"Divider\"", ")", ",", "u\" widget repeats the same character across the whole line. \"", "u\"It can also add blank lines above and below.\"", "]", "text_edit", "=", "[", "u\"The \"", ",", "(", "'important'", ",", "u\"Edit\"", ")", ",", "u\" widget is a simple text editing widget. It supports cursor \"", "u\"movement and tries to maintain the current column when focus \"", "u\"moves to another edit widget. It wraps and aligns the same \"", "u\"way as Text widgets.\"", "]", "text_edit_cap1", "=", "(", "'editcp'", ",", "u\"This is a caption. Edit here: \"", ")", "text_edit_text1", "=", "u\"editable stuff\"", "text_edit_cap2", "=", "(", "'editcp'", ",", "u\"This one supports newlines: \"", ")", "text_edit_text2", "=", "(", "u\"line one starts them all\\n\"", "u\"== line 2 == with some more text to edit.. words.. whee..\\n\"", "u\"LINE III, the line to end lines one and two, unless you \"", "u\"change something.\"", ")", "text_edit_cap3", "=", "(", "'editcp'", ",", "u\"This one is clipped, try \"", "u\"editing past the edge: \"", ")", "text_edit_text3", "=", "u\"add some text here -> -> -> ....\"", "text_edit_alignments", "=", "u\"Different Alignments:\"", "text_edit_left", "=", "u\"left aligned (default)\"", "text_edit_center", "=", "u\"center aligned\"", "text_edit_right", "=", "u\"right aligned\"", "text_intedit", "=", "(", "'editcp'", ",", "[", "(", "'important'", ",", "u\"IntEdit\"", ")", ",", "u\" allows only numbers: \"", "]", ")", "text_edit_padding", "=", "(", "'editcp'", ",", "u\"Edit widget within a Padding widget \"", ")", "text_columns1", "=", "[", "(", "'important'", ",", "u\"Columns\"", ")", ",", "u\" are used to share horizontal screen space. \"", "u\"This one splits the space into two parts with \"", "u\"three characters between each column. The \"", "u\"contents of each column is a single widget.\"", "]", "text_columns2", "=", "[", "u\"When you need to put more than one \"", "u\"widget into a column you can use a \"", ",", "(", "'important'", ",", "u\"Pile\"", ")", ",", "u\" to combine two or more widgets.\"", "]", "text_col_columns", "=", "u\"Columns may be placed inside other columns.\"", "text_col_21", "=", "u\"Col 2.1\"", "text_col_22", "=", "u\"Col 2.2\"", "text_col_23", "=", "u\"Col 2.3\"", "text_column_widths", "=", "(", "u\"Columns may also have uneven relative \"", "u\"weights or fixed widths. Use a minimum width so that \"", "u\"columns don't become too small.\"", ")", "text_weight", "=", "u\"Weight %d\"", "text_fixed_9", "=", "u\"<Fixed 9>\"", "# should be 9 columns wide", "text_fixed_14", "=", "u\"<--Fixed 14-->\"", "# should be 14 columns wide", "text_edit_col_cap1", "=", "(", "'editcp'", ",", "u\"Edit widget within Columns\"", ")", "text_edit_col_text1", "=", "u\"here's\\nsome\\ninfo\"", "text_edit_col_cap2", "=", "(", "'editcp'", ",", "u\"and within Pile \"", ")", "text_edit_col_text2", "=", "u\"more\"", "text_edit_col_cap3", "=", "(", "'editcp'", ",", "u\"another \"", ")", "text_edit_col_text3", "=", "u\"still more\"", "text_gridflow", "=", "[", "u\"A \"", ",", "(", "'important'", ",", "u\"GridFlow\"", ")", ",", "u\" widget \"", "u\"may be used to display a list of flow widgets with equal \"", "u\"widths. Widgets that don't fit on the first line will \"", "u\"flow to the next. This is useful for small widgets that \"", "u\"you want to keep together such as \"", ",", "(", "'important'", ",", "u\"Button\"", ")", ",", "u\", \"", ",", "(", "'important'", ",", "u\"CheckBox\"", ")", ",", "u\" and \"", ",", "(", "'important'", ",", "u\"RadioButton\"", ")", ",", "u\" widgets.\"", "]", "text_button_list", "=", "[", "u\"Yes\"", ",", "u\"No\"", ",", "u\"Perhaps\"", ",", "u\"Certainly\"", ",", "u\"Partially\"", ",", "u\"Tuesdays Only\"", ",", "u\"Help\"", "]", "text_cb_list", "=", "[", "u\"Wax\"", ",", "u\"Wash\"", ",", "u\"Buff\"", ",", "u\"Clear Coat\"", ",", "u\"Dry\"", ",", "u\"Racing Stripe\"", "]", "text_rb_list", "=", "[", "u\"Morning\"", ",", "u\"Afternoon\"", ",", "u\"Evening\"", ",", "u\"Weekend\"", "]", "text_listbox", "=", "[", "u\"All these widgets have been displayed \"", "u\"with the help of a \"", ",", "(", "'important'", ",", "u\"ListBox\"", ")", ",", "u\" widget. \"", "u\"ListBox widgets handle scrolling and changing focus. A \"", ",", "(", "'important'", ",", "u\"Frame\"", ")", ",", "u\" widget is used to keep the \"", "u\"instructions at the top of the screen.\"", "]", "def", "button_press", "(", "button", ")", ":", "frame", ".", "footer", "=", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Text", "(", "[", "u\"Pressed: \"", ",", "button", ".", "get_label", "(", ")", "]", ")", ",", "'header'", ")", "radio_button_group", "=", "[", "]", "blank", "=", "urwid", ".", "Divider", "(", ")", "listbox_content", "=", "[", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "Text", "(", "text_intro", ")", ",", "left", "=", "2", ",", "right", "=", "2", ",", "min_width", "=", "20", ")", ",", "blank", ",", "urwid", ".", "Text", "(", "text_right", ",", "align", "=", "'right'", ")", ",", "blank", ",", "urwid", ".", "Text", "(", "text_center", ",", "align", "=", "'center'", ")", ",", "blank", ",", "urwid", ".", "Text", "(", "text_clip", ",", "wrap", "=", "'clip'", ")", ",", "blank", ",", "urwid", ".", "Text", "(", "text_right_clip", ",", "align", "=", "'right'", ",", "wrap", "=", "'clip'", ")", ",", "blank", ",", "urwid", ".", "Text", "(", "text_center_clip", ",", "align", "=", "'center'", ",", "wrap", "=", "'clip'", ")", ",", "blank", ",", "urwid", ".", "Text", "(", "text_ellipsis", ",", "wrap", "=", "'ellipsis'", ")", ",", "blank", ",", "urwid", ".", "Text", "(", "text_any", ",", "wrap", "=", "'any'", ")", ",", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "Text", "(", "text_padding", ")", ",", "(", "'relative'", ",", "20", ")", ",", "40", ")", ",", "blank", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Divider", "(", "\"=\"", ",", "1", ")", ",", "'bright'", ")", ",", "urwid", ".", "Padding", "(", "urwid", ".", "Text", "(", "text_divider", ")", ",", "left", "=", "2", ",", "right", "=", "2", ",", "min_width", "=", "20", ")", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Divider", "(", "\"-\"", ",", "0", ",", "1", ")", ",", "'bright'", ")", ",", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "Text", "(", "text_edit", ")", ",", "left", "=", "2", ",", "right", "=", "2", ",", "min_width", "=", "20", ")", ",", "blank", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "text_edit_cap1", ",", "text_edit_text1", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "blank", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "text_edit_cap2", ",", "text_edit_text2", ",", "multiline", "=", "True", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "blank", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "text_edit_cap3", ",", "text_edit_text3", ",", "wrap", "=", "'clip'", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "blank", ",", "urwid", ".", "Text", "(", "text_edit_alignments", ")", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "\"\"", ",", "text_edit_left", ",", "align", "=", "'left'", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "\"\"", ",", "text_edit_center", ",", "align", "=", "'center'", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "\"\"", ",", "text_edit_right", ",", "align", "=", "'right'", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "blank", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "IntEdit", "(", "text_intedit", ",", "123", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "text_edit_padding", ",", "\"\"", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "left", "=", "10", ",", "width", "=", "50", ")", ",", "blank", ",", "blank", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Columns", "(", "[", "urwid", ".", "Divider", "(", "\".\"", ")", ",", "urwid", ".", "Divider", "(", "\",\"", ")", ",", "urwid", ".", "Divider", "(", "\".\"", ")", ",", "]", ")", ",", "'bright'", ")", ",", "blank", ",", "urwid", ".", "Columns", "(", "[", "urwid", ".", "Padding", "(", "urwid", ".", "Text", "(", "text_columns1", ")", ",", "left", "=", "2", ",", "right", "=", "0", ",", "min_width", "=", "20", ")", ",", "urwid", ".", "Pile", "(", "[", "urwid", ".", "Divider", "(", "\"~\"", ")", ",", "urwid", ".", "Text", "(", "text_columns2", ")", ",", "urwid", ".", "Divider", "(", "\"_\"", ")", "]", ")", "]", ",", "3", ")", ",", "blank", ",", "blank", ",", "urwid", ".", "Columns", "(", "[", "urwid", ".", "Text", "(", "text_col_columns", ")", ",", "urwid", ".", "Columns", "(", "[", "urwid", ".", "Text", "(", "text_col_21", ")", ",", "urwid", ".", "Text", "(", "text_col_22", ")", ",", "urwid", ".", "Text", "(", "text_col_23", ")", ",", "]", ",", "1", ")", ",", "]", ",", "2", ")", ",", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "Text", "(", "text_column_widths", ")", ",", "left", "=", "2", ",", "right", "=", "2", ",", "min_width", "=", "20", ")", ",", "blank", ",", "urwid", ".", "Columns", "(", "[", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Text", "(", "text_weight", "%", "1", ")", ",", "'reverse'", ")", ",", "(", "'weight'", ",", "2", ",", "urwid", ".", "Text", "(", "text_weight", "%", "2", ")", ")", ",", "(", "'weight'", ",", "3", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Text", "(", "text_weight", "%", "3", ")", ",", "'reverse'", ")", ")", ",", "(", "'weight'", ",", "4", ",", "urwid", ".", "Text", "(", "text_weight", "%", "4", ")", ")", ",", "(", "'weight'", ",", "5", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Text", "(", "text_weight", "%", "5", ")", ",", "'reverse'", ")", ")", ",", "(", "'weight'", ",", "6", ",", "urwid", ".", "Text", "(", "text_weight", "%", "6", ")", ")", ",", "]", ",", "0", ",", "min_width", "=", "8", ")", ",", "blank", ",", "urwid", ".", "Columns", "(", "[", "(", "'weight'", ",", "2", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Text", "(", "text_weight", "%", "2", ")", ",", "'reverse'", ")", ")", ",", "(", "'fixed'", ",", "9", ",", "urwid", ".", "Text", "(", "text_fixed_9", ")", ")", ",", "(", "'weight'", ",", "3", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Text", "(", "text_weight", "%", "3", ")", ",", "'reverse'", ")", ")", ",", "(", "'fixed'", ",", "14", ",", "urwid", ".", "Text", "(", "text_fixed_14", ")", ")", ",", "]", ",", "0", ",", "min_width", "=", "8", ")", ",", "blank", ",", "urwid", ".", "Columns", "(", "[", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "text_edit_col_cap1", ",", "text_edit_col_text1", ",", "multiline", "=", "True", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "urwid", ".", "Pile", "(", "[", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "text_edit_col_cap2", ",", "text_edit_col_text2", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "blank", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Edit", "(", "text_edit_col_cap3", ",", "text_edit_col_text3", ")", ",", "'editbx'", ",", "'editfc'", ")", ",", "]", ")", ",", "]", ",", "1", ")", ",", "blank", ",", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Columns", "(", "[", "urwid", ".", "Divider", "(", "\"'\"", ")", ",", "urwid", ".", "Divider", "(", "'\"'", ")", ",", "urwid", ".", "Divider", "(", "\"~\"", ")", ",", "urwid", ".", "Divider", "(", "'\"'", ")", ",", "urwid", ".", "Divider", "(", "\"'\"", ")", ",", "]", ")", ",", "'bright'", ")", ",", "blank", ",", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "Text", "(", "text_gridflow", ")", ",", "left", "=", "2", ",", "right", "=", "2", ",", "min_width", "=", "20", ")", ",", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "GridFlow", "(", "[", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Button", "(", "txt", ",", "button_press", ")", ",", "'buttn'", ",", "'buttnf'", ")", "for", "txt", "in", "text_button_list", "]", ",", "13", ",", "3", ",", "1", ",", "'left'", ")", ",", "left", "=", "4", ",", "right", "=", "3", ",", "min_width", "=", "13", ")", ",", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "GridFlow", "(", "[", "urwid", ".", "AttrWrap", "(", "urwid", ".", "CheckBox", "(", "txt", ")", ",", "'buttn'", ",", "'buttnf'", ")", "for", "txt", "in", "text_cb_list", "]", ",", "10", ",", "3", ",", "1", ",", "'left'", ")", ",", "left", "=", "4", ",", "right", "=", "3", ",", "min_width", "=", "10", ")", ",", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "GridFlow", "(", "[", "urwid", ".", "AttrWrap", "(", "urwid", ".", "RadioButton", "(", "radio_button_group", ",", "txt", ")", ",", "'buttn'", ",", "'buttnf'", ")", "for", "txt", "in", "text_rb_list", "]", ",", "13", ",", "3", ",", "1", ",", "'left'", ")", ",", "left", "=", "4", ",", "right", "=", "3", ",", "min_width", "=", "13", ")", ",", "blank", ",", "blank", ",", "urwid", ".", "Padding", "(", "urwid", ".", "Text", "(", "text_listbox", ")", ",", "left", "=", "2", ",", "right", "=", "2", ",", "min_width", "=", "20", ")", ",", "blank", ",", "blank", ",", "]", "header", "=", "urwid", ".", "AttrWrap", "(", "urwid", ".", "Text", "(", "text_header", ")", ",", "'header'", ")", "listbox", "=", "urwid", ".", "ListBox", "(", "urwid", ".", "SimpleListWalker", "(", "listbox_content", ")", ")", "frame", "=", "urwid", ".", "Frame", "(", "urwid", ".", "AttrWrap", "(", "listbox", ",", "'body'", ")", ",", "header", "=", "header", ")", "palette", "=", "[", "(", "'body'", ",", "'black'", ",", "'light gray'", ",", "'standout'", ")", ",", "(", "'reverse'", ",", "'light gray'", ",", "'black'", ")", ",", "(", "'header'", ",", "'white'", ",", "'dark red'", ",", "'bold'", ")", ",", "(", "'important'", ",", "'dark blue'", ",", "'light gray'", ",", "(", "'standout'", ",", "'underline'", ")", ")", ",", "(", "'editfc'", ",", "'white'", ",", "'dark blue'", ",", "'bold'", ")", ",", "(", "'editbx'", ",", "'light gray'", ",", "'dark blue'", ")", ",", "(", "'editcp'", ",", "'black'", ",", "'light gray'", ",", "'standout'", ")", ",", "(", "'bright'", ",", "'dark gray'", ",", "'light gray'", ",", "(", "'bold'", ",", "'standout'", ")", ")", ",", "(", "'buttn'", ",", "'black'", ",", "'dark cyan'", ")", ",", "(", "'buttnf'", ",", "'white'", ",", "'dark blue'", ",", "'bold'", ")", ",", "]", "# use appropriate Screen class", "if", "urwid", ".", "web_display", ".", "is_web_request", "(", ")", ":", "screen", "=", "urwid", ".", "web_display", ".", "Screen", "(", ")", "else", ":", "screen", "=", "urwid", ".", "raw_display", ".", "Screen", "(", ")", "def", "unhandled", "(", "key", ")", ":", "if", "key", "==", "'f8'", ":", "raise", "urwid", ".", "ExitMainLoop", "(", ")", "urwid", ".", "MainLoop", "(", "frame", ",", "palette", ",", "screen", ",", "unhandled_input", "=", "unhandled", ")", ".", "run", "(", ")" ]
https://github.com/urwid/urwid/blob/e2423b5069f51d318ea1ac0f355a0efe5448f7eb/examples/tour.py#L31-L326
ctxis/CAPE
dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82
modules/processing/parsers/mwcp/reporter.py
python
Reporter.get_output_text
(self)
return output
Get data in human readable report format.
Get data in human readable report format.
[ "Get", "data", "in", "human", "readable", "report", "format", "." ]
def get_output_text(self): """ Get data in human readable report format. """ output = "" infoorderlist = INFO_FIELD_ORDER fieldorderlist = STANDARD_FIELD_ORDER if 'inputfilename' in self.metadata: output += "\n----File Information----\n\n" for key in infoorderlist: if key in self.metadata: output += self.get_printable_key_value( key, self.metadata[key]) output += "\n----Standard Metadata----\n\n" for key in fieldorderlist: if key in self.metadata: output += self.get_printable_key_value(key, self.metadata[key]) # in case we have additional fields in fields.json but the order is not # updated for key in self.metadata: if key not in fieldorderlist and key not in ["other", "debug", "outputfile"] and key in self.fields: output += self.get_printable_key_value(key, self.metadata[key]) if "other" in self.metadata: output += "\n----Other Metadata----\n\n" for key in sorted(list(self.metadata["other"])): output += self.get_printable_key_value( key, self.metadata["other"][key]) if "debug" in self.metadata: output += "\n----Debug----\n\n" for item in self.metadata["debug"]: output += "{}\n".format(item) if "outputfile" in self.metadata: output += "\n----Output Files----\n\n" for value in self.metadata["outputfile"]: output += self.get_printable_key_value( value[0], (value[1], value[2])) if self.errors: output += "\n----Errors----\n\n" for item in self.errors: output += "{}\n".format(item) return output
[ "def", "get_output_text", "(", "self", ")", ":", "output", "=", "\"\"", "infoorderlist", "=", "INFO_FIELD_ORDER", "fieldorderlist", "=", "STANDARD_FIELD_ORDER", "if", "'inputfilename'", "in", "self", ".", "metadata", ":", "output", "+=", "\"\\n----File Information----\\n\\n\"", "for", "key", "in", "infoorderlist", ":", "if", "key", "in", "self", ".", "metadata", ":", "output", "+=", "self", ".", "get_printable_key_value", "(", "key", ",", "self", ".", "metadata", "[", "key", "]", ")", "output", "+=", "\"\\n----Standard Metadata----\\n\\n\"", "for", "key", "in", "fieldorderlist", ":", "if", "key", "in", "self", ".", "metadata", ":", "output", "+=", "self", ".", "get_printable_key_value", "(", "key", ",", "self", ".", "metadata", "[", "key", "]", ")", "# in case we have additional fields in fields.json but the order is not", "# updated", "for", "key", "in", "self", ".", "metadata", ":", "if", "key", "not", "in", "fieldorderlist", "and", "key", "not", "in", "[", "\"other\"", ",", "\"debug\"", ",", "\"outputfile\"", "]", "and", "key", "in", "self", ".", "fields", ":", "output", "+=", "self", ".", "get_printable_key_value", "(", "key", ",", "self", ".", "metadata", "[", "key", "]", ")", "if", "\"other\"", "in", "self", ".", "metadata", ":", "output", "+=", "\"\\n----Other Metadata----\\n\\n\"", "for", "key", "in", "sorted", "(", "list", "(", "self", ".", "metadata", "[", "\"other\"", "]", ")", ")", ":", "output", "+=", "self", ".", "get_printable_key_value", "(", "key", ",", "self", ".", "metadata", "[", "\"other\"", "]", "[", "key", "]", ")", "if", "\"debug\"", "in", "self", ".", "metadata", ":", "output", "+=", "\"\\n----Debug----\\n\\n\"", "for", "item", "in", "self", ".", "metadata", "[", "\"debug\"", "]", ":", "output", "+=", "\"{}\\n\"", ".", "format", "(", "item", ")", "if", "\"outputfile\"", "in", "self", ".", "metadata", ":", "output", "+=", "\"\\n----Output Files----\\n\\n\"", "for", "value", "in", "self", ".", "metadata", "[", "\"outputfile\"", "]", ":", "output", "+=", "self", ".", "get_printable_key_value", "(", "value", "[", "0", "]", ",", "(", "value", "[", "1", "]", ",", "value", "[", "2", "]", ")", ")", "if", "self", ".", "errors", ":", "output", "+=", "\"\\n----Errors----\\n\\n\"", "for", "item", "in", "self", ".", "errors", ":", "output", "+=", "\"{}\\n\"", ".", "format", "(", "item", ")", "return", "output" ]
https://github.com/ctxis/CAPE/blob/dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82/modules/processing/parsers/mwcp/reporter.py#L702-L752
ipython/ipyparallel
d35d4fb9501da5b3280b11e83ed633a95f17be1d
ipyparallel/cluster/_winhpcjob.py
python
WinHPCJob.tostring
(self)
return txt
Return the string representation of the job description XML.
Return the string representation of the job description XML.
[ "Return", "the", "string", "representation", "of", "the", "job", "description", "XML", "." ]
def tostring(self): """Return the string representation of the job description XML.""" root = self.as_element() indent(root) txt = ET.tostring(root, encoding="utf-8").decode('utf-8') # Now remove the tokens used to order the attributes. txt = re.sub(r'_[A-Z]_', '', txt) txt = '<?xml version="1.0" encoding="utf-8"?>\n' + txt return txt
[ "def", "tostring", "(", "self", ")", ":", "root", "=", "self", ".", "as_element", "(", ")", "indent", "(", "root", ")", "txt", "=", "ET", ".", "tostring", "(", "root", ",", "encoding", "=", "\"utf-8\"", ")", ".", "decode", "(", "'utf-8'", ")", "# Now remove the tokens used to order the attributes.", "txt", "=", "re", ".", "sub", "(", "r'_[A-Z]_'", ",", "''", ",", "txt", ")", "txt", "=", "'<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n'", "+", "txt", "return", "txt" ]
https://github.com/ipython/ipyparallel/blob/d35d4fb9501da5b3280b11e83ed633a95f17be1d/ipyparallel/cluster/_winhpcjob.py#L129-L137
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/importlib/_bootstrap_external.py
python
_LoaderBasics.exec_module
(self, module)
Execute the module.
Execute the module.
[ "Execute", "the", "module", "." ]
def exec_module(self, module): """Execute the module.""" code = self.get_code(module.__name__) if code is None: raise ImportError('cannot load module {!r} when get_code() ' 'returns None'.format(module.__name__)) _bootstrap._call_with_frames_removed(exec, code, module.__dict__)
[ "def", "exec_module", "(", "self", ",", "module", ")", ":", "code", "=", "self", ".", "get_code", "(", "module", ".", "__name__", ")", "if", "code", "is", "None", ":", "raise", "ImportError", "(", "'cannot load module {!r} when get_code() '", "'returns None'", ".", "format", "(", "module", ".", "__name__", ")", ")", "_bootstrap", ".", "_call_with_frames_removed", "(", "exec", ",", "code", ",", "module", ".", "__dict__", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/importlib/_bootstrap_external.py#L782-L788
TesterlifeRaymond/doraemon
d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333
src/lib/BeautifulReport.py
python
ReportTestResult.addError
(self, test, err)
add Some Error Result and infos :param test: :param err: :return:
add Some Error Result and infos :param test: :param err: :return:
[ "add", "Some", "Error", "Result", "and", "infos", ":", "param", "test", ":", ":", "param", "err", ":", ":", "return", ":" ]
def addError(self, test, err): """ add Some Error Result and infos :param test: :param err: :return: """ logs = [] output = self.complete_output() logs.append(output) logs.extend(self.error_or_failure_text(err)) self.failure_count += 1 self.add_test_type('失败', logs) if self.verbosity > 1: sys.stderr.write('F ') sys.stderr.write(str(test)) sys.stderr.write('\n') else: sys.stderr.write('F') self._mirrorOutput = True
[ "def", "addError", "(", "self", ",", "test", ",", "err", ")", ":", "logs", "=", "[", "]", "output", "=", "self", ".", "complete_output", "(", ")", "logs", ".", "append", "(", "output", ")", "logs", ".", "extend", "(", "self", ".", "error_or_failure_text", "(", "err", ")", ")", "self", ".", "failure_count", "+=", "1", "self", ".", "add_test_type", "(", "'失败', lo", "g", ")", "", "if", "self", ".", "verbosity", ">", "1", ":", "sys", ".", "stderr", ".", "write", "(", "'F '", ")", "sys", ".", "stderr", ".", "write", "(", "str", "(", "test", ")", ")", "sys", ".", "stderr", ".", "write", "(", "'\\n'", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "'F'", ")", "self", ".", "_mirrorOutput", "=", "True" ]
https://github.com/TesterlifeRaymond/doraemon/blob/d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333/src/lib/BeautifulReport.py#L248-L267
lebedov/scikit-cuda
5d3c74f926fe7ce67ecfc85e9623aab7bc0b344f
skcuda/cublas.py
python
cublasDgemm
(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc)
Matrix-matrix product for real double precision general matrix. References ---------- `cublas<t>gemm <http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm>`_
Matrix-matrix product for real double precision general matrix.
[ "Matrix", "-", "matrix", "product", "for", "real", "double", "precision", "general", "matrix", "." ]
def cublasDgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc): """ Matrix-matrix product for real double precision general matrix. References ---------- `cublas<t>gemm <http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm>`_ """ status = _libcublas.cublasDgemm_v2(handle, _CUBLAS_OP[transa], _CUBLAS_OP[transb], m, n, k, ctypes.byref(ctypes.c_double(alpha)), int(A), lda, int(B), ldb, ctypes.byref(ctypes.c_double(beta)), int(C), ldc) cublasCheckStatus(status)
[ "def", "cublasDgemm", "(", "handle", ",", "transa", ",", "transb", ",", "m", ",", "n", ",", "k", ",", "alpha", ",", "A", ",", "lda", ",", "B", ",", "ldb", ",", "beta", ",", "C", ",", "ldc", ")", ":", "status", "=", "_libcublas", ".", "cublasDgemm_v2", "(", "handle", ",", "_CUBLAS_OP", "[", "transa", "]", ",", "_CUBLAS_OP", "[", "transb", "]", ",", "m", ",", "n", ",", "k", ",", "ctypes", ".", "byref", "(", "ctypes", ".", "c_double", "(", "alpha", ")", ")", ",", "int", "(", "A", ")", ",", "lda", ",", "int", "(", "B", ")", ",", "ldb", ",", "ctypes", ".", "byref", "(", "ctypes", ".", "c_double", "(", "beta", ")", ")", ",", "int", "(", "C", ")", ",", "ldc", ")", "cublasCheckStatus", "(", "status", ")" ]
https://github.com/lebedov/scikit-cuda/blob/5d3c74f926fe7ce67ecfc85e9623aab7bc0b344f/skcuda/cublas.py#L4367-L4383
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
plugins/ipconsole/ipython_view.py
python
ConsoleView._showPrompt
(self, prompt)
Prints prompt at start of line. @param prompt: Prompt to print. @type prompt: string
Prints prompt at start of line.
[ "Prints", "prompt", "at", "start", "of", "line", "." ]
def _showPrompt(self, prompt): """ Prints prompt at start of line. @param prompt: Prompt to print. @type prompt: string """ self._write(prompt) self.text_buffer.move_mark(self.line_start, self.text_buffer.get_end_iter())
[ "def", "_showPrompt", "(", "self", ",", "prompt", ")", ":", "self", ".", "_write", "(", "prompt", ")", "self", ".", "text_buffer", ".", "move_mark", "(", "self", ".", "line_start", ",", "self", ".", "text_buffer", ".", "get_end_iter", "(", ")", ")" ]
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/plugins/ipconsole/ipython_view.py#L499-L507
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_serviceaccount_secret.py
python
OCServiceAccountSecret.service_account
(self)
return self._service_account
Property for the service account
Property for the service account
[ "Property", "for", "the", "service", "account" ]
def service_account(self): ''' Property for the service account ''' if not self._service_account: self.get() return self._service_account
[ "def", "service_account", "(", "self", ")", ":", "if", "not", "self", ".", "_service_account", ":", "self", ".", "get", "(", ")", "return", "self", ".", "_service_account" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_serviceaccount_secret.py#L1604-L1608
SamSchott/maestral
a32653bac7b5a76cb326d4fd5a4fb2c11f19a2fc
src/maestral/main.py
python
Maestral.list_shared_links
(self, dbx_path: Optional[str] = None)
return [dropbox_stone_to_dict(link) for link in res.links]
Returns a list of all shared links for the given Dropbox path. If no path is given, return all shared links for the account, up to a maximum of 1,000 links. :param dbx_path: Path to item on Dropbox. :returns: List of shared link information as dictionaries. See :class:`dropbox.sharing.SharedLinkMetadata` for keys and values. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked.
Returns a list of all shared links for the given Dropbox path. If no path is given, return all shared links for the account, up to a maximum of 1,000 links.
[ "Returns", "a", "list", "of", "all", "shared", "links", "for", "the", "given", "Dropbox", "path", ".", "If", "no", "path", "is", "given", "return", "all", "shared", "links", "for", "the", "account", "up", "to", "a", "maximum", "of", "1", "000", "links", "." ]
def list_shared_links(self, dbx_path: Optional[str] = None) -> List[StoneType]: """ Returns a list of all shared links for the given Dropbox path. If no path is given, return all shared links for the account, up to a maximum of 1,000 links. :param dbx_path: Path to item on Dropbox. :returns: List of shared link information as dictionaries. See :class:`dropbox.sharing.SharedLinkMetadata` for keys and values. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. """ self._check_linked() res = self.client.list_shared_links(dbx_path) return [dropbox_stone_to_dict(link) for link in res.links]
[ "def", "list_shared_links", "(", "self", ",", "dbx_path", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "List", "[", "StoneType", "]", ":", "self", ".", "_check_linked", "(", ")", "res", "=", "self", ".", "client", ".", "list_shared_links", "(", "dbx_path", ")", "return", "[", "dropbox_stone_to_dict", "(", "link", ")", "for", "link", "in", "res", ".", "links", "]" ]
https://github.com/SamSchott/maestral/blob/a32653bac7b5a76cb326d4fd5a4fb2c11f19a2fc/src/maestral/main.py#L1310-L1327
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/cv/models/segmenter.py
python
UNet.__init__
(self, num_classes=2, use_mixed_loss=False, use_deconv=False, align_corners=False, **params)
[]
def __init__(self, num_classes=2, use_mixed_loss=False, use_deconv=False, align_corners=False, **params): params.update({ 'use_deconv': use_deconv, 'align_corners': align_corners }) super(UNet, self).__init__( model_name='UNet', num_classes=num_classes, use_mixed_loss=use_mixed_loss, **params)
[ "def", "__init__", "(", "self", ",", "num_classes", "=", "2", ",", "use_mixed_loss", "=", "False", ",", "use_deconv", "=", "False", ",", "align_corners", "=", "False", ",", "*", "*", "params", ")", ":", "params", ".", "update", "(", "{", "'use_deconv'", ":", "use_deconv", ",", "'align_corners'", ":", "align_corners", "}", ")", "super", "(", "UNet", ",", "self", ")", ".", "__init__", "(", "model_name", "=", "'UNet'", ",", "num_classes", "=", "num_classes", ",", "use_mixed_loss", "=", "use_mixed_loss", ",", "*", "*", "params", ")" ]
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/cv/models/segmenter.py#L662-L676
man-group/arctic
004983367acd4b5fcc5d034cb275389fe09dc9d0
arctic/chunkstore/chunkstore.py
python
ChunkStore.read_audit_log
(self, symbol=None)
return [x for x in self._audit.find({}, {'_id': False})]
Reads the audit log Parameters ---------- symbol: str optionally only retrieve specific symbol's audit information Returns ------- list of dicts
Reads the audit log
[ "Reads", "the", "audit", "log" ]
def read_audit_log(self, symbol=None): """ Reads the audit log Parameters ---------- symbol: str optionally only retrieve specific symbol's audit information Returns ------- list of dicts """ if symbol: return [x for x in self._audit.find({'symbol': symbol}, {'_id': False})] return [x for x in self._audit.find({}, {'_id': False})]
[ "def", "read_audit_log", "(", "self", ",", "symbol", "=", "None", ")", ":", "if", "symbol", ":", "return", "[", "x", "for", "x", "in", "self", ".", "_audit", ".", "find", "(", "{", "'symbol'", ":", "symbol", "}", ",", "{", "'_id'", ":", "False", "}", ")", "]", "return", "[", "x", "for", "x", "in", "self", ".", "_audit", ".", "find", "(", "{", "}", ",", "{", "'_id'", ":", "False", "}", ")", "]" ]
https://github.com/man-group/arctic/blob/004983367acd4b5fcc5d034cb275389fe09dc9d0/arctic/chunkstore/chunkstore.py#L289-L304
implus/PytorchInsight
2864528f8b83f52c3df76f7c3804aa468b91e5cf
detection/mmdet/ops/dcn/modules/deform_conv.py
python
DeformConv.__init__
(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, bias=False)
[]
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, bias=False): assert not bias super(DeformConv, self).__init__() assert in_channels % groups == 0, \ 'in_channels {} cannot be divisible by groups {}'.format( in_channels, groups) assert out_channels % groups == 0, \ 'out_channels {} cannot be divisible by groups {}'.format( out_channels, groups) self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = _pair(kernel_size) self.stride = _pair(stride) self.padding = _pair(padding) self.dilation = _pair(dilation) self.groups = groups self.deformable_groups = deformable_groups self.weight = nn.Parameter( torch.Tensor(out_channels, in_channels // self.groups, *self.kernel_size)) self.reset_parameters()
[ "def", "__init__", "(", "self", ",", "in_channels", ",", "out_channels", ",", "kernel_size", ",", "stride", "=", "1", ",", "padding", "=", "0", ",", "dilation", "=", "1", ",", "groups", "=", "1", ",", "deformable_groups", "=", "1", ",", "bias", "=", "False", ")", ":", "assert", "not", "bias", "super", "(", "DeformConv", ",", "self", ")", ".", "__init__", "(", ")", "assert", "in_channels", "%", "groups", "==", "0", ",", "'in_channels {} cannot be divisible by groups {}'", ".", "format", "(", "in_channels", ",", "groups", ")", "assert", "out_channels", "%", "groups", "==", "0", ",", "'out_channels {} cannot be divisible by groups {}'", ".", "format", "(", "out_channels", ",", "groups", ")", "self", ".", "in_channels", "=", "in_channels", "self", ".", "out_channels", "=", "out_channels", "self", ".", "kernel_size", "=", "_pair", "(", "kernel_size", ")", "self", ".", "stride", "=", "_pair", "(", "stride", ")", "self", ".", "padding", "=", "_pair", "(", "padding", ")", "self", ".", "dilation", "=", "_pair", "(", "dilation", ")", "self", ".", "groups", "=", "groups", "self", ".", "deformable_groups", "=", "deformable_groups", "self", ".", "weight", "=", "nn", ".", "Parameter", "(", "torch", ".", "Tensor", "(", "out_channels", ",", "in_channels", "//", "self", ".", "groups", ",", "*", "self", ".", "kernel_size", ")", ")", "self", ".", "reset_parameters", "(", ")" ]
https://github.com/implus/PytorchInsight/blob/2864528f8b83f52c3df76f7c3804aa468b91e5cf/detection/mmdet/ops/dcn/modules/deform_conv.py#L12-L44
zenodo/zenodo
3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5
zenodo/modules/records/query.py
python
apply_version_filters
(search, urlkwargs)
return (search, urlkwargs)
Apply record version filters to search.
Apply record version filters to search.
[ "Apply", "record", "version", "filters", "to", "search", "." ]
def apply_version_filters(search, urlkwargs): """Apply record version filters to search.""" if 'all_versions' in request.values: all_versions = request.values['all_versions'] if str(all_versions).lower() in ("", "1", "true"): urlkwargs.add('all_versions', "true") else: urlkwargs.add('all_versions', str(request.values['all_versions'])) search = search.filter(Q('term', **{'relations.version.is_last': True})) else: search = search.filter(Q('term', **{'relations.version.is_last': True})) return (search, urlkwargs)
[ "def", "apply_version_filters", "(", "search", ",", "urlkwargs", ")", ":", "if", "'all_versions'", "in", "request", ".", "values", ":", "all_versions", "=", "request", ".", "values", "[", "'all_versions'", "]", "if", "str", "(", "all_versions", ")", ".", "lower", "(", ")", "in", "(", "\"\"", ",", "\"1\"", ",", "\"true\"", ")", ":", "urlkwargs", ".", "add", "(", "'all_versions'", ",", "\"true\"", ")", "else", ":", "urlkwargs", ".", "add", "(", "'all_versions'", ",", "str", "(", "request", ".", "values", "[", "'all_versions'", "]", ")", ")", "search", "=", "search", ".", "filter", "(", "Q", "(", "'term'", ",", "*", "*", "{", "'relations.version.is_last'", ":", "True", "}", ")", ")", "else", ":", "search", "=", "search", ".", "filter", "(", "Q", "(", "'term'", ",", "*", "*", "{", "'relations.version.is_last'", ":", "True", "}", ")", ")", "return", "(", "search", ",", "urlkwargs", ")" ]
https://github.com/zenodo/zenodo/blob/3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5/zenodo/modules/records/query.py#L34-L45
braincorp/PVM
3de2683634f372d2ac5aaa8b19e8ff23420d94d1
PVM_tools/bounding_region.py
python
BoundingRegion.set_keyframe
(self, key_status)
Set keyframe status :param key_status: :return:
Set keyframe status
[ "Set", "keyframe", "status" ]
def set_keyframe(self, key_status): """ Set keyframe status :param key_status: :return: """ self._is_keyframe = key_status
[ "def", "set_keyframe", "(", "self", ",", "key_status", ")", ":", "self", ".", "_is_keyframe", "=", "key_status" ]
https://github.com/braincorp/PVM/blob/3de2683634f372d2ac5aaa8b19e8ff23420d94d1/PVM_tools/bounding_region.py#L637-L644
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/distutils/cygwinccompiler.py
python
_find_exe_version
(cmd)
return LooseVersion(result.group(1).decode())
Find the version of an executable by running `cmd` in the shell. If the command is not found, or the output does not match `RE_VERSION`, returns None.
Find the version of an executable by running `cmd` in the shell.
[ "Find", "the", "version", "of", "an", "executable", "by", "running", "cmd", "in", "the", "shell", "." ]
def _find_exe_version(cmd): """Find the version of an executable by running `cmd` in the shell. If the command is not found, or the output does not match `RE_VERSION`, returns None. """ executable = cmd.split()[0] if find_executable(executable) is None: return None out = Popen(cmd, shell=True, stdout=PIPE).stdout try: out_string = out.read() finally: out.close() result = RE_VERSION.search(out_string) if result is None: return None # LooseVersion works with strings # so we need to decode our bytes return LooseVersion(result.group(1).decode())
[ "def", "_find_exe_version", "(", "cmd", ")", ":", "executable", "=", "cmd", ".", "split", "(", ")", "[", "0", "]", "if", "find_executable", "(", "executable", ")", "is", "None", ":", "return", "None", "out", "=", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ")", ".", "stdout", "try", ":", "out_string", "=", "out", ".", "read", "(", ")", "finally", ":", "out", ".", "close", "(", ")", "result", "=", "RE_VERSION", ".", "search", "(", "out_string", ")", "if", "result", "is", "None", ":", "return", "None", "# LooseVersion works with strings", "# so we need to decode our bytes", "return", "LooseVersion", "(", "result", ".", "group", "(", "1", ")", ".", "decode", "(", ")", ")" ]
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/distutils/cygwinccompiler.py#L373-L392
ialbert/biostar-central
2dc7bd30691a50b2da9c2833ba354056bc686afa
biostar/forum/ajax.py
python
handle_search
(request)
return ajax_success(users=users, msg="Username searched")
Used to search by the user handle.
Used to search by the user handle.
[ "Used", "to", "search", "by", "the", "user", "handle", "." ]
def handle_search(request): """ Used to search by the user handle. """ query = request.GET.get('query') if query: users = User.objects.filter(profile__handle__icontains=query ).values_list('profile__handle', flat=True ).order_by('profile__score') else: users = User.objects.order_by('profile__score').values_list('profile__handle', flat=True) users = list(users[:20]) # Return list of users matching username return ajax_success(users=users, msg="Username searched")
[ "def", "handle_search", "(", "request", ")", ":", "query", "=", "request", ".", "GET", ".", "get", "(", "'query'", ")", "if", "query", ":", "users", "=", "User", ".", "objects", ".", "filter", "(", "profile__handle__icontains", "=", "query", ")", ".", "values_list", "(", "'profile__handle'", ",", "flat", "=", "True", ")", ".", "order_by", "(", "'profile__score'", ")", "else", ":", "users", "=", "User", ".", "objects", ".", "order_by", "(", "'profile__score'", ")", ".", "values_list", "(", "'profile__handle'", ",", "flat", "=", "True", ")", "users", "=", "list", "(", "users", "[", ":", "20", "]", ")", "# Return list of users matching username", "return", "ajax_success", "(", "users", "=", "users", ",", "msg", "=", "\"Username searched\"", ")" ]
https://github.com/ialbert/biostar-central/blob/2dc7bd30691a50b2da9c2833ba354056bc686afa/biostar/forum/ajax.py#L384-L399
burke-software/django-report-builder
21394979d3dc35afac06155aa2dd6cc4bdaffe19
report_builder/models.py
python
Report._get_model_manager
(self)
return model_manager
Get manager from settings else use objects
Get manager from settings else use objects
[ "Get", "manager", "from", "settings", "else", "use", "objects" ]
def _get_model_manager(self): """ Get manager from settings else use objects """ model_manager = 'objects' if getattr(settings, 'REPORT_BUILDER_MODEL_MANAGER', False): model_manager = settings.REPORT_BUILDER_MODEL_MANAGER return model_manager
[ "def", "_get_model_manager", "(", "self", ")", ":", "model_manager", "=", "'objects'", "if", "getattr", "(", "settings", ",", "'REPORT_BUILDER_MODEL_MANAGER'", ",", "False", ")", ":", "model_manager", "=", "settings", ".", "REPORT_BUILDER_MODEL_MANAGER", "return", "model_manager" ]
https://github.com/burke-software/django-report-builder/blob/21394979d3dc35afac06155aa2dd6cc4bdaffe19/report_builder/models.py#L63-L69
biolab/orange2
db40a9449cb45b507d63dcd5739b223f9cffb8e6
Orange/clustering/hierarchical.py
python
clustering
(data, distance_constructor=Orange.distance.Euclidean, linkage=AVERAGE, order=False, progress_callback=None)
return root
Return a hierarchical clustering of the instances in a data set. The method works in approximately O(n2) time (with the worst case O(n3)). :param data: Input data table for clustering. :type data: :class:`Orange.data.Table` :param distance_constructor: Instance distance constructor :type distance_constructor: :class:`Orange.distance.DistanceConstructor` :param linkage: Linkage flag. Must be one of module level flags: - :obj:`SINGLE` - :obj:`AVERAGE` - :obj:`COMPLETE` - :obj:`WARD` :type linkage: int :param order: If `True` run `order_leaves` on the resulting clustering. :type order: bool :param progress_callback: A function (taking one argument) to use for reporting the on the progress. :type progress_callback: function :rtype: :class:`HierarchicalCluster`
Return a hierarchical clustering of the instances in a data set. The method works in approximately O(n2) time (with the worst case O(n3)). :param data: Input data table for clustering. :type data: :class:`Orange.data.Table` :param distance_constructor: Instance distance constructor :type distance_constructor: :class:`Orange.distance.DistanceConstructor` :param linkage: Linkage flag. Must be one of module level flags: - :obj:`SINGLE` - :obj:`AVERAGE` - :obj:`COMPLETE` - :obj:`WARD` :type linkage: int :param order: If `True` run `order_leaves` on the resulting clustering. :type order: bool :param progress_callback: A function (taking one argument) to use for reporting the on the progress. :type progress_callback: function :rtype: :class:`HierarchicalCluster`
[ "Return", "a", "hierarchical", "clustering", "of", "the", "instances", "in", "a", "data", "set", ".", "The", "method", "works", "in", "approximately", "O", "(", "n2", ")", "time", "(", "with", "the", "worst", "case", "O", "(", "n3", "))", ".", ":", "param", "data", ":", "Input", "data", "table", "for", "clustering", ".", ":", "type", "data", ":", ":", "class", ":", "Orange", ".", "data", ".", "Table", ":", "param", "distance_constructor", ":", "Instance", "distance", "constructor", ":", "type", "distance_constructor", ":", ":", "class", ":", "Orange", ".", "distance", ".", "DistanceConstructor", ":", "param", "linkage", ":", "Linkage", "flag", ".", "Must", "be", "one", "of", "module", "level", "flags", ":", "-", ":", "obj", ":", "SINGLE", "-", ":", "obj", ":", "AVERAGE", "-", ":", "obj", ":", "COMPLETE", "-", ":", "obj", ":", "WARD", ":", "type", "linkage", ":", "int", ":", "param", "order", ":", "If", "True", "run", "order_leaves", "on", "the", "resulting", "clustering", ".", ":", "type", "order", ":", "bool", ":", "param", "progress_callback", ":", "A", "function", "(", "taking", "one", "argument", ")", "to", "use", "for", "reporting", "the", "on", "the", "progress", ".", ":", "type", "progress_callback", ":", "function", ":", "rtype", ":", ":", "class", ":", "HierarchicalCluster" ]
def clustering(data, distance_constructor=Orange.distance.Euclidean, linkage=AVERAGE, order=False, progress_callback=None): """ Return a hierarchical clustering of the instances in a data set. The method works in approximately O(n2) time (with the worst case O(n3)). :param data: Input data table for clustering. :type data: :class:`Orange.data.Table` :param distance_constructor: Instance distance constructor :type distance_constructor: :class:`Orange.distance.DistanceConstructor` :param linkage: Linkage flag. Must be one of module level flags: - :obj:`SINGLE` - :obj:`AVERAGE` - :obj:`COMPLETE` - :obj:`WARD` :type linkage: int :param order: If `True` run `order_leaves` on the resulting clustering. :type order: bool :param progress_callback: A function (taking one argument) to use for reporting the on the progress. :type progress_callback: function :rtype: :class:`HierarchicalCluster` """ distance = distance_constructor(data) matrix = Orange.misc.SymMatrix(len(data)) for i in range(len(data)): for j in range(i + 1): matrix[i, j] = distance(data[i], data[j]) root = HierarchicalClustering(matrix, linkage=linkage, progress_callback=(lambda value, obj=None: progress_callback(value * 100.0 / (2 if order else 1))) if progress_callback else None) if order: order_leaves(root, matrix, progress_callback=(lambda value: progress_callback(50.0 + value / 2)) if progress_callback else None) return root
[ "def", "clustering", "(", "data", ",", "distance_constructor", "=", "Orange", ".", "distance", ".", "Euclidean", ",", "linkage", "=", "AVERAGE", ",", "order", "=", "False", ",", "progress_callback", "=", "None", ")", ":", "distance", "=", "distance_constructor", "(", "data", ")", "matrix", "=", "Orange", ".", "misc", ".", "SymMatrix", "(", "len", "(", "data", ")", ")", "for", "i", "in", "range", "(", "len", "(", "data", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ")", ":", "matrix", "[", "i", ",", "j", "]", "=", "distance", "(", "data", "[", "i", "]", ",", "data", "[", "j", "]", ")", "root", "=", "HierarchicalClustering", "(", "matrix", ",", "linkage", "=", "linkage", ",", "progress_callback", "=", "(", "lambda", "value", ",", "obj", "=", "None", ":", "progress_callback", "(", "value", "*", "100.0", "/", "(", "2", "if", "order", "else", "1", ")", ")", ")", "if", "progress_callback", "else", "None", ")", "if", "order", ":", "order_leaves", "(", "root", ",", "matrix", ",", "progress_callback", "=", "(", "lambda", "value", ":", "progress_callback", "(", "50.0", "+", "value", "/", "2", ")", ")", "if", "progress_callback", "else", "None", ")", "return", "root" ]
https://github.com/biolab/orange2/blob/db40a9449cb45b507d63dcd5739b223f9cffb8e6/Orange/clustering/hierarchical.py#L378-L415
renatahodovan/fuzzinator
017264c683b4ecf23f56f30a1b9c0f891b4251a1
fuzzinator/call/anonymize_decorator.py
python
AnonymizeDecorator.__init__
(self, *, old_text, new_text=None, properties=None, **kwargs)
[]
def __init__(self, *, old_text, new_text=None, properties=None, **kwargs): self.old_text = old_text self.new_text = new_text or '' self.properties = as_list(properties) if properties else None
[ "def", "__init__", "(", "self", ",", "*", ",", "old_text", ",", "new_text", "=", "None", ",", "properties", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "old_text", "=", "old_text", "self", ".", "new_text", "=", "new_text", "or", "''", "self", ".", "properties", "=", "as_list", "(", "properties", ")", "if", "properties", "else", "None" ]
https://github.com/renatahodovan/fuzzinator/blob/017264c683b4ecf23f56f30a1b9c0f891b4251a1/fuzzinator/call/anonymize_decorator.py#L43-L46
serhatbolsu/robotframework-appiumlibrary
fae262c1d65a77efdf1dcbb16d7c893703866fb7
AppiumLibrary/keywords/_element.py
python
_ElementKeywords.input_text
(self, locator, text)
Types the given `text` into text field identified by `locator`. See `introduction` for details about locating elements.
Types the given `text` into text field identified by `locator`.
[ "Types", "the", "given", "text", "into", "text", "field", "identified", "by", "locator", "." ]
def input_text(self, locator, text): """Types the given `text` into text field identified by `locator`. See `introduction` for details about locating elements. """ self._info("Typing text '%s' into text field '%s'" % (text, locator)) self._element_input_text_by_locator(locator, text)
[ "def", "input_text", "(", "self", ",", "locator", ",", "text", ")", ":", "self", ".", "_info", "(", "\"Typing text '%s' into text field '%s'\"", "%", "(", "text", ",", "locator", ")", ")", "self", ".", "_element_input_text_by_locator", "(", "locator", ",", "text", ")" ]
https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/fae262c1d65a77efdf1dcbb16d7c893703866fb7/AppiumLibrary/keywords/_element.py#L64-L70
aianaconda/TensorFlow_Engineering_Implementation
cb787e359da9ac5a08d00cd2458fecb4cb5a3a31
code/8-24 mask_rcnn_model.py
python
build_detection_targets
(rpn_rois, gt_class_ids, gt_boxes, gt_masks,num_class)
return rois, roi_gt_class_ids, bboxes, masks
Generate targets for training Stage 2 classifier and mask heads. This is not used in normal training. It's useful for debugging or to train the Mask RCNN heads without using the RPN head. Inputs: rpn_rois: [N, (y1, x1, y2, x2)] proposal boxes. gt_class_ids: [instance count] Integer class IDs gt_boxes: [instance count, (y1, x1, y2, x2)] gt_masks: [height, width, instance count] Ground truth masks. Can be full size or mini-masks. Returns: rois: [TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)] class_ids: [TRAIN_ROIS_PER_IMAGE]. Integer class IDs. bboxes: [TRAIN_ROIS_PER_IMAGE, NUM_CLASSES, (y, x, log(h), log(w))]. Class-specific bbox refinements. masks: [TRAIN_ROIS_PER_IMAGE, height, width, NUM_CLASSES). Class specific masks cropped to bbox boundaries and resized to neural network output size.
Generate targets for training Stage 2 classifier and mask heads. This is not used in normal training. It's useful for debugging or to train the Mask RCNN heads without using the RPN head.
[ "Generate", "targets", "for", "training", "Stage", "2", "classifier", "and", "mask", "heads", ".", "This", "is", "not", "used", "in", "normal", "training", ".", "It", "s", "useful", "for", "debugging", "or", "to", "train", "the", "Mask", "RCNN", "heads", "without", "using", "the", "RPN", "head", "." ]
def build_detection_targets(rpn_rois, gt_class_ids, gt_boxes, gt_masks,num_class): """Generate targets for training Stage 2 classifier and mask heads. This is not used in normal training. It's useful for debugging or to train the Mask RCNN heads without using the RPN head. Inputs: rpn_rois: [N, (y1, x1, y2, x2)] proposal boxes. gt_class_ids: [instance count] Integer class IDs gt_boxes: [instance count, (y1, x1, y2, x2)] gt_masks: [height, width, instance count] Ground truth masks. Can be full size or mini-masks. Returns: rois: [TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)] class_ids: [TRAIN_ROIS_PER_IMAGE]. Integer class IDs. bboxes: [TRAIN_ROIS_PER_IMAGE, NUM_CLASSES, (y, x, log(h), log(w))]. Class-specific bbox refinements. masks: [TRAIN_ROIS_PER_IMAGE, height, width, NUM_CLASSES). Class specific masks cropped to bbox boundaries and resized to neural network output size. """ assert rpn_rois.shape[0] > 0 assert gt_class_ids.dtype == np.int32, "Expected int but got {}".format( gt_class_ids.dtype) assert gt_boxes.dtype == np.int32, "Expected int but got {}".format( gt_boxes.dtype) assert gt_masks.dtype == np.bool_, "Expected bool but got {}".format( gt_masks.dtype) # It's common to add GT Boxes to ROIs but we don't do that here because # according to XinLei Chen's paper, it doesn't help. # Trim empty padding in gt_boxes and gt_masks parts instance_ids = np.where(gt_class_ids > 0)[0] assert instance_ids.shape[0] > 0, "Image must contain instances." gt_class_ids = gt_class_ids[instance_ids] gt_boxes = gt_boxes[instance_ids] gt_masks = gt_masks[:, :, instance_ids] # Compute areas of ROIs and ground truth boxes. rpn_roi_area = (rpn_rois[:, 2] - rpn_rois[:, 0]) * \ (rpn_rois[:, 3] - rpn_rois[:, 1]) gt_box_area = (gt_boxes[:, 2] - gt_boxes[:, 0]) * \ (gt_boxes[:, 3] - gt_boxes[:, 1]) # Compute overlaps [rpn_rois, gt_boxes] overlaps = np.zeros((rpn_rois.shape[0], gt_boxes.shape[0])) for i in range(overlaps.shape[1]): gt = gt_boxes[i] overlaps[:, i] = utils.compute_iou( gt, rpn_rois, gt_box_area[i], rpn_roi_area) # Assign ROIs to GT boxes rpn_roi_iou_argmax = np.argmax(overlaps, axis=1) rpn_roi_iou_max = overlaps[np.arange( overlaps.shape[0]), rpn_roi_iou_argmax] # GT box assigned to each ROI rpn_roi_gt_boxes = gt_boxes[rpn_roi_iou_argmax] rpn_roi_gt_class_ids = gt_class_ids[rpn_roi_iou_argmax] # Positive ROIs are those with >= 0.5 IoU with a GT box. fg_ids = np.where(rpn_roi_iou_max > 0.5)[0] # Negative ROIs are those with max IoU 0.1-0.5 (hard example mining) # TODO: To hard example mine or not to hard example mine, that's the question # bg_ids = np.where((rpn_roi_iou_max >= 0.1) & (rpn_roi_iou_max < 0.5))[0] bg_ids = np.where(rpn_roi_iou_max < 0.5)[0] # Subsample ROIs. Aim for 33% foreground. # FG fg_roi_count = int(TRAIN_ROIS_PER_IMAGE * ROI_POSITIVE_RATIO) if fg_ids.shape[0] > fg_roi_count: keep_fg_ids = np.random.choice(fg_ids, fg_roi_count, replace=False) else: keep_fg_ids = fg_ids # BG remaining = TRAIN_ROIS_PER_IMAGE - keep_fg_ids.shape[0] if bg_ids.shape[0] > remaining: keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False) else: keep_bg_ids = bg_ids # Combine indices of ROIs to keep keep = np.concatenate([keep_fg_ids, keep_bg_ids]) # Need more? remaining = TRAIN_ROIS_PER_IMAGE - keep.shape[0] if remaining > 0: # Looks like we don't have enough samples to maintain the desired # balance. Reduce requirements and fill in the rest. This is # likely different from the Mask RCNN paper. # There is a small chance we have neither fg nor bg samples. if keep.shape[0] == 0: # Pick bg regions with easier IoU threshold bg_ids = np.where(rpn_roi_iou_max < 0.5)[0] assert bg_ids.shape[0] >= remaining keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False) assert keep_bg_ids.shape[0] == remaining keep = np.concatenate([keep, keep_bg_ids]) else: # Fill the rest with repeated bg rois. keep_extra_ids = np.random.choice( keep_bg_ids, remaining, replace=True) keep = np.concatenate([keep, keep_extra_ids]) assert keep.shape[0] == TRAIN_ROIS_PER_IMAGE, \ "keep doesn't match ROI batch size {}, {}".format( keep.shape[0], TRAIN_ROIS_PER_IMAGE) # Reset the gt boxes assigned to BG ROIs. rpn_roi_gt_boxes[keep_bg_ids, :] = 0 rpn_roi_gt_class_ids[keep_bg_ids] = 0 # For each kept ROI, assign a class_id, and for FG ROIs also add bbox refinement. rois = rpn_rois[keep] roi_gt_boxes = rpn_roi_gt_boxes[keep] roi_gt_class_ids = rpn_roi_gt_class_ids[keep] roi_gt_assignment = rpn_roi_iou_argmax[keep] # Class-aware bbox deltas. [y, x, log(h), log(w)] bboxes = np.zeros((TRAIN_ROIS_PER_IMAGE, num_class, 4), dtype=np.float32) pos_ids = np.where(roi_gt_class_ids > 0)[0] bboxes[pos_ids, roi_gt_class_ids[pos_ids]] = utils.box_refinement( rois[pos_ids], roi_gt_boxes[pos_ids, :4]) # Normalize bbox refinements bboxes /= BBOX_STD_DEV # Generate class-specific target masks masks = np.zeros((TRAIN_ROIS_PER_IMAGE,MASK_SHAPE[0],MASK_SHAPE[1], num_class), dtype=np.float32) for i in pos_ids: class_id = roi_gt_class_ids[i] assert class_id > 0, "class id must be greater than 0" gt_id = roi_gt_assignment[i] class_mask = gt_masks[:, :, gt_id] if USE_MINI_MASK: # Create a mask placeholder, the size of the image placeholder = np.zeros([IMAGE_DIM,IMAGE_DIM], dtype=bool) # GT box gt_y1, gt_x1, gt_y2, gt_x2 = gt_boxes[gt_id] gt_w = gt_x2 - gt_x1 gt_h = gt_y2 - gt_y1 # Resize mini mask to size of GT box placeholder[gt_y1:gt_y2, gt_x1:gt_x2] = \ np.round(skimage.transform.resize( class_mask, (gt_h, gt_w), order=1, mode="constant")).astype(bool) # Place the mini batch in the placeholder class_mask = placeholder # Pick part of the mask and resize it y1, x1, y2, x2 = rois[i].astype(np.int32) m = class_mask[y1:y2, x1:x2] mask = skimage.transform.resize(m, MASK_SHAPE, order=1, mode="constant") masks[i, :, :, class_id] = mask return rois, roi_gt_class_ids, bboxes, masks
[ "def", "build_detection_targets", "(", "rpn_rois", ",", "gt_class_ids", ",", "gt_boxes", ",", "gt_masks", ",", "num_class", ")", ":", "assert", "rpn_rois", ".", "shape", "[", "0", "]", ">", "0", "assert", "gt_class_ids", ".", "dtype", "==", "np", ".", "int32", ",", "\"Expected int but got {}\"", ".", "format", "(", "gt_class_ids", ".", "dtype", ")", "assert", "gt_boxes", ".", "dtype", "==", "np", ".", "int32", ",", "\"Expected int but got {}\"", ".", "format", "(", "gt_boxes", ".", "dtype", ")", "assert", "gt_masks", ".", "dtype", "==", "np", ".", "bool_", ",", "\"Expected bool but got {}\"", ".", "format", "(", "gt_masks", ".", "dtype", ")", "# It's common to add GT Boxes to ROIs but we don't do that here because", "# according to XinLei Chen's paper, it doesn't help.", "# Trim empty padding in gt_boxes and gt_masks parts", "instance_ids", "=", "np", ".", "where", "(", "gt_class_ids", ">", "0", ")", "[", "0", "]", "assert", "instance_ids", ".", "shape", "[", "0", "]", ">", "0", ",", "\"Image must contain instances.\"", "gt_class_ids", "=", "gt_class_ids", "[", "instance_ids", "]", "gt_boxes", "=", "gt_boxes", "[", "instance_ids", "]", "gt_masks", "=", "gt_masks", "[", ":", ",", ":", ",", "instance_ids", "]", "# Compute areas of ROIs and ground truth boxes.", "rpn_roi_area", "=", "(", "rpn_rois", "[", ":", ",", "2", "]", "-", "rpn_rois", "[", ":", ",", "0", "]", ")", "*", "(", "rpn_rois", "[", ":", ",", "3", "]", "-", "rpn_rois", "[", ":", ",", "1", "]", ")", "gt_box_area", "=", "(", "gt_boxes", "[", ":", ",", "2", "]", "-", "gt_boxes", "[", ":", ",", "0", "]", ")", "*", "(", "gt_boxes", "[", ":", ",", "3", "]", "-", "gt_boxes", "[", ":", ",", "1", "]", ")", "# Compute overlaps [rpn_rois, gt_boxes]", "overlaps", "=", "np", ".", "zeros", "(", "(", "rpn_rois", ".", "shape", "[", "0", "]", ",", "gt_boxes", ".", "shape", "[", "0", "]", ")", ")", "for", "i", "in", "range", "(", "overlaps", ".", "shape", "[", "1", "]", ")", ":", "gt", "=", "gt_boxes", "[", "i", "]", "overlaps", "[", ":", ",", "i", "]", "=", "utils", ".", "compute_iou", "(", "gt", ",", "rpn_rois", ",", "gt_box_area", "[", "i", "]", ",", "rpn_roi_area", ")", "# Assign ROIs to GT boxes", "rpn_roi_iou_argmax", "=", "np", ".", "argmax", "(", "overlaps", ",", "axis", "=", "1", ")", "rpn_roi_iou_max", "=", "overlaps", "[", "np", ".", "arange", "(", "overlaps", ".", "shape", "[", "0", "]", ")", ",", "rpn_roi_iou_argmax", "]", "# GT box assigned to each ROI", "rpn_roi_gt_boxes", "=", "gt_boxes", "[", "rpn_roi_iou_argmax", "]", "rpn_roi_gt_class_ids", "=", "gt_class_ids", "[", "rpn_roi_iou_argmax", "]", "# Positive ROIs are those with >= 0.5 IoU with a GT box.", "fg_ids", "=", "np", ".", "where", "(", "rpn_roi_iou_max", ">", "0.5", ")", "[", "0", "]", "# Negative ROIs are those with max IoU 0.1-0.5 (hard example mining)", "# TODO: To hard example mine or not to hard example mine, that's the question", "# bg_ids = np.where((rpn_roi_iou_max >= 0.1) & (rpn_roi_iou_max < 0.5))[0]", "bg_ids", "=", "np", ".", "where", "(", "rpn_roi_iou_max", "<", "0.5", ")", "[", "0", "]", "# Subsample ROIs. Aim for 33% foreground.", "# FG", "fg_roi_count", "=", "int", "(", "TRAIN_ROIS_PER_IMAGE", "*", "ROI_POSITIVE_RATIO", ")", "if", "fg_ids", ".", "shape", "[", "0", "]", ">", "fg_roi_count", ":", "keep_fg_ids", "=", "np", ".", "random", ".", "choice", "(", "fg_ids", ",", "fg_roi_count", ",", "replace", "=", "False", ")", "else", ":", "keep_fg_ids", "=", "fg_ids", "# BG", "remaining", "=", "TRAIN_ROIS_PER_IMAGE", "-", "keep_fg_ids", ".", "shape", "[", "0", "]", "if", "bg_ids", ".", "shape", "[", "0", "]", ">", "remaining", ":", "keep_bg_ids", "=", "np", ".", "random", ".", "choice", "(", "bg_ids", ",", "remaining", ",", "replace", "=", "False", ")", "else", ":", "keep_bg_ids", "=", "bg_ids", "# Combine indices of ROIs to keep", "keep", "=", "np", ".", "concatenate", "(", "[", "keep_fg_ids", ",", "keep_bg_ids", "]", ")", "# Need more?", "remaining", "=", "TRAIN_ROIS_PER_IMAGE", "-", "keep", ".", "shape", "[", "0", "]", "if", "remaining", ">", "0", ":", "# Looks like we don't have enough samples to maintain the desired", "# balance. Reduce requirements and fill in the rest. This is", "# likely different from the Mask RCNN paper.", "# There is a small chance we have neither fg nor bg samples.", "if", "keep", ".", "shape", "[", "0", "]", "==", "0", ":", "# Pick bg regions with easier IoU threshold", "bg_ids", "=", "np", ".", "where", "(", "rpn_roi_iou_max", "<", "0.5", ")", "[", "0", "]", "assert", "bg_ids", ".", "shape", "[", "0", "]", ">=", "remaining", "keep_bg_ids", "=", "np", ".", "random", ".", "choice", "(", "bg_ids", ",", "remaining", ",", "replace", "=", "False", ")", "assert", "keep_bg_ids", ".", "shape", "[", "0", "]", "==", "remaining", "keep", "=", "np", ".", "concatenate", "(", "[", "keep", ",", "keep_bg_ids", "]", ")", "else", ":", "# Fill the rest with repeated bg rois.", "keep_extra_ids", "=", "np", ".", "random", ".", "choice", "(", "keep_bg_ids", ",", "remaining", ",", "replace", "=", "True", ")", "keep", "=", "np", ".", "concatenate", "(", "[", "keep", ",", "keep_extra_ids", "]", ")", "assert", "keep", ".", "shape", "[", "0", "]", "==", "TRAIN_ROIS_PER_IMAGE", ",", "\"keep doesn't match ROI batch size {}, {}\"", ".", "format", "(", "keep", ".", "shape", "[", "0", "]", ",", "TRAIN_ROIS_PER_IMAGE", ")", "# Reset the gt boxes assigned to BG ROIs.", "rpn_roi_gt_boxes", "[", "keep_bg_ids", ",", ":", "]", "=", "0", "rpn_roi_gt_class_ids", "[", "keep_bg_ids", "]", "=", "0", "# For each kept ROI, assign a class_id, and for FG ROIs also add bbox refinement.", "rois", "=", "rpn_rois", "[", "keep", "]", "roi_gt_boxes", "=", "rpn_roi_gt_boxes", "[", "keep", "]", "roi_gt_class_ids", "=", "rpn_roi_gt_class_ids", "[", "keep", "]", "roi_gt_assignment", "=", "rpn_roi_iou_argmax", "[", "keep", "]", "# Class-aware bbox deltas. [y, x, log(h), log(w)]", "bboxes", "=", "np", ".", "zeros", "(", "(", "TRAIN_ROIS_PER_IMAGE", ",", "num_class", ",", "4", ")", ",", "dtype", "=", "np", ".", "float32", ")", "pos_ids", "=", "np", ".", "where", "(", "roi_gt_class_ids", ">", "0", ")", "[", "0", "]", "bboxes", "[", "pos_ids", ",", "roi_gt_class_ids", "[", "pos_ids", "]", "]", "=", "utils", ".", "box_refinement", "(", "rois", "[", "pos_ids", "]", ",", "roi_gt_boxes", "[", "pos_ids", ",", ":", "4", "]", ")", "# Normalize bbox refinements", "bboxes", "/=", "BBOX_STD_DEV", "# Generate class-specific target masks", "masks", "=", "np", ".", "zeros", "(", "(", "TRAIN_ROIS_PER_IMAGE", ",", "MASK_SHAPE", "[", "0", "]", ",", "MASK_SHAPE", "[", "1", "]", ",", "num_class", ")", ",", "dtype", "=", "np", ".", "float32", ")", "for", "i", "in", "pos_ids", ":", "class_id", "=", "roi_gt_class_ids", "[", "i", "]", "assert", "class_id", ">", "0", ",", "\"class id must be greater than 0\"", "gt_id", "=", "roi_gt_assignment", "[", "i", "]", "class_mask", "=", "gt_masks", "[", ":", ",", ":", ",", "gt_id", "]", "if", "USE_MINI_MASK", ":", "# Create a mask placeholder, the size of the image", "placeholder", "=", "np", ".", "zeros", "(", "[", "IMAGE_DIM", ",", "IMAGE_DIM", "]", ",", "dtype", "=", "bool", ")", "# GT box", "gt_y1", ",", "gt_x1", ",", "gt_y2", ",", "gt_x2", "=", "gt_boxes", "[", "gt_id", "]", "gt_w", "=", "gt_x2", "-", "gt_x1", "gt_h", "=", "gt_y2", "-", "gt_y1", "# Resize mini mask to size of GT box", "placeholder", "[", "gt_y1", ":", "gt_y2", ",", "gt_x1", ":", "gt_x2", "]", "=", "np", ".", "round", "(", "skimage", ".", "transform", ".", "resize", "(", "class_mask", ",", "(", "gt_h", ",", "gt_w", ")", ",", "order", "=", "1", ",", "mode", "=", "\"constant\"", ")", ")", ".", "astype", "(", "bool", ")", "# Place the mini batch in the placeholder", "class_mask", "=", "placeholder", "# Pick part of the mask and resize it", "y1", ",", "x1", ",", "y2", ",", "x2", "=", "rois", "[", "i", "]", ".", "astype", "(", "np", ".", "int32", ")", "m", "=", "class_mask", "[", "y1", ":", "y2", ",", "x1", ":", "x2", "]", "mask", "=", "skimage", ".", "transform", ".", "resize", "(", "m", ",", "MASK_SHAPE", ",", "order", "=", "1", ",", "mode", "=", "\"constant\"", ")", "masks", "[", "i", ",", ":", ",", ":", ",", "class_id", "]", "=", "mask", "return", "rois", ",", "roi_gt_class_ids", ",", "bboxes", ",", "masks" ]
https://github.com/aianaconda/TensorFlow_Engineering_Implementation/blob/cb787e359da9ac5a08d00cd2458fecb4cb5a3a31/code/8-24 mask_rcnn_model.py#L1195-L1349
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_clusterrole.py
python
Rule.resources
(self)
return self.__resources
property for resources
property for resources
[ "property", "for", "resources" ]
def resources(self): '''property for resources''' if self.__resources is None: return [] return self.__resources
[ "def", "resources", "(", "self", ")", ":", "if", "self", ".", "__resources", "is", "None", ":", "return", "[", "]", "return", "self", ".", "__resources" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_clusterrole.py#L1514-L1519
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/data/data.py
python
BaseData.__getstate__
(self)
return self.__dict__
[]
def __getstate__(self) -> Dict[str, Any]: return self.__dict__
[ "def", "__getstate__", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "self", ".", "__dict__" ]
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/data/data.py#L118-L119
paramiko/paramiko
88f35a537428e430f7f26eee8026715e357b55d6
paramiko/message.py
python
Message.add_bytes
(self, b)
return self
Write bytes to the stream, without any formatting. :param str b: bytes to add
Write bytes to the stream, without any formatting.
[ "Write", "bytes", "to", "the", "stream", "without", "any", "formatting", "." ]
def add_bytes(self, b): """ Write bytes to the stream, without any formatting. :param str b: bytes to add """ self.packet.write(b) return self
[ "def", "add_bytes", "(", "self", ",", "b", ")", ":", "self", ".", "packet", ".", "write", "(", "b", ")", "return", "self" ]
https://github.com/paramiko/paramiko/blob/88f35a537428e430f7f26eee8026715e357b55d6/paramiko/message.py#L196-L203
google/trax
d6cae2067dedd0490b78d831033607357e975015
trax/data/text_encoder.py
python
ByteTextEncoder.vocab_size
(self)
return 2**8 + self._num_reserved_ids
[]
def vocab_size(self): return 2**8 + self._num_reserved_ids
[ "def", "vocab_size", "(", "self", ")", ":", "return", "2", "**", "8", "+", "self", ".", "_num_reserved_ids" ]
https://github.com/google/trax/blob/d6cae2067dedd0490b78d831033607357e975015/trax/data/text_encoder.py#L199-L200
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
mysite/profile/migrations/0028_copy_person_username_to_user_username.py
python
Migration.forwards
(self, orm)
Write your forwards migration here
Write your forwards migration here
[ "Write", "your", "forwards", "migration", "here" ]
def forwards(self, orm): "Write your forwards migration here" for person in orm.Person.objects.all(): user, was_user_created = orm['auth.User'].objects.get_or_create(username=person.username) person.user = user assert user.username == person.username if was_user_created: user.is_active = False user.save() person.save()
[ "def", "forwards", "(", "self", ",", "orm", ")", ":", "for", "person", "in", "orm", ".", "Person", ".", "objects", ".", "all", "(", ")", ":", "user", ",", "was_user_created", "=", "orm", "[", "'auth.User'", "]", ".", "objects", ".", "get_or_create", "(", "username", "=", "person", ".", "username", ")", "person", ".", "user", "=", "user", "assert", "user", ".", "username", "==", "person", ".", "username", "if", "was_user_created", ":", "user", ".", "is_active", "=", "False", "user", ".", "save", "(", ")", "person", ".", "save", "(", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/mysite/profile/migrations/0028_copy_person_username_to_user_username.py#L25-L35
goncalopp/simple-ocr-opencv
3af7530e5279cda2a8528cfbcbb57359eb20dd4f
simpleocr/segmentation_aux.py
python
contained_segments_matrix
(segments)
return a_inside_b
givens a n*n matrix m, n=len(segments), in which m[i,j] means segments[i] is contained inside segments[j]
givens a n*n matrix m, n=len(segments), in which m[i,j] means segments[i] is contained inside segments[j]
[ "givens", "a", "n", "*", "n", "matrix", "m", "n", "=", "len", "(", "segments", ")", "in", "which", "m", "[", "i", "j", "]", "means", "segments", "[", "i", "]", "is", "contained", "inside", "segments", "[", "j", "]" ]
def contained_segments_matrix(segments): """ givens a n*n matrix m, n=len(segments), in which m[i,j] means segments[i] is contained inside segments[j] """ x1, y1 = segments[:, 0], segments[:, 1] x2, y2 = x1 + segments[:, 2], y1 + segments[:, 3] n = len(segments) x1so, x2so, y1so, y2so = list(map(numpy.argsort, (x1, x2, y1, y2))) x1soi, x2soi, y1soi, y2soi = list(map(numpy.argsort, (x1so, x2so, y1so, y2so))) # inverse transformations # let rows be x1 and collumns be x2. this array represents where x1<x2 o1 = numpy.triu(numpy.ones((n, n)), k=1).astype(bool) # let rows be x1 and collumns be x2. this array represents where x1>x2 o2 = numpy.tril(numpy.ones((n, n)), k=0).astype(bool) a_inside_b_x = o2[x1soi][:, x1soi] * o1[x2soi][:, x2soi] # (x1[a]>x1[b] and x2[a]<x2[b]) a_inside_b_y = o2[y1soi][:, y1soi] * o1[y2soi][:, y2soi] # (y1[a]>y1[b] and y2[a]<y2[b]) a_inside_b = a_inside_b_x * a_inside_b_y return a_inside_b
[ "def", "contained_segments_matrix", "(", "segments", ")", ":", "x1", ",", "y1", "=", "segments", "[", ":", ",", "0", "]", ",", "segments", "[", ":", ",", "1", "]", "x2", ",", "y2", "=", "x1", "+", "segments", "[", ":", ",", "2", "]", ",", "y1", "+", "segments", "[", ":", ",", "3", "]", "n", "=", "len", "(", "segments", ")", "x1so", ",", "x2so", ",", "y1so", ",", "y2so", "=", "list", "(", "map", "(", "numpy", ".", "argsort", ",", "(", "x1", ",", "x2", ",", "y1", ",", "y2", ")", ")", ")", "x1soi", ",", "x2soi", ",", "y1soi", ",", "y2soi", "=", "list", "(", "map", "(", "numpy", ".", "argsort", ",", "(", "x1so", ",", "x2so", ",", "y1so", ",", "y2so", ")", ")", ")", "# inverse transformations", "# let rows be x1 and collumns be x2. this array represents where x1<x2", "o1", "=", "numpy", ".", "triu", "(", "numpy", ".", "ones", "(", "(", "n", ",", "n", ")", ")", ",", "k", "=", "1", ")", ".", "astype", "(", "bool", ")", "# let rows be x1 and collumns be x2. this array represents where x1>x2", "o2", "=", "numpy", ".", "tril", "(", "numpy", ".", "ones", "(", "(", "n", ",", "n", ")", ")", ",", "k", "=", "0", ")", ".", "astype", "(", "bool", ")", "a_inside_b_x", "=", "o2", "[", "x1soi", "]", "[", ":", ",", "x1soi", "]", "*", "o1", "[", "x2soi", "]", "[", ":", ",", "x2soi", "]", "# (x1[a]>x1[b] and x2[a]<x2[b])", "a_inside_b_y", "=", "o2", "[", "y1soi", "]", "[", ":", ",", "y1soi", "]", "*", "o1", "[", "y2soi", "]", "[", ":", ",", "y2soi", "]", "# (y1[a]>y1[b] and y2[a]<y2[b])", "a_inside_b", "=", "a_inside_b_x", "*", "a_inside_b_y", "return", "a_inside_b" ]
https://github.com/goncalopp/simple-ocr-opencv/blob/3af7530e5279cda2a8528cfbcbb57359eb20dd4f/simpleocr/segmentation_aux.py#L102-L120
Amulet-Team/Amulet-Core
a57aeaa4216806401ff35a2dba38782a35abc42e
amulet/api/selection/box.py
python
SelectionBox.touches
(self, other: SelectionBox)
return self.touches_or_intersects(other) and not self.intersects(other)
Method to check if this instance of :class:`SelectionBox` touches but does not intersect another SelectionBox. :param other: The other SelectionBox :return: True if the two :class:`SelectionBox` instances touch, False otherwise
Method to check if this instance of :class:`SelectionBox` touches but does not intersect another SelectionBox.
[ "Method", "to", "check", "if", "this", "instance", "of", ":", "class", ":", "SelectionBox", "touches", "but", "does", "not", "intersect", "another", "SelectionBox", "." ]
def touches(self, other: SelectionBox) -> bool: """ Method to check if this instance of :class:`SelectionBox` touches but does not intersect another SelectionBox. :param other: The other SelectionBox :return: True if the two :class:`SelectionBox` instances touch, False otherwise """ # It touches if the box does not intersect but intersects when expanded by one block. # There may be a simpler way to do this. return self.touches_or_intersects(other) and not self.intersects(other)
[ "def", "touches", "(", "self", ",", "other", ":", "SelectionBox", ")", "->", "bool", ":", "# It touches if the box does not intersect but intersects when expanded by one block.", "# There may be a simpler way to do this.", "return", "self", ".", "touches_or_intersects", "(", "other", ")", "and", "not", "self", ".", "intersects", "(", "other", ")" ]
https://github.com/Amulet-Team/Amulet-Core/blob/a57aeaa4216806401ff35a2dba38782a35abc42e/amulet/api/selection/box.py#L389-L398
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_13/pyasn1/type/univ.py
python
Real.__str__
(self)
return str(float(self))
[]
def __str__(self): return str(float(self))
[ "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "float", "(", "self", ")", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_13/pyasn1/type/univ.py#L573-L573
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/distlib/version.py
python
Version.__hash__
(self)
return hash(self._parts)
[]
def __hash__(self): return hash(self._parts)
[ "def", "__hash__", "(", "self", ")", ":", "return", "hash", "(", "self", ".", "_parts", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/distlib/version.py#L64-L65
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/flow_dto.py
python
FlowDTO.connections
(self, connections)
Sets the connections of this FlowDTO. The connections in this flow. :param connections: The connections of this FlowDTO. :type: list[ConnectionEntity]
Sets the connections of this FlowDTO. The connections in this flow.
[ "Sets", "the", "connections", "of", "this", "FlowDTO", ".", "The", "connections", "in", "this", "flow", "." ]
def connections(self, connections): """ Sets the connections of this FlowDTO. The connections in this flow. :param connections: The connections of this FlowDTO. :type: list[ConnectionEntity] """ self._connections = connections
[ "def", "connections", "(", "self", ",", "connections", ")", ":", "self", ".", "_connections", "=", "connections" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/flow_dto.py#L213-L222
dbolya/yolact
57b8f2d95e62e2e649b382f516ab41f949b57239
scripts/bbox_recall.py
python
jaccard
(box_a, box_b, iscrowd=False)
Compute the jaccard overlap of two sets of boxes. The jaccard overlap is simply the intersection over union of two boxes. Here we operate on ground truth boxes and default boxes. If iscrowd=True, put the crowd in box_b. E.g.: A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B) Args: box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4] box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4] Return: jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)]
Compute the jaccard overlap of two sets of boxes. The jaccard overlap is simply the intersection over union of two boxes. Here we operate on ground truth boxes and default boxes. If iscrowd=True, put the crowd in box_b. E.g.: A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B) Args: box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4] box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4] Return: jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)]
[ "Compute", "the", "jaccard", "overlap", "of", "two", "sets", "of", "boxes", ".", "The", "jaccard", "overlap", "is", "simply", "the", "intersection", "over", "union", "of", "two", "boxes", ".", "Here", "we", "operate", "on", "ground", "truth", "boxes", "and", "default", "boxes", ".", "If", "iscrowd", "=", "True", "put", "the", "crowd", "in", "box_b", ".", "E", ".", "g", ".", ":", "A", "∩", "B", "/", "A", "∪", "B", "=", "A", "∩", "B", "/", "(", "area", "(", "A", ")", "+", "area", "(", "B", ")", "-", "A", "∩", "B", ")", "Args", ":", "box_a", ":", "(", "tensor", ")", "Ground", "truth", "bounding", "boxes", "Shape", ":", "[", "num_objects", "4", "]", "box_b", ":", "(", "tensor", ")", "Prior", "boxes", "from", "priorbox", "layers", "Shape", ":", "[", "num_priors", "4", "]", "Return", ":", "jaccard", "overlap", ":", "(", "tensor", ")", "Shape", ":", "[", "box_a", ".", "size", "(", "0", ")", "box_b", ".", "size", "(", "0", ")", "]" ]
def jaccard(box_a, box_b, iscrowd=False): """Compute the jaccard overlap of two sets of boxes. The jaccard overlap is simply the intersection over union of two boxes. Here we operate on ground truth boxes and default boxes. If iscrowd=True, put the crowd in box_b. E.g.: A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B) Args: box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4] box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4] Return: jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)] """ inter = intersect(box_a, box_b) area_a = ((box_a[:, 2]-box_a[:, 0]) * (box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B] area_b = ((box_b[:, 2]-box_b[:, 0]) * (box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B] union = area_a + area_b - inter if iscrowd: return inter / area_a else: return inter / union
[ "def", "jaccard", "(", "box_a", ",", "box_b", ",", "iscrowd", "=", "False", ")", ":", "inter", "=", "intersect", "(", "box_a", ",", "box_b", ")", "area_a", "=", "(", "(", "box_a", "[", ":", ",", "2", "]", "-", "box_a", "[", ":", ",", "0", "]", ")", "*", "(", "box_a", "[", ":", ",", "3", "]", "-", "box_a", "[", ":", ",", "1", "]", ")", ")", ".", "unsqueeze", "(", "1", ")", ".", "expand_as", "(", "inter", ")", "# [A,B]", "area_b", "=", "(", "(", "box_b", "[", ":", ",", "2", "]", "-", "box_b", "[", ":", ",", "0", "]", ")", "*", "(", "box_b", "[", ":", ",", "3", "]", "-", "box_b", "[", ":", ",", "1", "]", ")", ")", ".", "unsqueeze", "(", "0", ")", ".", "expand_as", "(", "inter", ")", "# [A,B]", "union", "=", "area_a", "+", "area_b", "-", "inter", "if", "iscrowd", ":", "return", "inter", "/", "area_a", "else", ":", "return", "inter", "/", "union" ]
https://github.com/dbolya/yolact/blob/57b8f2d95e62e2e649b382f516ab41f949b57239/scripts/bbox_recall.py#L45-L67
wangzheng0822/algo
b2c1228ff915287ad7ebeae4355fa26854ea1557
python/40_dynamic_programming/yh_triangle.py
python
yh_triangle_bottom_up
(nums: List[Layer_nums])
return memo[0]
[]
def yh_triangle_bottom_up(nums: List[Layer_nums]) -> int: assert len(nums) > 0 n = len(nums) memo = nums[-1].copy() for i in range(n-1, 0, -1): for j in range(i): memo[j] = min(memo[j] + nums[i-1][j], memo[j+1] + nums[i-1][j]) return memo[0]
[ "def", "yh_triangle_bottom_up", "(", "nums", ":", "List", "[", "Layer_nums", "]", ")", "->", "int", ":", "assert", "len", "(", "nums", ")", ">", "0", "n", "=", "len", "(", "nums", ")", "memo", "=", "nums", "[", "-", "1", "]", ".", "copy", "(", ")", "for", "i", "in", "range", "(", "n", "-", "1", ",", "0", ",", "-", "1", ")", ":", "for", "j", "in", "range", "(", "i", ")", ":", "memo", "[", "j", "]", "=", "min", "(", "memo", "[", "j", "]", "+", "nums", "[", "i", "-", "1", "]", "[", "j", "]", ",", "memo", "[", "j", "+", "1", "]", "+", "nums", "[", "i", "-", "1", "]", "[", "j", "]", ")", "return", "memo", "[", "0", "]" ]
https://github.com/wangzheng0822/algo/blob/b2c1228ff915287ad7ebeae4355fa26854ea1557/python/40_dynamic_programming/yh_triangle.py#L49-L57
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/index.py
python
PackageFinder.find_all_candidates
(self, project_name)
return file_versions + find_links_versions + page_versions
Find all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See _link_package_versions for details on which files are accepted
Find all available InstallationCandidate for project_name
[ "Find", "all", "available", "InstallationCandidate", "for", "project_name" ]
def find_all_candidates(self, project_name): # type: (str) -> List[Optional[InstallationCandidate]] """Find all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See _link_package_versions for details on which files are accepted """ index_locations = self._get_index_urls_locations(project_name) index_file_loc, index_url_loc = self._sort_locations(index_locations) fl_file_loc, fl_url_loc = self._sort_locations( self.find_links, expand_dir=True, ) file_locations = (Link(url) for url in itertools.chain( index_file_loc, fl_file_loc, )) # We trust every url that the user has given us whether it was given # via --index-url or --find-links. # We want to filter out any thing which does not have a secure origin. url_locations = [ link for link in itertools.chain( (Link(url) for url in index_url_loc), (Link(url) for url in fl_url_loc), ) if self._validate_secure_origin(logger, link) ] logger.debug('%d location(s) to search for versions of %s:', len(url_locations), project_name) for location in url_locations: logger.debug('* %s', location) canonical_name = canonicalize_name(project_name) formats = self.format_control.get_allowed_formats(canonical_name) search = Search(project_name, canonical_name, formats) find_links_versions = self._package_versions( # We trust every directly linked archive in find_links (Link(url, '-f') for url in self.find_links), search ) page_versions = [] for page in self._get_pages(url_locations, project_name): logger.debug('Analyzing links from page %s', page.url) with indent_log(): page_versions.extend( self._package_versions(page.iter_links(), search) ) file_versions = self._package_versions(file_locations, search) if file_versions: file_versions.sort(reverse=True) logger.debug( 'Local files found: %s', ', '.join([ url_to_path(candidate.location.url) for candidate in file_versions ]) ) # This is an intentional priority ordering return file_versions + find_links_versions + page_versions
[ "def", "find_all_candidates", "(", "self", ",", "project_name", ")", ":", "# type: (str) -> List[Optional[InstallationCandidate]]", "index_locations", "=", "self", ".", "_get_index_urls_locations", "(", "project_name", ")", "index_file_loc", ",", "index_url_loc", "=", "self", ".", "_sort_locations", "(", "index_locations", ")", "fl_file_loc", ",", "fl_url_loc", "=", "self", ".", "_sort_locations", "(", "self", ".", "find_links", ",", "expand_dir", "=", "True", ",", ")", "file_locations", "=", "(", "Link", "(", "url", ")", "for", "url", "in", "itertools", ".", "chain", "(", "index_file_loc", ",", "fl_file_loc", ",", ")", ")", "# We trust every url that the user has given us whether it was given", "# via --index-url or --find-links.", "# We want to filter out any thing which does not have a secure origin.", "url_locations", "=", "[", "link", "for", "link", "in", "itertools", ".", "chain", "(", "(", "Link", "(", "url", ")", "for", "url", "in", "index_url_loc", ")", ",", "(", "Link", "(", "url", ")", "for", "url", "in", "fl_url_loc", ")", ",", ")", "if", "self", ".", "_validate_secure_origin", "(", "logger", ",", "link", ")", "]", "logger", ".", "debug", "(", "'%d location(s) to search for versions of %s:'", ",", "len", "(", "url_locations", ")", ",", "project_name", ")", "for", "location", "in", "url_locations", ":", "logger", ".", "debug", "(", "'* %s'", ",", "location", ")", "canonical_name", "=", "canonicalize_name", "(", "project_name", ")", "formats", "=", "self", ".", "format_control", ".", "get_allowed_formats", "(", "canonical_name", ")", "search", "=", "Search", "(", "project_name", ",", "canonical_name", ",", "formats", ")", "find_links_versions", "=", "self", ".", "_package_versions", "(", "# We trust every directly linked archive in find_links", "(", "Link", "(", "url", ",", "'-f'", ")", "for", "url", "in", "self", ".", "find_links", ")", ",", "search", ")", "page_versions", "=", "[", "]", "for", "page", "in", "self", ".", "_get_pages", "(", "url_locations", ",", "project_name", ")", ":", "logger", ".", "debug", "(", "'Analyzing links from page %s'", ",", "page", ".", "url", ")", "with", "indent_log", "(", ")", ":", "page_versions", ".", "extend", "(", "self", ".", "_package_versions", "(", "page", ".", "iter_links", "(", ")", ",", "search", ")", ")", "file_versions", "=", "self", ".", "_package_versions", "(", "file_locations", ",", "search", ")", "if", "file_versions", ":", "file_versions", ".", "sort", "(", "reverse", "=", "True", ")", "logger", ".", "debug", "(", "'Local files found: %s'", ",", "', '", ".", "join", "(", "[", "url_to_path", "(", "candidate", ".", "location", ".", "url", ")", "for", "candidate", "in", "file_versions", "]", ")", ")", "# This is an intentional priority ordering", "return", "file_versions", "+", "find_links_versions", "+", "page_versions" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/index.py#L564-L629
amimo/dcc
114326ab5a082a42c7728a375726489e4709ca29
androguard/core/bytecodes/axml/__init__.py
python
ARSCParser.get_resource_xml_name
(self, r_id, package=None)
Returns the XML name for a resource, including the package name if package is None. A full name might look like `@com.example:string/foobar` Otherwise the name is only looked up in the specified package and is returned without the package name. The same example from about without the package name will read as `@string/foobar`. If the ID could not be found, `None` is returned. A description of the XML name can be found here: https://developer.android.com/guide/topics/resources/providing-resources#ResourcesFromXml :param r_id: numerical ID if the resource :param package: package name :return: XML name identifier
Returns the XML name for a resource, including the package name if package is None. A full name might look like `@com.example:string/foobar` Otherwise the name is only looked up in the specified package and is returned without the package name. The same example from about without the package name will read as `@string/foobar`.
[ "Returns", "the", "XML", "name", "for", "a", "resource", "including", "the", "package", "name", "if", "package", "is", "None", ".", "A", "full", "name", "might", "look", "like", "@com", ".", "example", ":", "string", "/", "foobar", "Otherwise", "the", "name", "is", "only", "looked", "up", "in", "the", "specified", "package", "and", "is", "returned", "without", "the", "package", "name", ".", "The", "same", "example", "from", "about", "without", "the", "package", "name", "will", "read", "as", "@string", "/", "foobar", "." ]
def get_resource_xml_name(self, r_id, package=None): """ Returns the XML name for a resource, including the package name if package is None. A full name might look like `@com.example:string/foobar` Otherwise the name is only looked up in the specified package and is returned without the package name. The same example from about without the package name will read as `@string/foobar`. If the ID could not be found, `None` is returned. A description of the XML name can be found here: https://developer.android.com/guide/topics/resources/providing-resources#ResourcesFromXml :param r_id: numerical ID if the resource :param package: package name :return: XML name identifier """ if package: resource, name, i_id = self.get_id(package, r_id) if not i_id: return None return "@{}/{}".format(resource, name) else: for p in self.get_packages_names(): r, n, i_id = self.get_id(p, r_id) if i_id: # found the resource in this package package = p resource = r name = n break if not package: return None else: return "@{}:{}/{}".format(package, resource, name)
[ "def", "get_resource_xml_name", "(", "self", ",", "r_id", ",", "package", "=", "None", ")", ":", "if", "package", ":", "resource", ",", "name", ",", "i_id", "=", "self", ".", "get_id", "(", "package", ",", "r_id", ")", "if", "not", "i_id", ":", "return", "None", "return", "\"@{}/{}\"", ".", "format", "(", "resource", ",", "name", ")", "else", ":", "for", "p", "in", "self", ".", "get_packages_names", "(", ")", ":", "r", ",", "n", ",", "i_id", "=", "self", ".", "get_id", "(", "p", ",", "r_id", ")", "if", "i_id", ":", "# found the resource in this package", "package", "=", "p", "resource", "=", "r", "name", "=", "n", "break", "if", "not", "package", ":", "return", "None", "else", ":", "return", "\"@{}:{}/{}\"", ".", "format", "(", "package", ",", "resource", ",", "name", ")" ]
https://github.com/amimo/dcc/blob/114326ab5a082a42c7728a375726489e4709ca29/androguard/core/bytecodes/axml/__init__.py#L1978-L2012
bikalims/bika.lims
35e4bbdb5a3912cae0b5eb13e51097c8b0486349
bika/lims/content/attachmenttype.py
python
AttachmentType._renameAfterCreation
(self, check_auto_id=False)
[]
def _renameAfterCreation(self, check_auto_id=False): from bika.lims.idserver import renameAfterCreation renameAfterCreation(self)
[ "def", "_renameAfterCreation", "(", "self", ",", "check_auto_id", "=", "False", ")", ":", "from", "bika", ".", "lims", ".", "idserver", "import", "renameAfterCreation", "renameAfterCreation", "(", "self", ")" ]
https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/content/attachmenttype.py#L30-L32
sigmavirus24/github3.py
f642a27833d6bef93daf5bb27b35e5ddbcfbb773
src/github3/repos/repo.py
python
_Repository.milestones
( self, state=None, sort=None, direction=None, number=-1, etag=None )
return self._iter(int(number), url, milestone.Milestone, params, etag)
Iterate over the milestones on this repository. :param str state: (optional), state of the milestones, accepted values: ('open', 'closed') :param str sort: (optional), how to sort the milestones, accepted values: ('due_date', 'completeness') :param str direction: (optional), direction to sort the milestones, accepted values: ('asc', 'desc') :param int number: (optional), number of milestones to return. Default: -1 returns all milestones :param str etag: (optional), ETag from a previous request to the same endpoint :returns: generator of milestones :rtype: :class:`~github3.issues.milestone.Milestone`
Iterate over the milestones on this repository.
[ "Iterate", "over", "the", "milestones", "on", "this", "repository", "." ]
def milestones( self, state=None, sort=None, direction=None, number=-1, etag=None ): """Iterate over the milestones on this repository. :param str state: (optional), state of the milestones, accepted values: ('open', 'closed') :param str sort: (optional), how to sort the milestones, accepted values: ('due_date', 'completeness') :param str direction: (optional), direction to sort the milestones, accepted values: ('asc', 'desc') :param int number: (optional), number of milestones to return. Default: -1 returns all milestones :param str etag: (optional), ETag from a previous request to the same endpoint :returns: generator of milestones :rtype: :class:`~github3.issues.milestone.Milestone` """ url = self._build_url("milestones", base_url=self._api) accepted = { "state": ("open", "closed", "all"), "sort": ("due_date", "completeness"), "direction": ("asc", "desc"), } params = {"state": state, "sort": sort, "direction": direction} for (k, v) in list(params.items()): if not (v and (v in accepted[k])): # e.g., '' or None del params[k] if not params: params = None return self._iter(int(number), url, milestone.Milestone, params, etag)
[ "def", "milestones", "(", "self", ",", "state", "=", "None", ",", "sort", "=", "None", ",", "direction", "=", "None", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "url", "=", "self", ".", "_build_url", "(", "\"milestones\"", ",", "base_url", "=", "self", ".", "_api", ")", "accepted", "=", "{", "\"state\"", ":", "(", "\"open\"", ",", "\"closed\"", ",", "\"all\"", ")", ",", "\"sort\"", ":", "(", "\"due_date\"", ",", "\"completeness\"", ")", ",", "\"direction\"", ":", "(", "\"asc\"", ",", "\"desc\"", ")", ",", "}", "params", "=", "{", "\"state\"", ":", "state", ",", "\"sort\"", ":", "sort", ",", "\"direction\"", ":", "direction", "}", "for", "(", "k", ",", "v", ")", "in", "list", "(", "params", ".", "items", "(", ")", ")", ":", "if", "not", "(", "v", "and", "(", "v", "in", "accepted", "[", "k", "]", ")", ")", ":", "# e.g., '' or None", "del", "params", "[", "k", "]", "if", "not", "params", ":", "params", "=", "None", "return", "self", ".", "_iter", "(", "int", "(", "number", ")", ",", "url", ",", "milestone", ".", "Milestone", ",", "params", ",", "etag", ")" ]
https://github.com/sigmavirus24/github3.py/blob/f642a27833d6bef93daf5bb27b35e5ddbcfbb773/src/github3/repos/repo.py#L2238-L2274
rlworkgroup/garage
b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507
src/garage/sampler/multiprocessing_sampler.py
python
run_worker
(factory, to_worker, to_sampler, worker_number, agent, env)
Run the streaming worker state machine. Starts in the "not streaming" state. Enters the "streaming" state when the "start" or "continue" message is received. While in the "streaming" state, it streams episodes back to the parent process. When it receives a "stop" message, or the queue back to the parent process is full, it enters the "not streaming" state. When it receives the "exit" message, it terminates. Critically, the worker never blocks on sending messages back to the sampler, to ensure it remains responsive to messages. Args: factory (WorkerFactory): Pickleable factory for creating workers. Should be transmitted to other processes / nodes where work needs to be done, then workers should be constructed there. to_worker (multiprocessing.Queue): Queue to send commands to the worker. to_sampler (multiprocessing.Queue): Queue to send episodes back to the sampler. worker_number (int): Number of this worker. agent (Policy): Agent to use to sample episodes. If a list is passed in, it must have length exactly `worker_factory.n_workers`, and will be spread across the workers. env (Environment): Environment from which episodes are sampled. If a list is passed in, it must have length exactly `worker_factory.n_workers`, and will be spread across the workers. Raises: AssertionError: On internal errors.
Run the streaming worker state machine.
[ "Run", "the", "streaming", "worker", "state", "machine", "." ]
def run_worker(factory, to_worker, to_sampler, worker_number, agent, env): """Run the streaming worker state machine. Starts in the "not streaming" state. Enters the "streaming" state when the "start" or "continue" message is received. While in the "streaming" state, it streams episodes back to the parent process. When it receives a "stop" message, or the queue back to the parent process is full, it enters the "not streaming" state. When it receives the "exit" message, it terminates. Critically, the worker never blocks on sending messages back to the sampler, to ensure it remains responsive to messages. Args: factory (WorkerFactory): Pickleable factory for creating workers. Should be transmitted to other processes / nodes where work needs to be done, then workers should be constructed there. to_worker (multiprocessing.Queue): Queue to send commands to the worker. to_sampler (multiprocessing.Queue): Queue to send episodes back to the sampler. worker_number (int): Number of this worker. agent (Policy): Agent to use to sample episodes. If a list is passed in, it must have length exactly `worker_factory.n_workers`, and will be spread across the workers. env (Environment): Environment from which episodes are sampled. If a list is passed in, it must have length exactly `worker_factory.n_workers`, and will be spread across the workers. Raises: AssertionError: On internal errors. """ # When a python process is closing, multiprocessing Queues attempt to flush # their contents to the underlying pipe. If the pipe is full, they block # until someone reads from it. In this case, the to_sampler pipe may be # full (or nearly full), and never read from, causing this process to hang # forever. To avoid this, call cancel_join_thread, which will cause the # data to never be flushed to the pipe, allowing this process to end, and # the join on this process in the parent process to complete. # We call this immediately on process start in case this process crashes # (usually do to a bug or out-of-memory error in the underlying worker). to_sampler.cancel_join_thread() setproctitle.setproctitle('worker:' + setproctitle.getproctitle()) inner_worker = factory(worker_number) inner_worker.update_agent(cloudpickle.loads(agent)) inner_worker.update_env(env) version = 0 streaming_samples = False while True: if streaming_samples: # We're streaming, so try to get a message without waiting. If we # can't, the message is "continue", without any contents. try: tag, contents = to_worker.get_nowait() except queue.Empty: tag = 'continue' contents = None else: # We're not streaming anymore, so wait for a message. tag, contents = to_worker.get() if tag == 'start': # Update env and policy. agent_update, env_update, version = contents inner_worker.update_agent(cloudpickle.loads(agent_update)) inner_worker.update_env(env_update) streaming_samples = True elif tag == 'stop': streaming_samples = False elif tag == 'continue': batch = inner_worker.rollout() try: to_sampler.put_nowait( ('episode', (batch, version, worker_number))) except queue.Full: # Either the sampler has fallen far behind the workers, or we # missed a "stop" message. Either way, stop streaming. # If the queue becomes empty again, the sampler will send a # continue (or some other) message. streaming_samples = False elif tag == 'exit': to_worker.close() to_sampler.close() inner_worker.shutdown() return else: raise AssertionError('Unknown tag {} with contents {}'.format( tag, contents))
[ "def", "run_worker", "(", "factory", ",", "to_worker", ",", "to_sampler", ",", "worker_number", ",", "agent", ",", "env", ")", ":", "# When a python process is closing, multiprocessing Queues attempt to flush", "# their contents to the underlying pipe. If the pipe is full, they block", "# until someone reads from it. In this case, the to_sampler pipe may be", "# full (or nearly full), and never read from, causing this process to hang", "# forever. To avoid this, call cancel_join_thread, which will cause the", "# data to never be flushed to the pipe, allowing this process to end, and", "# the join on this process in the parent process to complete.", "# We call this immediately on process start in case this process crashes", "# (usually do to a bug or out-of-memory error in the underlying worker).", "to_sampler", ".", "cancel_join_thread", "(", ")", "setproctitle", ".", "setproctitle", "(", "'worker:'", "+", "setproctitle", ".", "getproctitle", "(", ")", ")", "inner_worker", "=", "factory", "(", "worker_number", ")", "inner_worker", ".", "update_agent", "(", "cloudpickle", ".", "loads", "(", "agent", ")", ")", "inner_worker", ".", "update_env", "(", "env", ")", "version", "=", "0", "streaming_samples", "=", "False", "while", "True", ":", "if", "streaming_samples", ":", "# We're streaming, so try to get a message without waiting. If we", "# can't, the message is \"continue\", without any contents.", "try", ":", "tag", ",", "contents", "=", "to_worker", ".", "get_nowait", "(", ")", "except", "queue", ".", "Empty", ":", "tag", "=", "'continue'", "contents", "=", "None", "else", ":", "# We're not streaming anymore, so wait for a message.", "tag", ",", "contents", "=", "to_worker", ".", "get", "(", ")", "if", "tag", "==", "'start'", ":", "# Update env and policy.", "agent_update", ",", "env_update", ",", "version", "=", "contents", "inner_worker", ".", "update_agent", "(", "cloudpickle", ".", "loads", "(", "agent_update", ")", ")", "inner_worker", ".", "update_env", "(", "env_update", ")", "streaming_samples", "=", "True", "elif", "tag", "==", "'stop'", ":", "streaming_samples", "=", "False", "elif", "tag", "==", "'continue'", ":", "batch", "=", "inner_worker", ".", "rollout", "(", ")", "try", ":", "to_sampler", ".", "put_nowait", "(", "(", "'episode'", ",", "(", "batch", ",", "version", ",", "worker_number", ")", ")", ")", "except", "queue", ".", "Full", ":", "# Either the sampler has fallen far behind the workers, or we", "# missed a \"stop\" message. Either way, stop streaming.", "# If the queue becomes empty again, the sampler will send a", "# continue (or some other) message.", "streaming_samples", "=", "False", "elif", "tag", "==", "'exit'", ":", "to_worker", ".", "close", "(", ")", "to_sampler", ".", "close", "(", ")", "inner_worker", ".", "shutdown", "(", ")", "return", "else", ":", "raise", "AssertionError", "(", "'Unknown tag {} with contents {}'", ".", "format", "(", "tag", ",", "contents", ")", ")" ]
https://github.com/rlworkgroup/garage/blob/b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507/src/garage/sampler/multiprocessing_sampler.py#L354-L447
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Tools/pybench/Lists.py
python
ListSlicing.test
(self)
[]
def test(self): n = range(100) r = range(25) for i in xrange(self.rounds): l = n[:] for j in r: m = l[50:] m = l[:25] m = l[50:55] l[:3] = n m = l[:-1] m = l[1:] l[-1:] = n
[ "def", "test", "(", "self", ")", ":", "n", "=", "range", "(", "100", ")", "r", "=", "range", "(", "25", ")", "for", "i", "in", "xrange", "(", "self", ".", "rounds", ")", ":", "l", "=", "n", "[", ":", "]", "for", "j", "in", "r", ":", "m", "=", "l", "[", "50", ":", "]", "m", "=", "l", "[", ":", "25", "]", "m", "=", "l", "[", "50", ":", "55", "]", "l", "[", ":", "3", "]", "=", "n", "m", "=", "l", "[", ":", "-", "1", "]", "m", "=", "l", "[", "1", ":", "]", "l", "[", "-", "1", ":", "]", "=", "n" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Tools/pybench/Lists.py#L139-L156
decalage2/ViperMonkey
631d242f43108226bb25ed91e773a274012dc8c2
vipermonkey/core/vba_object.py
python
get_cached_value
(arg)
return constant_expr_cache[arg_str]
Get the cached value of an all constant numeric expression if we have it.
Get the cached value of an all constant numeric expression if we have it.
[ "Get", "the", "cached", "value", "of", "an", "all", "constant", "numeric", "expression", "if", "we", "have", "it", "." ]
def get_cached_value(arg): """ Get the cached value of an all constant numeric expression if we have it. """ # Don't do any more work if this is already a resolved value. if (isinstance(arg, int) or isinstance(arg, dict)): return arg # If it is something that may be hard to convert to a string, no cached value. if contains_excel(arg): return None # This is not already resolved to an int. See if we computed this before. arg_str = str(arg) if (arg_str not in constant_expr_cache.keys()): return None return constant_expr_cache[arg_str]
[ "def", "get_cached_value", "(", "arg", ")", ":", "# Don't do any more work if this is already a resolved value.", "if", "(", "isinstance", "(", "arg", ",", "int", ")", "or", "isinstance", "(", "arg", ",", "dict", ")", ")", ":", "return", "arg", "# If it is something that may be hard to convert to a string, no cached value.", "if", "contains_excel", "(", "arg", ")", ":", "return", "None", "# This is not already resolved to an int. See if we computed this before.", "arg_str", "=", "str", "(", "arg", ")", "if", "(", "arg_str", "not", "in", "constant_expr_cache", ".", "keys", "(", ")", ")", ":", "return", "None", "return", "constant_expr_cache", "[", "arg_str", "]" ]
https://github.com/decalage2/ViperMonkey/blob/631d242f43108226bb25ed91e773a274012dc8c2/vipermonkey/core/vba_object.py#L426-L444
gdraheim/docker-systemctl-replacement
9cbe1a00eb4bdac6ff05b96ca34ec9ed3d8fc06c
docker_mirror.py
python
DockerMirrorPackagesRepo.get_docker_mirrors
(self, image)
return mirrors
attach local centos-repo / opensuse-repo to docker-start enviroment. Effectivly when it is required to 'docker start centos:x.y' then do 'docker start centos-repo:x.y' before and extend the original to 'docker start --add-host mirror...:centos-repo centos:x.y'.
attach local centos-repo / opensuse-repo to docker-start enviroment. Effectivly when it is required to 'docker start centos:x.y' then do 'docker start centos-repo:x.y' before and extend the original to 'docker start --add-host mirror...:centos-repo centos:x.y'.
[ "attach", "local", "centos", "-", "repo", "/", "opensuse", "-", "repo", "to", "docker", "-", "start", "enviroment", ".", "Effectivly", "when", "it", "is", "required", "to", "docker", "start", "centos", ":", "x", ".", "y", "then", "do", "docker", "start", "centos", "-", "repo", ":", "x", ".", "y", "before", "and", "extend", "the", "original", "to", "docker", "start", "--", "add", "-", "host", "mirror", "...", ":", "centos", "-", "repo", "centos", ":", "x", ".", "y", "." ]
def get_docker_mirrors(self, image): """ attach local centos-repo / opensuse-repo to docker-start enviroment. Effectivly when it is required to 'docker start centos:x.y' then do 'docker start centos-repo:x.y' before and extend the original to 'docker start --add-host mirror...:centos-repo centos:x.y'. """ mirrors = [] if image.startswith("centos:"): mirrors = self.get_centos_docker_mirrors(image) if ADDEPEL: if "centos" in image: mirrors += self.get_epel_docker_mirrors(image) if image.startswith("opensuse/leap:"): mirrors = self.get_opensuse_docker_mirrors(image) if image.startswith("opensuse:"): mirrors = self.get_opensuse_docker_mirrors(image) if image.startswith("ubuntu:"): mirrors = self.get_ubuntu_docker_mirrors(image) logg.info(" %s -> %s", image, " ".join([mirror.cname for mirror in mirrors])) return mirrors
[ "def", "get_docker_mirrors", "(", "self", ",", "image", ")", ":", "mirrors", "=", "[", "]", "if", "image", ".", "startswith", "(", "\"centos:\"", ")", ":", "mirrors", "=", "self", ".", "get_centos_docker_mirrors", "(", "image", ")", "if", "ADDEPEL", ":", "if", "\"centos\"", "in", "image", ":", "mirrors", "+=", "self", ".", "get_epel_docker_mirrors", "(", "image", ")", "if", "image", ".", "startswith", "(", "\"opensuse/leap:\"", ")", ":", "mirrors", "=", "self", ".", "get_opensuse_docker_mirrors", "(", "image", ")", "if", "image", ".", "startswith", "(", "\"opensuse:\"", ")", ":", "mirrors", "=", "self", ".", "get_opensuse_docker_mirrors", "(", "image", ")", "if", "image", ".", "startswith", "(", "\"ubuntu:\"", ")", ":", "mirrors", "=", "self", ".", "get_ubuntu_docker_mirrors", "(", "image", ")", "logg", ".", "info", "(", "\" %s -> %s\"", ",", "image", ",", "\" \"", ".", "join", "(", "[", "mirror", ".", "cname", "for", "mirror", "in", "mirrors", "]", ")", ")", "return", "mirrors" ]
https://github.com/gdraheim/docker-systemctl-replacement/blob/9cbe1a00eb4bdac6ff05b96ca34ec9ed3d8fc06c/docker_mirror.py#L222-L240
QuarkChain/pyquarkchain
af1dd06a50d918aaf45569d9b0f54f5ecceb6afe
quarkchain/protocol.py
python
Connection.close
(self)
Override AbstractConnection.close()
Override AbstractConnection.close()
[ "Override", "AbstractConnection", ".", "close", "()" ]
def close(self): """ Override AbstractConnection.close() """ self.writer.close() super().close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "writer", ".", "close", "(", ")", "super", "(", ")", ".", "close", "(", ")" ]
https://github.com/QuarkChain/pyquarkchain/blob/af1dd06a50d918aaf45569d9b0f54f5ecceb6afe/quarkchain/protocol.py#L291-L295
iopsgroup/imoocc
de810eb6d4c1697b7139305925a5b0ba21225f3f
scanhosts/modules/paramiko1_9/dsskey.py
python
DSSKey.generate
(bits=1024, progress_func=None)
return key
Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{DSSKey}
Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key.
[ "Generate", "a", "new", "private", "DSS", "key", ".", "This", "factory", "function", "can", "be", "used", "to", "generate", "a", "new", "host", "key", "or", "authentication", "key", "." ]
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{DSSKey} """ dsa = DSA.generate(bits, rng.read, progress_func) key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y)) key.x = dsa.x return key
[ "def", "generate", "(", "bits", "=", "1024", ",", "progress_func", "=", "None", ")", ":", "dsa", "=", "DSA", ".", "generate", "(", "bits", ",", "rng", ".", "read", ",", "progress_func", ")", "key", "=", "DSSKey", "(", "vals", "=", "(", "dsa", ".", "p", ",", "dsa", ".", "q", ",", "dsa", ".", "g", ",", "dsa", ".", "y", ")", ")", "key", ".", "x", "=", "dsa", ".", "x", "return", "key" ]
https://github.com/iopsgroup/imoocc/blob/de810eb6d4c1697b7139305925a5b0ba21225f3f/scanhosts/modules/paramiko1_9/dsskey.py#L151-L167
edgewall/trac
beb3e4eaf1e0a456d801a50a8614ecab06de29fc
trac/versioncontrol/api.py
python
Changeset.get_changes
(self)
Generator that produces a tuple for every change in the changeset. The tuple will contain `(path, kind, change, base_path, base_rev)`, where `change` can be one of Changeset.ADD, Changeset.COPY, Changeset.DELETE, Changeset.EDIT or Changeset.MOVE, and `kind` is one of Node.FILE or Node.DIRECTORY. The `path` is the targeted path for the `change` (which is the ''deleted'' path for a DELETE change). The `base_path` and `base_rev` are the source path and rev for the action (`None` and `-1` in the case of an ADD change).
Generator that produces a tuple for every change in the changeset.
[ "Generator", "that", "produces", "a", "tuple", "for", "every", "change", "in", "the", "changeset", "." ]
def get_changes(self): """Generator that produces a tuple for every change in the changeset. The tuple will contain `(path, kind, change, base_path, base_rev)`, where `change` can be one of Changeset.ADD, Changeset.COPY, Changeset.DELETE, Changeset.EDIT or Changeset.MOVE, and `kind` is one of Node.FILE or Node.DIRECTORY. The `path` is the targeted path for the `change` (which is the ''deleted'' path for a DELETE change). The `base_path` and `base_rev` are the source path and rev for the action (`None` and `-1` in the case of an ADD change). """ pass
[ "def", "get_changes", "(", "self", ")", ":", "pass" ]
https://github.com/edgewall/trac/blob/beb3e4eaf1e0a456d801a50a8614ecab06de29fc/trac/versioncontrol/api.py#L1299-L1311
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_load_balancer_ingress.py
python
V1LoadBalancerIngress.hostname
(self, hostname)
Sets the hostname of this V1LoadBalancerIngress. Hostname is set for load-balancer ingress points that are DNS based (typically AWS load-balancers) :param hostname: The hostname of this V1LoadBalancerIngress. :type: str
Sets the hostname of this V1LoadBalancerIngress. Hostname is set for load-balancer ingress points that are DNS based (typically AWS load-balancers)
[ "Sets", "the", "hostname", "of", "this", "V1LoadBalancerIngress", ".", "Hostname", "is", "set", "for", "load", "-", "balancer", "ingress", "points", "that", "are", "DNS", "based", "(", "typically", "AWS", "load", "-", "balancers", ")" ]
def hostname(self, hostname): """ Sets the hostname of this V1LoadBalancerIngress. Hostname is set for load-balancer ingress points that are DNS based (typically AWS load-balancers) :param hostname: The hostname of this V1LoadBalancerIngress. :type: str """ self._hostname = hostname
[ "def", "hostname", "(", "self", ",", "hostname", ")", ":", "self", ".", "_hostname", "=", "hostname" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_load_balancer_ingress.py#L58-L67
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
lts/ctp/__init__.py
python
TraderApi.Init
(self)
初始化 @remark 初始化运行环境,只有调用后,接口才开始工作
初始化
[ "初始化" ]
def Init(self): """初始化 @remark 初始化运行环境,只有调用后,接口才开始工作 """
[ "def", "Init", "(", "self", ")", ":" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/lts/ctp/__init__.py#L123-L126
jjhelmus/nmrglue
f47397dcda84854d2136395a9998fe0b57356cbf
nmrglue/fileio/sparky.py
python
write_2D
(filename, dic, data, overwrite=False)
return
Write a 2D Sparky file. See :py:func:`write` for documentation.
Write a 2D Sparky file. See :py:func:`write` for documentation.
[ "Write", "a", "2D", "Sparky", "file", ".", "See", ":", "py", ":", "func", ":", "write", "for", "documentation", "." ]
def write_2D(filename, dic, data, overwrite=False): """ Write a 2D Sparky file. See :py:func:`write` for documentation. """ # open the file for writing f = fileiobase.open_towrite(filename, overwrite) # write the file header put_fileheader(f, dic2fileheader(dic)) # write the axis headers put_axisheader(f, dic2axisheader(dic["w1"])) put_axisheader(f, dic2axisheader(dic["w2"])) lentX = dic["w2"]["bsize"] lentY = dic["w1"]["bsize"] t_tup = (lentY, lentX) ttX = int(np.ceil(data.shape[1] / float(lentX))) # total tiles in X dim ttY = int(np.ceil(data.shape[0] / float(lentY))) # total tiles in Y dim tt = ttX * ttY for i in range(int(tt)): put_data(f, find_tilen_2d(data, i, (t_tup))) f.close() return
[ "def", "write_2D", "(", "filename", ",", "dic", ",", "data", ",", "overwrite", "=", "False", ")", ":", "# open the file for writing", "f", "=", "fileiobase", ".", "open_towrite", "(", "filename", ",", "overwrite", ")", "# write the file header", "put_fileheader", "(", "f", ",", "dic2fileheader", "(", "dic", ")", ")", "# write the axis headers", "put_axisheader", "(", "f", ",", "dic2axisheader", "(", "dic", "[", "\"w1\"", "]", ")", ")", "put_axisheader", "(", "f", ",", "dic2axisheader", "(", "dic", "[", "\"w2\"", "]", ")", ")", "lentX", "=", "dic", "[", "\"w2\"", "]", "[", "\"bsize\"", "]", "lentY", "=", "dic", "[", "\"w1\"", "]", "[", "\"bsize\"", "]", "t_tup", "=", "(", "lentY", ",", "lentX", ")", "ttX", "=", "int", "(", "np", ".", "ceil", "(", "data", ".", "shape", "[", "1", "]", "/", "float", "(", "lentX", ")", ")", ")", "# total tiles in X dim", "ttY", "=", "int", "(", "np", ".", "ceil", "(", "data", ".", "shape", "[", "0", "]", "/", "float", "(", "lentY", ")", ")", ")", "# total tiles in Y dim", "tt", "=", "ttX", "*", "ttY", "for", "i", "in", "range", "(", "int", "(", "tt", ")", ")", ":", "put_data", "(", "f", ",", "find_tilen_2d", "(", "data", ",", "i", ",", "(", "t_tup", ")", ")", ")", "f", ".", "close", "(", ")", "return" ]
https://github.com/jjhelmus/nmrglue/blob/f47397dcda84854d2136395a9998fe0b57356cbf/nmrglue/fileio/sparky.py#L412-L438
wanggrun/Adaptively-Connected-Neural-Networks
e27066ef52301bdafa5932f43af8feeb23647edb
tensorpack-installed/tensorpack/graph_builder/training.py
python
DataParallelBuilder._check_grad_list
(grad_list)
Args: grad_list: list of list of tuples, shape is Ngpu x Nvar x 2
Args: grad_list: list of list of tuples, shape is Ngpu x Nvar x 2
[ "Args", ":", "grad_list", ":", "list", "of", "list", "of", "tuples", "shape", "is", "Ngpu", "x", "Nvar", "x", "2" ]
def _check_grad_list(grad_list): """ Args: grad_list: list of list of tuples, shape is Ngpu x Nvar x 2 """ nvars = [len(k) for k in grad_list] def basename(x): return re.sub('tower[0-9]+/', '', x.op.name) if len(set(nvars)) != 1: names_per_gpu = [set([basename(k[1]) for k in grad_and_vars]) for grad_and_vars in grad_list] inters = copy.copy(names_per_gpu[0]) for s in names_per_gpu: inters &= s for s in names_per_gpu: s -= inters logger.error("Unique trainable variables on towers: " + pprint.pformat(names_per_gpu)) raise ValueError("Number of gradients from each tower is different! " + str(nvars))
[ "def", "_check_grad_list", "(", "grad_list", ")", ":", "nvars", "=", "[", "len", "(", "k", ")", "for", "k", "in", "grad_list", "]", "def", "basename", "(", "x", ")", ":", "return", "re", ".", "sub", "(", "'tower[0-9]+/'", ",", "''", ",", "x", ".", "op", ".", "name", ")", "if", "len", "(", "set", "(", "nvars", ")", ")", "!=", "1", ":", "names_per_gpu", "=", "[", "set", "(", "[", "basename", "(", "k", "[", "1", "]", ")", "for", "k", "in", "grad_and_vars", "]", ")", "for", "grad_and_vars", "in", "grad_list", "]", "inters", "=", "copy", ".", "copy", "(", "names_per_gpu", "[", "0", "]", ")", "for", "s", "in", "names_per_gpu", ":", "inters", "&=", "s", "for", "s", "in", "names_per_gpu", ":", "s", "-=", "inters", "logger", ".", "error", "(", "\"Unique trainable variables on towers: \"", "+", "pprint", ".", "pformat", "(", "names_per_gpu", ")", ")", "raise", "ValueError", "(", "\"Number of gradients from each tower is different! \"", "+", "str", "(", "nvars", ")", ")" ]
https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/tensorpack-installed/tensorpack/graph_builder/training.py#L47-L65
timkpaine/pyEX
254acd2b0cf7cb7183100106f4ecc11d1860c46a
pyEX/refdata/symbols/equities.py
python
symbols
(token="", version="stable", filter="", format="json")
return _get( "ref-data/symbols", token=token, version=version, filter=filter, format=format )
This call returns an array of symbols that IEX Cloud supports for API calls. https://iexcloud.io/docs/api/#symbols 8am, 9am, 12pm, 1pm UTC daily Args: token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-results format (str): return format, defaults to json Returns: dict or DataFrame or list: result
This call returns an array of symbols that IEX Cloud supports for API calls.
[ "This", "call", "returns", "an", "array", "of", "symbols", "that", "IEX", "Cloud", "supports", "for", "API", "calls", "." ]
def symbols(token="", version="stable", filter="", format="json"): """This call returns an array of symbols that IEX Cloud supports for API calls. https://iexcloud.io/docs/api/#symbols 8am, 9am, 12pm, 1pm UTC daily Args: token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-results format (str): return format, defaults to json Returns: dict or DataFrame or list: result """ return _get( "ref-data/symbols", token=token, version=version, filter=filter, format=format )
[ "def", "symbols", "(", "token", "=", "\"\"", ",", "version", "=", "\"stable\"", ",", "filter", "=", "\"\"", ",", "format", "=", "\"json\"", ")", ":", "return", "_get", "(", "\"ref-data/symbols\"", ",", "token", "=", "token", ",", "version", "=", "version", ",", "filter", "=", "filter", ",", "format", "=", "format", ")" ]
https://github.com/timkpaine/pyEX/blob/254acd2b0cf7cb7183100106f4ecc11d1860c46a/pyEX/refdata/symbols/equities.py#L16-L33
pywinauto/pywinauto
7235e6f83edfd96a7aeb8bbf9fef7b8f3d912512
pywinauto/controls/common_controls.py
python
ToolbarWrapper.button
(self, button_identifier, exact=True, by_tooltip=False)
return _toolbar_button(button_index, self)
Return the button at index button_index
Return the button at index button_index
[ "Return", "the", "button", "at", "index", "button_index" ]
def button(self, button_identifier, exact=True, by_tooltip=False): """Return the button at index button_index""" if isinstance(button_identifier, six.string_types): texts = self.texts()[1:] self.actions.log('Toolbar buttons: ' + str(texts)) # one of these will be returned for the matching text indices = [i for i in range(0, len(texts))] if by_tooltip: texts = self.tip_texts() self.actions.log('Toolbar tooltips: ' + str(texts)) if exact: try: button_index = texts.index(button_identifier) except ValueError: raise findbestmatch.MatchError(items=texts, tofind=button_identifier) else: # find which index best matches that text button_index = findbestmatch.find_best_match(button_identifier, texts, indices) else: button_index = button_identifier return _toolbar_button(button_index, self)
[ "def", "button", "(", "self", ",", "button_identifier", ",", "exact", "=", "True", ",", "by_tooltip", "=", "False", ")", ":", "if", "isinstance", "(", "button_identifier", ",", "six", ".", "string_types", ")", ":", "texts", "=", "self", ".", "texts", "(", ")", "[", "1", ":", "]", "self", ".", "actions", ".", "log", "(", "'Toolbar buttons: '", "+", "str", "(", "texts", ")", ")", "# one of these will be returned for the matching text", "indices", "=", "[", "i", "for", "i", "in", "range", "(", "0", ",", "len", "(", "texts", ")", ")", "]", "if", "by_tooltip", ":", "texts", "=", "self", ".", "tip_texts", "(", ")", "self", ".", "actions", ".", "log", "(", "'Toolbar tooltips: '", "+", "str", "(", "texts", ")", ")", "if", "exact", ":", "try", ":", "button_index", "=", "texts", ".", "index", "(", "button_identifier", ")", "except", "ValueError", ":", "raise", "findbestmatch", ".", "MatchError", "(", "items", "=", "texts", ",", "tofind", "=", "button_identifier", ")", "else", ":", "# find which index best matches that text", "button_index", "=", "findbestmatch", ".", "find_best_match", "(", "button_identifier", ",", "texts", ",", "indices", ")", "else", ":", "button_index", "=", "button_identifier", "return", "_toolbar_button", "(", "button_index", ",", "self", ")" ]
https://github.com/pywinauto/pywinauto/blob/7235e6f83edfd96a7aeb8bbf9fef7b8f3d912512/pywinauto/controls/common_controls.py#L2458-L2481
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/pip/_internal/vcs/__init__.py
python
VersionControl.unpack
(self, location)
Clean up current location and download the url repository (and vcs infos) into location
Clean up current location and download the url repository (and vcs infos) into location
[ "Clean", "up", "current", "location", "and", "download", "the", "url", "repository", "(", "and", "vcs", "infos", ")", "into", "location" ]
def unpack(self, location): """ Clean up current location and download the url repository (and vcs infos) into location """ if os.path.exists(location): rmtree(location) self.obtain(location)
[ "def", "unpack", "(", "self", ",", "location", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "location", ")", ":", "rmtree", "(", "location", ")", "self", ".", "obtain", "(", "location", ")" ]
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_internal/vcs/__init__.py#L403-L410
hakril/PythonForWindows
61e027a678d5b87aa64fcf8a37a6661a86236589
windows/winproxy/apis/crypt32.py
python
CryptEncodeObjectEx
(dwCertEncodingType, lpszStructType, pvStructInfo, dwFlags, pEncodePara, pvEncoded, pcbEncoded)
return CryptEncodeObjectEx.ctypes_function(dwCertEncodingType, lpszStructType, pvStructInfo, dwFlags, pEncodePara, pvEncoded, pcbEncoded)
[]
def CryptEncodeObjectEx(dwCertEncodingType, lpszStructType, pvStructInfo, dwFlags, pEncodePara, pvEncoded, pcbEncoded): lpszStructType = gdef.LPCSTR(lpszStructType) if isinstance(lpszStructType, int_types) else lpszStructType return CryptEncodeObjectEx.ctypes_function(dwCertEncodingType, lpszStructType, pvStructInfo, dwFlags, pEncodePara, pvEncoded, pcbEncoded)
[ "def", "CryptEncodeObjectEx", "(", "dwCertEncodingType", ",", "lpszStructType", ",", "pvStructInfo", ",", "dwFlags", ",", "pEncodePara", ",", "pvEncoded", ",", "pcbEncoded", ")", ":", "lpszStructType", "=", "gdef", ".", "LPCSTR", "(", "lpszStructType", ")", "if", "isinstance", "(", "lpszStructType", ",", "int_types", ")", "else", "lpszStructType", "return", "CryptEncodeObjectEx", ".", "ctypes_function", "(", "dwCertEncodingType", ",", "lpszStructType", ",", "pvStructInfo", ",", "dwFlags", ",", "pEncodePara", ",", "pvEncoded", ",", "pcbEncoded", ")" ]
https://github.com/hakril/PythonForWindows/blob/61e027a678d5b87aa64fcf8a37a6661a86236589/windows/winproxy/apis/crypt32.py#L169-L171
junzis/pyModeS
00f04a88869c604bcadf80652c3f638166935c88
pyModeS/decoder/bds/bds53.py
python
is53
(msg)
return True
Check if a message is likely to be BDS code 5,3 (Air-referenced state vector) Args: msg (str): 28 hexdigits string Returns: bool: True or False
Check if a message is likely to be BDS code 5,3 (Air-referenced state vector)
[ "Check", "if", "a", "message", "is", "likely", "to", "be", "BDS", "code", "5", "3", "(", "Air", "-", "referenced", "state", "vector", ")" ]
def is53(msg): """Check if a message is likely to be BDS code 5,3 (Air-referenced state vector) Args: msg (str): 28 hexdigits string Returns: bool: True or False """ if common.allzeros(msg): return False d = common.hex2bin(common.data(msg)) # status bit 1, 13, 24, 34, 47 if common.wrongstatus(d, 1, 3, 12): return False if common.wrongstatus(d, 13, 14, 23): return False if common.wrongstatus(d, 24, 25, 33): return False if common.wrongstatus(d, 34, 35, 46): return False if common.wrongstatus(d, 47, 49, 56): return False ias = ias53(msg) if ias is not None and ias > 500: return False mach = mach53(msg) if mach is not None and mach > 1: return False tas = tas53(msg) if tas is not None and tas > 500: return False vr = vr53(msg) if vr is not None and abs(vr) > 8000: return False return True
[ "def", "is53", "(", "msg", ")", ":", "if", "common", ".", "allzeros", "(", "msg", ")", ":", "return", "False", "d", "=", "common", ".", "hex2bin", "(", "common", ".", "data", "(", "msg", ")", ")", "# status bit 1, 13, 24, 34, 47", "if", "common", ".", "wrongstatus", "(", "d", ",", "1", ",", "3", ",", "12", ")", ":", "return", "False", "if", "common", ".", "wrongstatus", "(", "d", ",", "13", ",", "14", ",", "23", ")", ":", "return", "False", "if", "common", ".", "wrongstatus", "(", "d", ",", "24", ",", "25", ",", "33", ")", ":", "return", "False", "if", "common", ".", "wrongstatus", "(", "d", ",", "34", ",", "35", ",", "46", ")", ":", "return", "False", "if", "common", ".", "wrongstatus", "(", "d", ",", "47", ",", "49", ",", "56", ")", ":", "return", "False", "ias", "=", "ias53", "(", "msg", ")", "if", "ias", "is", "not", "None", "and", "ias", ">", "500", ":", "return", "False", "mach", "=", "mach53", "(", "msg", ")", "if", "mach", "is", "not", "None", "and", "mach", ">", "1", ":", "return", "False", "tas", "=", "tas53", "(", "msg", ")", "if", "tas", "is", "not", "None", "and", "tas", ">", "500", ":", "return", "False", "vr", "=", "vr53", "(", "msg", ")", "if", "vr", "is", "not", "None", "and", "abs", "(", "vr", ")", ">", "8000", ":", "return", "False", "return", "True" ]
https://github.com/junzis/pyModeS/blob/00f04a88869c604bcadf80652c3f638166935c88/pyModeS/decoder/bds/bds53.py#L9-L58
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/netapi/rest_tornado/event_processor.py
python
SaltInfo.process_presence_events
(self, salt_data, token, opts)
Check if any minions have connected or dropped. Send a message to the client if they have.
Check if any minions have connected or dropped. Send a message to the client if they have.
[ "Check", "if", "any", "minions", "have", "connected", "or", "dropped", ".", "Send", "a", "message", "to", "the", "client", "if", "they", "have", "." ]
def process_presence_events(self, salt_data, token, opts): """ Check if any minions have connected or dropped. Send a message to the client if they have. """ log.debug("In presence") changed = False # check if any connections were dropped if set(salt_data["data"].get("lost", [])): dropped_minions = set(salt_data["data"].get("lost", [])) else: dropped_minions = set(self.minions) - set( salt_data["data"].get("present", []) ) for minion in dropped_minions: changed = True log.debug("Popping %s", minion) self.minions.pop(minion, None) # check if any new connections were made if set(salt_data["data"].get("new", [])): log.debug("got new minions") new_minions = set(salt_data["data"].get("new", [])) changed = True elif set(salt_data["data"].get("present", [])) - set(self.minions): log.debug("detected new minions") new_minions = set(salt_data["data"].get("present", [])) - set(self.minions) changed = True else: new_minions = [] tgt = ",".join(new_minions) for mid in new_minions: log.debug("Adding minion") self.minions[mid] = {} if tgt: changed = True client = salt.netapi.NetapiClient(opts) client.run( { "fun": "grains.items", "tgt": tgt, "expr_type": "list", "mode": "client", "client": "local", "asynchronous": "local_async", "token": token, } ) if changed: self.publish_minions()
[ "def", "process_presence_events", "(", "self", ",", "salt_data", ",", "token", ",", "opts", ")", ":", "log", ".", "debug", "(", "\"In presence\"", ")", "changed", "=", "False", "# check if any connections were dropped", "if", "set", "(", "salt_data", "[", "\"data\"", "]", ".", "get", "(", "\"lost\"", ",", "[", "]", ")", ")", ":", "dropped_minions", "=", "set", "(", "salt_data", "[", "\"data\"", "]", ".", "get", "(", "\"lost\"", ",", "[", "]", ")", ")", "else", ":", "dropped_minions", "=", "set", "(", "self", ".", "minions", ")", "-", "set", "(", "salt_data", "[", "\"data\"", "]", ".", "get", "(", "\"present\"", ",", "[", "]", ")", ")", "for", "minion", "in", "dropped_minions", ":", "changed", "=", "True", "log", ".", "debug", "(", "\"Popping %s\"", ",", "minion", ")", "self", ".", "minions", ".", "pop", "(", "minion", ",", "None", ")", "# check if any new connections were made", "if", "set", "(", "salt_data", "[", "\"data\"", "]", ".", "get", "(", "\"new\"", ",", "[", "]", ")", ")", ":", "log", ".", "debug", "(", "\"got new minions\"", ")", "new_minions", "=", "set", "(", "salt_data", "[", "\"data\"", "]", ".", "get", "(", "\"new\"", ",", "[", "]", ")", ")", "changed", "=", "True", "elif", "set", "(", "salt_data", "[", "\"data\"", "]", ".", "get", "(", "\"present\"", ",", "[", "]", ")", ")", "-", "set", "(", "self", ".", "minions", ")", ":", "log", ".", "debug", "(", "\"detected new minions\"", ")", "new_minions", "=", "set", "(", "salt_data", "[", "\"data\"", "]", ".", "get", "(", "\"present\"", ",", "[", "]", ")", ")", "-", "set", "(", "self", ".", "minions", ")", "changed", "=", "True", "else", ":", "new_minions", "=", "[", "]", "tgt", "=", "\",\"", ".", "join", "(", "new_minions", ")", "for", "mid", "in", "new_minions", ":", "log", ".", "debug", "(", "\"Adding minion\"", ")", "self", ".", "minions", "[", "mid", "]", "=", "{", "}", "if", "tgt", ":", "changed", "=", "True", "client", "=", "salt", ".", "netapi", ".", "NetapiClient", "(", "opts", ")", "client", ".", "run", "(", "{", "\"fun\"", ":", "\"grains.items\"", ",", "\"tgt\"", ":", "tgt", ",", "\"expr_type\"", ":", "\"list\"", ",", "\"mode\"", ":", "\"client\"", ",", "\"client\"", ":", "\"local\"", ",", "\"asynchronous\"", ":", "\"local_async\"", ",", "\"token\"", ":", "token", ",", "}", ")", "if", "changed", ":", "self", ".", "publish_minions", "(", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/netapi/rest_tornado/event_processor.py#L148-L202
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/pyxmpp2/expdict.py
python
ExpiringDictionary.expire
(self)
Do the expiration of dictionary items. Remove items that expired by now from the dictionary. :Return: time, in seconds, when the next item expires or `None` :returntype: `float`
Do the expiration of dictionary items.
[ "Do", "the", "expiration", "of", "dictionary", "items", "." ]
def expire(self): """Do the expiration of dictionary items. Remove items that expired by now from the dictionary. :Return: time, in seconds, when the next item expires or `None` :returntype: `float` """ with self._lock: logger.debug("expdict.expire. timeouts: {0!r}" .format(self._timeouts)) next_timeout = None for k in list(self._timeouts.keys()): ret = self._expire_item(k) if ret is not None: if next_timeout is None: next_timeout = ret else: next_timeout = min(next_timeout, ret) return next_timeout
[ "def", "expire", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "logger", ".", "debug", "(", "\"expdict.expire. timeouts: {0!r}\"", ".", "format", "(", "self", ".", "_timeouts", ")", ")", "next_timeout", "=", "None", "for", "k", "in", "list", "(", "self", ".", "_timeouts", ".", "keys", "(", ")", ")", ":", "ret", "=", "self", ".", "_expire_item", "(", "k", ")", "if", "ret", "is", "not", "None", ":", "if", "next_timeout", "is", "None", ":", "next_timeout", "=", "ret", "else", ":", "next_timeout", "=", "min", "(", "next_timeout", ",", "ret", ")", "return", "next_timeout" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/pyxmpp2/expdict.py#L112-L131
bbfamily/abu
2de85ae57923a720dac99a545b4f856f6b87304b
abupy/MetricsBu/ABuGridHelper.py
python
score_pd_plot
(grid_score_pd, y_key, x_key=None)
对最优结果score可视化,暂时未迁移完整,需迁移其余最优模块后可用
对最优结果score可视化,暂时未迁移完整,需迁移其余最优模块后可用
[ "对最优结果score可视化,暂时未迁移完整,需迁移其余最优模块后可用" ]
def score_pd_plot(grid_score_pd, y_key, x_key=None): """对最优结果score可视化,暂时未迁移完整,需迁移其余最优模块后可用""" if x_key is not None: xt = pd.crosstab(grid_score_pd[x_key], grid_score_pd[y_key]) xt_pct = xt.div(xt.sum(1).astype(float), axis=0) xt_pct.plot(kind='bar', stacked=True, title=str(x_key) + ' -> ' + str(y_key)) plt.xlabel(str(x_key)) plt.ylabel(str(y_key)) else: for col in grid_score_pd.columns: if col.startswith('Y_'): continue xt = pd.crosstab(grid_score_pd[col], grid_score_pd[y_key]) xt_pct = xt.div(xt.sum(1).astype(float), axis=0) xt_pct.plot(kind='bar', stacked=True, title=str(col) + ' -> ' + str(y_key)) plt.xlabel(str(col)) plt.ylabel(str(y_key)) plt.show()
[ "def", "score_pd_plot", "(", "grid_score_pd", ",", "y_key", ",", "x_key", "=", "None", ")", ":", "if", "x_key", "is", "not", "None", ":", "xt", "=", "pd", ".", "crosstab", "(", "grid_score_pd", "[", "x_key", "]", ",", "grid_score_pd", "[", "y_key", "]", ")", "xt_pct", "=", "xt", ".", "div", "(", "xt", ".", "sum", "(", "1", ")", ".", "astype", "(", "float", ")", ",", "axis", "=", "0", ")", "xt_pct", ".", "plot", "(", "kind", "=", "'bar'", ",", "stacked", "=", "True", ",", "title", "=", "str", "(", "x_key", ")", "+", "' -> '", "+", "str", "(", "y_key", ")", ")", "plt", ".", "xlabel", "(", "str", "(", "x_key", ")", ")", "plt", ".", "ylabel", "(", "str", "(", "y_key", ")", ")", "else", ":", "for", "col", "in", "grid_score_pd", ".", "columns", ":", "if", "col", ".", "startswith", "(", "'Y_'", ")", ":", "continue", "xt", "=", "pd", ".", "crosstab", "(", "grid_score_pd", "[", "col", "]", ",", "grid_score_pd", "[", "y_key", "]", ")", "xt_pct", "=", "xt", ".", "div", "(", "xt", ".", "sum", "(", "1", ")", ".", "astype", "(", "float", ")", ",", "axis", "=", "0", ")", "xt_pct", ".", "plot", "(", "kind", "=", "'bar'", ",", "stacked", "=", "True", ",", "title", "=", "str", "(", "col", ")", "+", "' -> '", "+", "str", "(", "y_key", ")", ")", "plt", ".", "xlabel", "(", "str", "(", "col", ")", ")", "plt", ".", "ylabel", "(", "str", "(", "y_key", ")", ")", "plt", ".", "show", "(", ")" ]
https://github.com/bbfamily/abu/blob/2de85ae57923a720dac99a545b4f856f6b87304b/abupy/MetricsBu/ABuGridHelper.py#L57-L78
GoogleChrome/chromium-dashboard
7ef9184080fc4cdf11efbe29dba27f95f07a20d9
framework/basehandlers.py
python
FlaskHandler.split_input
(self, field_name, delim='\\r?\\n')
return [x.strip() for x in re.split(delim, input_text) if x]
Split the input lines, strip whitespace, and skip blank lines.
Split the input lines, strip whitespace, and skip blank lines.
[ "Split", "the", "input", "lines", "strip", "whitespace", "and", "skip", "blank", "lines", "." ]
def split_input(self, field_name, delim='\\r?\\n'): """Split the input lines, strip whitespace, and skip blank lines.""" input_text = flask.request.form.get(field_name) or '' return [x.strip() for x in re.split(delim, input_text) if x]
[ "def", "split_input", "(", "self", ",", "field_name", ",", "delim", "=", "'\\\\r?\\\\n'", ")", ":", "input_text", "=", "flask", ".", "request", ".", "form", ".", "get", "(", "field_name", ")", "or", "''", "return", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "re", ".", "split", "(", "delim", ",", "input_text", ")", "if", "x", "]" ]
https://github.com/GoogleChrome/chromium-dashboard/blob/7ef9184080fc4cdf11efbe29dba27f95f07a20d9/framework/basehandlers.py#L399-L403
EmpireProject/EmPyre
c73854ed9d90d2bba1717d3fe6df758d18c20b8f
data/agent/agent.py
python
decompress.__init__
(self, verbose=False)
Populates init.
Populates init.
[ "Populates", "init", "." ]
def __init__(self, verbose=False): """ Populates init. """ pass
[ "def", "__init__", "(", "self", ",", "verbose", "=", "False", ")", ":", "pass" ]
https://github.com/EmpireProject/EmPyre/blob/c73854ed9d90d2bba1717d3fe6df758d18c20b8f/data/agent/agent.py#L640-L644
GoogleCloudPlatform/webapp2
deb34447ef8927c940bed2d80c7eec75f9f01be8
webapp2.py
python
RequestHandler.handle_exception
(self, exception, debug)
Called if this handler throws an exception during execution. The default behavior is to re-raise the exception to be handled by :meth:`WSGIApplication.handle_exception`. :param exception: The exception that was thrown. :param debug_mode: True if the web application is running in debug mode.
Called if this handler throws an exception during execution.
[ "Called", "if", "this", "handler", "throws", "an", "exception", "during", "execution", "." ]
def handle_exception(self, exception, debug): """Called if this handler throws an exception during execution. The default behavior is to re-raise the exception to be handled by :meth:`WSGIApplication.handle_exception`. :param exception: The exception that was thrown. :param debug_mode: True if the web application is running in debug mode. """ raise
[ "def", "handle_exception", "(", "self", ",", "exception", ",", "debug", ")", ":", "raise" ]
https://github.com/GoogleCloudPlatform/webapp2/blob/deb34447ef8927c940bed2d80c7eec75f9f01be8/webapp2.py#L675-L686
git-cola/git-cola
b48b8028e0c3baf47faf7b074b9773737358163d
cola/widgets/grep.py
python
Grep.__init__
(self, context, parent=None)
[]
def __init__(self, context, parent=None): Dialog.__init__(self, parent) self.context = context self.grep_result = '' self.setWindowTitle(N_('Search')) if parent is not None: self.setWindowModality(Qt.WindowModal) self.edit_action = qtutils.add_action(self, N_('Edit'), self.edit, hotkeys.EDIT) self.refresh_action = qtutils.add_action( self, N_('Refresh'), self.search, *hotkeys.REFRESH_HOTKEYS ) self.input_label = QtWidgets.QLabel('git grep') self.input_label.setFont(qtutils.diff_font(context)) self.input_txt = HintedLineEdit( context, N_('command-line arguments'), parent=self ) self.regexp_combo = combo = QtWidgets.QComboBox() combo.setToolTip(N_('Choose the "git grep" regular expression mode')) items = [N_('Basic Regexp'), N_('Extended Regexp'), N_('Fixed String')] combo.addItems(items) combo.setCurrentIndex(0) combo.setEditable(False) tooltip0 = N_('Search using a POSIX basic regular expression') tooltip1 = N_('Search using a POSIX extended regular expression') tooltip2 = N_('Search for a fixed string') combo.setItemData(0, tooltip0, Qt.ToolTipRole) combo.setItemData(1, tooltip1, Qt.ToolTipRole) combo.setItemData(2, tooltip2, Qt.ToolTipRole) combo.setItemData(0, '--basic-regexp', Qt.UserRole) combo.setItemData(1, '--extended-regexp', Qt.UserRole) combo.setItemData(2, '--fixed-strings', Qt.UserRole) self.result_txt = GrepTextView(context, N_('grep result...'), self) self.preview_txt = PreviewTextView(context, self) self.preview_txt.setFocusProxy(self.result_txt) self.edit_button = qtutils.edit_button(default=True) qtutils.button_action(self.edit_button, self.edit_action) self.refresh_button = qtutils.refresh_button() qtutils.button_action(self.refresh_button, self.refresh_action) text = N_('Shell arguments') tooltip = N_( 'Parse arguments using a shell.\n' 'Queries with spaces will require "double quotes".' ) self.shell_checkbox = qtutils.checkbox( text=text, tooltip=tooltip, checked=False ) self.close_button = qtutils.close_button() self.refresh_group = Group(self.refresh_action, self.refresh_button) self.refresh_group.setEnabled(False) self.edit_group = Group(self.edit_action, self.edit_button) self.edit_group.setEnabled(False) self.input_layout = qtutils.hbox( defs.no_margin, defs.button_spacing, self.input_label, self.input_txt, self.regexp_combo, ) self.bottom_layout = qtutils.hbox( defs.no_margin, defs.button_spacing, self.close_button, qtutils.STRETCH, self.shell_checkbox, self.refresh_button, self.edit_button, ) self.splitter = qtutils.splitter(Qt.Vertical, self.result_txt, self.preview_txt) self.mainlayout = qtutils.vbox( defs.margin, defs.no_spacing, self.input_layout, self.splitter, self.bottom_layout, ) self.setLayout(self.mainlayout) thread = self.worker_thread = GrepThread(context, self) thread.result.connect(self.process_result, type=Qt.QueuedConnection) # pylint: disable=no-member self.input_txt.textChanged.connect(lambda s: self.search()) self.regexp_combo.currentIndexChanged.connect(lambda x: self.search()) self.result_txt.leave.connect(self.input_txt.setFocus) self.result_txt.cursorPositionChanged.connect(self.update_preview) qtutils.add_action( self.input_txt, 'Focus Results', self.focus_results, hotkeys.DOWN, *hotkeys.ACCEPT ) qtutils.add_action(self, 'Focus Input', self.focus_input, hotkeys.FOCUS) qtutils.connect_toggle(self.shell_checkbox, lambda x: self.search()) qtutils.connect_button(self.close_button, self.close) qtutils.add_close_action(self) self.init_size(parent=parent)
[ "def", "__init__", "(", "self", ",", "context", ",", "parent", "=", "None", ")", ":", "Dialog", ".", "__init__", "(", "self", ",", "parent", ")", "self", ".", "context", "=", "context", "self", ".", "grep_result", "=", "''", "self", ".", "setWindowTitle", "(", "N_", "(", "'Search'", ")", ")", "if", "parent", "is", "not", "None", ":", "self", ".", "setWindowModality", "(", "Qt", ".", "WindowModal", ")", "self", ".", "edit_action", "=", "qtutils", ".", "add_action", "(", "self", ",", "N_", "(", "'Edit'", ")", ",", "self", ".", "edit", ",", "hotkeys", ".", "EDIT", ")", "self", ".", "refresh_action", "=", "qtutils", ".", "add_action", "(", "self", ",", "N_", "(", "'Refresh'", ")", ",", "self", ".", "search", ",", "*", "hotkeys", ".", "REFRESH_HOTKEYS", ")", "self", ".", "input_label", "=", "QtWidgets", ".", "QLabel", "(", "'git grep'", ")", "self", ".", "input_label", ".", "setFont", "(", "qtutils", ".", "diff_font", "(", "context", ")", ")", "self", ".", "input_txt", "=", "HintedLineEdit", "(", "context", ",", "N_", "(", "'command-line arguments'", ")", ",", "parent", "=", "self", ")", "self", ".", "regexp_combo", "=", "combo", "=", "QtWidgets", ".", "QComboBox", "(", ")", "combo", ".", "setToolTip", "(", "N_", "(", "'Choose the \"git grep\" regular expression mode'", ")", ")", "items", "=", "[", "N_", "(", "'Basic Regexp'", ")", ",", "N_", "(", "'Extended Regexp'", ")", ",", "N_", "(", "'Fixed String'", ")", "]", "combo", ".", "addItems", "(", "items", ")", "combo", ".", "setCurrentIndex", "(", "0", ")", "combo", ".", "setEditable", "(", "False", ")", "tooltip0", "=", "N_", "(", "'Search using a POSIX basic regular expression'", ")", "tooltip1", "=", "N_", "(", "'Search using a POSIX extended regular expression'", ")", "tooltip2", "=", "N_", "(", "'Search for a fixed string'", ")", "combo", ".", "setItemData", "(", "0", ",", "tooltip0", ",", "Qt", ".", "ToolTipRole", ")", "combo", ".", "setItemData", "(", "1", ",", "tooltip1", ",", "Qt", ".", "ToolTipRole", ")", "combo", ".", "setItemData", "(", "2", ",", "tooltip2", ",", "Qt", ".", "ToolTipRole", ")", "combo", ".", "setItemData", "(", "0", ",", "'--basic-regexp'", ",", "Qt", ".", "UserRole", ")", "combo", ".", "setItemData", "(", "1", ",", "'--extended-regexp'", ",", "Qt", ".", "UserRole", ")", "combo", ".", "setItemData", "(", "2", ",", "'--fixed-strings'", ",", "Qt", ".", "UserRole", ")", "self", ".", "result_txt", "=", "GrepTextView", "(", "context", ",", "N_", "(", "'grep result...'", ")", ",", "self", ")", "self", ".", "preview_txt", "=", "PreviewTextView", "(", "context", ",", "self", ")", "self", ".", "preview_txt", ".", "setFocusProxy", "(", "self", ".", "result_txt", ")", "self", ".", "edit_button", "=", "qtutils", ".", "edit_button", "(", "default", "=", "True", ")", "qtutils", ".", "button_action", "(", "self", ".", "edit_button", ",", "self", ".", "edit_action", ")", "self", ".", "refresh_button", "=", "qtutils", ".", "refresh_button", "(", ")", "qtutils", ".", "button_action", "(", "self", ".", "refresh_button", ",", "self", ".", "refresh_action", ")", "text", "=", "N_", "(", "'Shell arguments'", ")", "tooltip", "=", "N_", "(", "'Parse arguments using a shell.\\n'", "'Queries with spaces will require \"double quotes\".'", ")", "self", ".", "shell_checkbox", "=", "qtutils", ".", "checkbox", "(", "text", "=", "text", ",", "tooltip", "=", "tooltip", ",", "checked", "=", "False", ")", "self", ".", "close_button", "=", "qtutils", ".", "close_button", "(", ")", "self", ".", "refresh_group", "=", "Group", "(", "self", ".", "refresh_action", ",", "self", ".", "refresh_button", ")", "self", ".", "refresh_group", ".", "setEnabled", "(", "False", ")", "self", ".", "edit_group", "=", "Group", "(", "self", ".", "edit_action", ",", "self", ".", "edit_button", ")", "self", ".", "edit_group", ".", "setEnabled", "(", "False", ")", "self", ".", "input_layout", "=", "qtutils", ".", "hbox", "(", "defs", ".", "no_margin", ",", "defs", ".", "button_spacing", ",", "self", ".", "input_label", ",", "self", ".", "input_txt", ",", "self", ".", "regexp_combo", ",", ")", "self", ".", "bottom_layout", "=", "qtutils", ".", "hbox", "(", "defs", ".", "no_margin", ",", "defs", ".", "button_spacing", ",", "self", ".", "close_button", ",", "qtutils", ".", "STRETCH", ",", "self", ".", "shell_checkbox", ",", "self", ".", "refresh_button", ",", "self", ".", "edit_button", ",", ")", "self", ".", "splitter", "=", "qtutils", ".", "splitter", "(", "Qt", ".", "Vertical", ",", "self", ".", "result_txt", ",", "self", ".", "preview_txt", ")", "self", ".", "mainlayout", "=", "qtutils", ".", "vbox", "(", "defs", ".", "margin", ",", "defs", ".", "no_spacing", ",", "self", ".", "input_layout", ",", "self", ".", "splitter", ",", "self", ".", "bottom_layout", ",", ")", "self", ".", "setLayout", "(", "self", ".", "mainlayout", ")", "thread", "=", "self", ".", "worker_thread", "=", "GrepThread", "(", "context", ",", "self", ")", "thread", ".", "result", ".", "connect", "(", "self", ".", "process_result", ",", "type", "=", "Qt", ".", "QueuedConnection", ")", "# pylint: disable=no-member", "self", ".", "input_txt", ".", "textChanged", ".", "connect", "(", "lambda", "s", ":", "self", ".", "search", "(", ")", ")", "self", ".", "regexp_combo", ".", "currentIndexChanged", ".", "connect", "(", "lambda", "x", ":", "self", ".", "search", "(", ")", ")", "self", ".", "result_txt", ".", "leave", ".", "connect", "(", "self", ".", "input_txt", ".", "setFocus", ")", "self", ".", "result_txt", ".", "cursorPositionChanged", ".", "connect", "(", "self", ".", "update_preview", ")", "qtutils", ".", "add_action", "(", "self", ".", "input_txt", ",", "'Focus Results'", ",", "self", ".", "focus_results", ",", "hotkeys", ".", "DOWN", ",", "*", "hotkeys", ".", "ACCEPT", ")", "qtutils", ".", "add_action", "(", "self", ",", "'Focus Input'", ",", "self", ".", "focus_input", ",", "hotkeys", ".", "FOCUS", ")", "qtutils", ".", "connect_toggle", "(", "self", ".", "shell_checkbox", ",", "lambda", "x", ":", "self", ".", "search", "(", ")", ")", "qtutils", ".", "connect_button", "(", "self", ".", "close_button", ",", "self", ".", "close", ")", "qtutils", ".", "add_close_action", "(", "self", ")", "self", ".", "init_size", "(", "parent", "=", "parent", ")" ]
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/widgets/grep.py#L93-L209
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/Django-1.11.29/django/forms/models.py
python
BaseModelFormSet.add_fields
(self, form, index)
Add a hidden field for the object's primary key.
Add a hidden field for the object's primary key.
[ "Add", "a", "hidden", "field", "for", "the", "object", "s", "primary", "key", "." ]
def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, OneToOneField, ForeignKey self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it here so we can tell which object is which when we get the # data back. Generally, pk.editable should be false, but for some # reason, auto_created pk fields and AutoField's editable attribute is # True, so check for that as well. def pk_is_not_editable(pk): return ( (not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or ( pk.remote_field and pk.remote_field.parent_link and pk_is_not_editable(pk.remote_field.model._meta.pk) ) ) if pk_is_not_editable(pk) or pk.name not in form.fields: if form.is_bound: # If we're adding the related instance, ignore its primary key # as it could be an auto-generated default which isn't actually # in the database. pk_value = None if form.instance._state.adding else form.instance.pk else: try: if index is not None: pk_value = self.get_queryset()[index].pk else: pk_value = None except IndexError: pk_value = None if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey): qs = pk.remote_field.model._default_manager.get_queryset() else: qs = self.model._default_manager.get_queryset() qs = qs.using(form.instance._state.db) if form._meta.widgets: widget = form._meta.widgets.get(self._pk_field.name, HiddenInput) else: widget = HiddenInput form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget) super(BaseModelFormSet, self).add_fields(form, index)
[ "def", "add_fields", "(", "self", ",", "form", ",", "index", ")", ":", "from", "django", ".", "db", ".", "models", "import", "AutoField", ",", "OneToOneField", ",", "ForeignKey", "self", ".", "_pk_field", "=", "pk", "=", "self", ".", "model", ".", "_meta", ".", "pk", "# If a pk isn't editable, then it won't be on the form, so we need to", "# add it here so we can tell which object is which when we get the", "# data back. Generally, pk.editable should be false, but for some", "# reason, auto_created pk fields and AutoField's editable attribute is", "# True, so check for that as well.", "def", "pk_is_not_editable", "(", "pk", ")", ":", "return", "(", "(", "not", "pk", ".", "editable", ")", "or", "(", "pk", ".", "auto_created", "or", "isinstance", "(", "pk", ",", "AutoField", ")", ")", "or", "(", "pk", ".", "remote_field", "and", "pk", ".", "remote_field", ".", "parent_link", "and", "pk_is_not_editable", "(", "pk", ".", "remote_field", ".", "model", ".", "_meta", ".", "pk", ")", ")", ")", "if", "pk_is_not_editable", "(", "pk", ")", "or", "pk", ".", "name", "not", "in", "form", ".", "fields", ":", "if", "form", ".", "is_bound", ":", "# If we're adding the related instance, ignore its primary key", "# as it could be an auto-generated default which isn't actually", "# in the database.", "pk_value", "=", "None", "if", "form", ".", "instance", ".", "_state", ".", "adding", "else", "form", ".", "instance", ".", "pk", "else", ":", "try", ":", "if", "index", "is", "not", "None", ":", "pk_value", "=", "self", ".", "get_queryset", "(", ")", "[", "index", "]", ".", "pk", "else", ":", "pk_value", "=", "None", "except", "IndexError", ":", "pk_value", "=", "None", "if", "isinstance", "(", "pk", ",", "OneToOneField", ")", "or", "isinstance", "(", "pk", ",", "ForeignKey", ")", ":", "qs", "=", "pk", ".", "remote_field", ".", "model", ".", "_default_manager", ".", "get_queryset", "(", ")", "else", ":", "qs", "=", "self", ".", "model", ".", "_default_manager", ".", "get_queryset", "(", ")", "qs", "=", "qs", ".", "using", "(", "form", ".", "instance", ".", "_state", ".", "db", ")", "if", "form", ".", "_meta", ".", "widgets", ":", "widget", "=", "form", ".", "_meta", ".", "widgets", ".", "get", "(", "self", ".", "_pk_field", ".", "name", ",", "HiddenInput", ")", "else", ":", "widget", "=", "HiddenInput", "form", ".", "fields", "[", "self", ".", "_pk_field", ".", "name", "]", "=", "ModelChoiceField", "(", "qs", ",", "initial", "=", "pk_value", ",", "required", "=", "False", ",", "widget", "=", "widget", ")", "super", "(", "BaseModelFormSet", ",", "self", ")", ".", "add_fields", "(", "form", ",", "index", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/forms/models.py#L805-L846
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/xml/dom/pulldom.py
python
PullDOM.__init__
(self, documentFactory=None)
[]
def __init__(self, documentFactory=None): from xml.dom import XML_NAMESPACE self.documentFactory = documentFactory self.firstEvent = [None, None] self.lastEvent = self.firstEvent self.elementStack = [] self.push = self.elementStack.append try: self.pop = self.elementStack.pop except AttributeError: # use class' pop instead pass self._ns_contexts = [{XML_NAMESPACE:'xml'}] # contains uri -> prefix dicts self._current_context = self._ns_contexts[-1] self.pending_events = []
[ "def", "__init__", "(", "self", ",", "documentFactory", "=", "None", ")", ":", "from", "xml", ".", "dom", "import", "XML_NAMESPACE", "self", ".", "documentFactory", "=", "documentFactory", "self", ".", "firstEvent", "=", "[", "None", ",", "None", "]", "self", ".", "lastEvent", "=", "self", ".", "firstEvent", "self", ".", "elementStack", "=", "[", "]", "self", ".", "push", "=", "self", ".", "elementStack", ".", "append", "try", ":", "self", ".", "pop", "=", "self", ".", "elementStack", ".", "pop", "except", "AttributeError", ":", "# use class' pop instead", "pass", "self", ".", "_ns_contexts", "=", "[", "{", "XML_NAMESPACE", ":", "'xml'", "}", "]", "# contains uri -> prefix dicts", "self", ".", "_current_context", "=", "self", ".", "_ns_contexts", "[", "-", "1", "]", "self", ".", "pending_events", "=", "[", "]" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/xml/dom/pulldom.py#L18-L32
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
chap19/monitor/python-monitorclient-1.1/build/lib.linux-x86_64-2.7/monitorclient/middleware/auth_token.py
python
AuthProtocol._get_cache_key
(self, token)
return 'tokens/%s' % htoken
Return the cache key. Do not use clear token as key if memcache protection is on.
Return the cache key.
[ "Return", "the", "cache", "key", "." ]
def _get_cache_key(self, token): """ Return the cache key. Do not use clear token as key if memcache protection is on. """ htoken = token if self._memcache_security_strategy in ('ENCRYPT', 'MAC'): derv_token = token + self._memcache_secret_key htoken = memcache_crypt.hash_data(derv_token) return 'tokens/%s' % htoken
[ "def", "_get_cache_key", "(", "self", ",", "token", ")", ":", "htoken", "=", "token", "if", "self", ".", "_memcache_security_strategy", "in", "(", "'ENCRYPT'", ",", "'MAC'", ")", ":", "derv_token", "=", "token", "+", "self", ".", "_memcache_secret_key", "htoken", "=", "memcache_crypt", ".", "hash_data", "(", "derv_token", ")", "return", "'tokens/%s'", "%", "htoken" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/chap19/monitor/python-monitorclient-1.1/build/lib.linux-x86_64-2.7/monitorclient/middleware/auth_token.py#L919-L929
roam-qgis/Roam
6bfa836a2735f611b7f26de18ae4a4581f7e83ef
src/roam/api/gps.py
python
GPSService.gpsfound_handler
(self, gpsConnection)
Handler for when the GPS signal has been found :param gpsConnection: The connection for the GPS :return: None
Handler for when the GPS signal has been found :param gpsConnection: The connection for the GPS :return: None
[ "Handler", "for", "when", "the", "GPS", "signal", "has", "been", "found", ":", "param", "gpsConnection", ":", "The", "connection", "for", "the", "GPS", ":", "return", ":", "None" ]
def gpsfound_handler(self, gpsConnection) -> None: """ Handler for when the GPS signal has been found :param gpsConnection: The connection for the GPS :return: None """ if not isinstance(gpsConnection, QgsNmeaConnection): # This can be hit if the scan is used as the bindings in QGIS aren't # right and will not have the type set correctly import sip gpsConnection = sip.cast(gpsConnection, QgsGpsConnection) self.gpsConn = gpsConnection self.gpsConn.stateChanged.connect(self.gpsStateChanged) self.gpsConn.nmeaSentenceReceived.connect(self.parse_data) self.connected = True
[ "def", "gpsfound_handler", "(", "self", ",", "gpsConnection", ")", "->", "None", ":", "if", "not", "isinstance", "(", "gpsConnection", ",", "QgsNmeaConnection", ")", ":", "# This can be hit if the scan is used as the bindings in QGIS aren't", "# right and will not have the type set correctly", "import", "sip", "gpsConnection", "=", "sip", ".", "cast", "(", "gpsConnection", ",", "QgsGpsConnection", ")", "self", ".", "gpsConn", "=", "gpsConnection", "self", ".", "gpsConn", ".", "stateChanged", ".", "connect", "(", "self", ".", "gpsStateChanged", ")", "self", ".", "gpsConn", ".", "nmeaSentenceReceived", ".", "connect", "(", "self", ".", "parse_data", ")", "self", ".", "connected", "=", "True" ]
https://github.com/roam-qgis/Roam/blob/6bfa836a2735f611b7f26de18ae4a4581f7e83ef/src/roam/api/gps.py#L202-L217
xgi/castero
766965fb1d3586d62ab6fd6dd144fa510c1e0ecb
castero/display.py
python
Display.modified_episodes
(self)
return self._modified_episodes
List[Episode]: database episodes to save on the next update
List[Episode]: database episodes to save on the next update
[ "List", "[", "Episode", "]", ":", "database", "episodes", "to", "save", "on", "the", "next", "update" ]
def modified_episodes(self) -> List[Episode]: """List[Episode]: database episodes to save on the next update""" return self._modified_episodes
[ "def", "modified_episodes", "(", "self", ")", "->", "List", "[", "Episode", "]", ":", "return", "self", ".", "_modified_episodes" ]
https://github.com/xgi/castero/blob/766965fb1d3586d62ab6fd6dd144fa510c1e0ecb/castero/display.py#L801-L803
packetloop/packetpig
6e101090224df219123ff5f6ab4c37524637571f
lib/scripts/impacket/impacket/dot11.py
python
Dot11DataFrame.set_sequence_control
(self, value)
Set the 802.11 \'Data\' data frame \'Sequence Control\' field
Set the 802.11 \'Data\' data frame \'Sequence Control\' field
[ "Set", "the", "802", ".", "11", "\\", "Data", "\\", "data", "frame", "\\", "Sequence", "Control", "\\", "field" ]
def set_sequence_control(self, value): 'Set the 802.11 \'Data\' data frame \'Sequence Control\' field' # set the bits nb = value & 0xFFFF self.header.set_word(20, nb, "<")
[ "def", "set_sequence_control", "(", "self", ",", "value", ")", ":", "# set the bits", "nb", "=", "value", "&", "0xFFFF", "self", ".", "header", ".", "set_word", "(", "20", ",", "nb", ",", "\"<\"", ")" ]
https://github.com/packetloop/packetpig/blob/6e101090224df219123ff5f6ab4c37524637571f/lib/scripts/impacket/impacket/dot11.py#L799-L803
ynvb/DIE
453fbdf137bfe0510e760df73441d41d35ea74d6
DIE/Lib/DataParser.py
python
DataParser.get_parser_list
(self)
return parser_list
Query available parsers @return: Returns a dictionary of all available parsers and their data. The dictionary key is the parser name, and value is a list of available data in the following format: Plugin1 -> [Plugin1 Description, Plugin1 Version, Plugin2 -> [Plugin2 Description, Plugin2 Version, ...] A special key named "headers" represents the type names of the returned columns
Query available parsers
[ "Query", "available", "parsers" ]
def get_parser_list(self): """ Query available parsers @return: Returns a dictionary of all available parsers and their data. The dictionary key is the parser name, and value is a list of available data in the following format: Plugin1 -> [Plugin1 Description, Plugin1 Version, Plugin2 -> [Plugin2 Description, Plugin2 Version, ...] A special key named "headers" represents the type names of the returned columns """ parser_list = {} # TODO: use classes or named tuples parser_list["headers"] = ["Description", "Version", "State", "Author"] for plugin in self.pManager.getAllPlugins(): parser_list[plugin.name] = [plugin.description, plugin.version, plugin.is_activated, plugin.author] return parser_list
[ "def", "get_parser_list", "(", "self", ")", ":", "parser_list", "=", "{", "}", "# TODO: use classes or named tuples", "parser_list", "[", "\"headers\"", "]", "=", "[", "\"Description\"", ",", "\"Version\"", ",", "\"State\"", ",", "\"Author\"", "]", "for", "plugin", "in", "self", ".", "pManager", ".", "getAllPlugins", "(", ")", ":", "parser_list", "[", "plugin", ".", "name", "]", "=", "[", "plugin", ".", "description", ",", "plugin", ".", "version", ",", "plugin", ".", "is_activated", ",", "plugin", ".", "author", "]", "return", "parser_list" ]
https://github.com/ynvb/DIE/blob/453fbdf137bfe0510e760df73441d41d35ea74d6/DIE/Lib/DataParser.py#L104-L121
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/pydoc.py
python
cli
()
Command-line interface (looks at sys.argv to decide what to do).
Command-line interface (looks at sys.argv to decide what to do).
[ "Command", "-", "line", "interface", "(", "looks", "at", "sys", ".", "argv", "to", "decide", "what", "to", "do", ")", "." ]
def cli(): """Command-line interface (looks at sys.argv to decide what to do).""" import getopt class BadUsage: pass # Scripts don't get the current directory in their path by default # unless they are run with the '-m' switch if '' not in sys.path: scriptdir = os.path.dirname(sys.argv[0]) if scriptdir in sys.path: sys.path.remove(scriptdir) sys.path.insert(0, '.') try: opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w') writing = 0 for opt, val in opts: if opt == '-g': gui() return if opt == '-k': apropos(val) return if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(server): print 'pydoc server ready at %s' % server.url def stopped(): print 'pydoc server stopped' serve(port, ready, stopped) return if opt == '-w': writing = 1 if not args: raise BadUsage for arg in args: if ispath(arg) and not os.path.exists(arg): print 'file %r does not exist' % arg break try: if ispath(arg) and os.path.isfile(arg): arg = importfile(arg) if writing: if ispath(arg) and os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: help.help(arg) except ErrorDuringImport, value: print value except (getopt.error, BadUsage): cmd = os.path.basename(sys.argv[0]) print """pydoc - the Python documentation tool %s <name> ... Show text documentation on something. <name> may be the name of a Python keyword, topic, function, module, or package, or a dotted reference to a class or function within a module or module in a package. If <name> contains a '%s', it is used as the path to a Python source file to document. If name is 'keywords', 'topics', or 'modules', a listing of these things is displayed. %s -k <keyword> Search for a keyword in the synopsis lines of all available modules. %s -p <port> Start an HTTP server on the given port on the local machine. Port number 0 can be used to get an arbitrary unused port. %s -g Pop up a graphical interface for finding and serving documentation. %s -w <name> ... Write out the HTML documentation for a module to a file in the current directory. If <name> contains a '%s', it is treated as a filename; if it names a directory, documentation is written for all the contents. """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
[ "def", "cli", "(", ")", ":", "import", "getopt", "class", "BadUsage", ":", "pass", "# Scripts don't get the current directory in their path by default", "# unless they are run with the '-m' switch", "if", "''", "not", "in", "sys", ".", "path", ":", "scriptdir", "=", "os", ".", "path", ".", "dirname", "(", "sys", ".", "argv", "[", "0", "]", ")", "if", "scriptdir", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "remove", "(", "scriptdir", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "'.'", ")", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "'gk:p:w'", ")", "writing", "=", "0", "for", "opt", ",", "val", "in", "opts", ":", "if", "opt", "==", "'-g'", ":", "gui", "(", ")", "return", "if", "opt", "==", "'-k'", ":", "apropos", "(", "val", ")", "return", "if", "opt", "==", "'-p'", ":", "try", ":", "port", "=", "int", "(", "val", ")", "except", "ValueError", ":", "raise", "BadUsage", "def", "ready", "(", "server", ")", ":", "print", "'pydoc server ready at %s'", "%", "server", ".", "url", "def", "stopped", "(", ")", ":", "print", "'pydoc server stopped'", "serve", "(", "port", ",", "ready", ",", "stopped", ")", "return", "if", "opt", "==", "'-w'", ":", "writing", "=", "1", "if", "not", "args", ":", "raise", "BadUsage", "for", "arg", "in", "args", ":", "if", "ispath", "(", "arg", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "arg", ")", ":", "print", "'file %r does not exist'", "%", "arg", "break", "try", ":", "if", "ispath", "(", "arg", ")", "and", "os", ".", "path", ".", "isfile", "(", "arg", ")", ":", "arg", "=", "importfile", "(", "arg", ")", "if", "writing", ":", "if", "ispath", "(", "arg", ")", "and", "os", ".", "path", ".", "isdir", "(", "arg", ")", ":", "writedocs", "(", "arg", ")", "else", ":", "writedoc", "(", "arg", ")", "else", ":", "help", ".", "help", "(", "arg", ")", "except", "ErrorDuringImport", ",", "value", ":", "print", "value", "except", "(", "getopt", ".", "error", ",", "BadUsage", ")", ":", "cmd", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", "print", "\"\"\"pydoc - the Python documentation tool\n\n%s <name> ...\n Show text documentation on something. <name> may be the name of a\n Python keyword, topic, function, module, or package, or a dotted\n reference to a class or function within a module or module in a\n package. If <name> contains a '%s', it is used as the path to a\n Python source file to document. If name is 'keywords', 'topics',\n or 'modules', a listing of these things is displayed.\n\n%s -k <keyword>\n Search for a keyword in the synopsis lines of all available modules.\n\n%s -p <port>\n Start an HTTP server on the given port on the local machine. Port\n number 0 can be used to get an arbitrary unused port.\n\n%s -g\n Pop up a graphical interface for finding and serving documentation.\n\n%s -w <name> ...\n Write out the HTML documentation for a module to a file in the current\n directory. If <name> contains a '%s', it is treated as a filename; if\n it names a directory, documentation is written for all the contents.\n\"\"\"", "%", "(", "cmd", ",", "os", ".", "sep", ",", "cmd", ",", "cmd", ",", "cmd", ",", "cmd", ",", "os", ".", "sep", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/pydoc.py#L2338-L2420
pilotmoon/PopClip-Extensions
29fc472befc09ee350092ac70283bd9fdb456cb6
source/Trello/requests/utils.py
python
dict_from_cookiejar
(cj)
return cookie_dict
Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from.
Returns a key/value dictionary from a CookieJar.
[ "Returns", "a", "key", "/", "value", "dictionary", "from", "a", "CookieJar", "." ]
def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. """ cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict
[ "def", "dict_from_cookiejar", "(", "cj", ")", ":", "cookie_dict", "=", "{", "}", "for", "cookie", "in", "cj", ":", "cookie_dict", "[", "cookie", ".", "name", "]", "=", "cookie", ".", "value", "return", "cookie_dict" ]
https://github.com/pilotmoon/PopClip-Extensions/blob/29fc472befc09ee350092ac70283bd9fdb456cb6/source/Trello/requests/utils.py#L262-L273
javipalanca/spade
6a857c2ae0a86b3bdfd20ccfcd28a11e1c6db81e
travis_pypi_setup.py
python
fetch_public_key
(repo)
return data['key']
Download RSA public key Travis will use for this repo. Travis API docs: http://docs.travis-ci.com/api/#repository-keys
Download RSA public key Travis will use for this repo.
[ "Download", "RSA", "public", "key", "Travis", "will", "use", "for", "this", "repo", "." ]
def fetch_public_key(repo): """Download RSA public key Travis will use for this repo. Travis API docs: http://docs.travis-ci.com/api/#repository-keys """ keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo) data = json.loads(urlopen(keyurl).read().decode()) if 'key' not in data: errmsg = "Could not find public key for repo: {}.\n".format(repo) errmsg += "Have you already added your GitHub repo to Travis?" raise ValueError(errmsg) return data['key']
[ "def", "fetch_public_key", "(", "repo", ")", ":", "keyurl", "=", "'https://api.travis-ci.org/repos/{0}/key'", ".", "format", "(", "repo", ")", "data", "=", "json", ".", "loads", "(", "urlopen", "(", "keyurl", ")", ".", "read", "(", ")", ".", "decode", "(", ")", ")", "if", "'key'", "not", "in", "data", ":", "errmsg", "=", "\"Could not find public key for repo: {}.\\n\"", ".", "format", "(", "repo", ")", "errmsg", "+=", "\"Have you already added your GitHub repo to Travis?\"", "raise", "ValueError", "(", "errmsg", ")", "return", "data", "[", "'key'", "]" ]
https://github.com/javipalanca/spade/blob/6a857c2ae0a86b3bdfd20ccfcd28a11e1c6db81e/travis_pypi_setup.py#L52-L63
tensorflow/federated
5a60a032360087b8f4c7fcfd97ed1c0131c3eac3
tensorflow_federated/python/core/impl/federated_context/intrinsics.py
python
federated_eval
(fn, placement)
return value_impl.Value(comp)
Evaluates a federated computation at `placement`, returning the result. Args: fn: A no-arg TFF computation. placement: The desired result placement (either `tff.SERVER` or `tff.CLIENTS`). Returns: A federated value with the given placement `placement`. Raises: TypeError: If the arguments are not of the appropriate types.
Evaluates a federated computation at `placement`, returning the result.
[ "Evaluates", "a", "federated", "computation", "at", "placement", "returning", "the", "result", "." ]
def federated_eval(fn, placement): """Evaluates a federated computation at `placement`, returning the result. Args: fn: A no-arg TFF computation. placement: The desired result placement (either `tff.SERVER` or `tff.CLIENTS`). Returns: A federated value with the given placement `placement`. Raises: TypeError: If the arguments are not of the appropriate types. """ # TODO(b/113112108): Verify that neither the value, nor any of its parts # are of a federated type. fn = value_impl.to_value(fn, None) py_typecheck.check_type(fn, value_impl.Value) py_typecheck.check_type(fn.type_signature, computation_types.FunctionType) if fn.type_signature.parameter is not None: raise TypeError( '`federated_eval` expects a `fn` that accepts no arguments, but ' 'the `fn` provided has a parameter of type {}.'.format( fn.type_signature.parameter)) comp = building_block_factory.create_federated_eval(fn.comp, placement) comp = _bind_comp_as_reference(comp) return value_impl.Value(comp)
[ "def", "federated_eval", "(", "fn", ",", "placement", ")", ":", "# TODO(b/113112108): Verify that neither the value, nor any of its parts", "# are of a federated type.", "fn", "=", "value_impl", ".", "to_value", "(", "fn", ",", "None", ")", "py_typecheck", ".", "check_type", "(", "fn", ",", "value_impl", ".", "Value", ")", "py_typecheck", ".", "check_type", "(", "fn", ".", "type_signature", ",", "computation_types", ".", "FunctionType", ")", "if", "fn", ".", "type_signature", ".", "parameter", "is", "not", "None", ":", "raise", "TypeError", "(", "'`federated_eval` expects a `fn` that accepts no arguments, but '", "'the `fn` provided has a parameter of type {}.'", ".", "format", "(", "fn", ".", "type_signature", ".", "parameter", ")", ")", "comp", "=", "building_block_factory", ".", "create_federated_eval", "(", "fn", ".", "comp", ",", "placement", ")", "comp", "=", "_bind_comp_as_reference", "(", "comp", ")", "return", "value_impl", ".", "Value", "(", "comp", ")" ]
https://github.com/tensorflow/federated/blob/5a60a032360087b8f4c7fcfd97ed1c0131c3eac3/tensorflow_federated/python/core/impl/federated_context/intrinsics.py#L178-L207