nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_node_system_info.py
python
V1NodeSystemInfo.kubelet_version
(self, kubelet_version)
Sets the kubelet_version of this V1NodeSystemInfo. Kubelet Version reported by the node. # noqa: E501 :param kubelet_version: The kubelet_version of this V1NodeSystemInfo. # noqa: E501 :type: str
Sets the kubelet_version of this V1NodeSystemInfo.
[ "Sets", "the", "kubelet_version", "of", "this", "V1NodeSystemInfo", "." ]
def kubelet_version(self, kubelet_version): """Sets the kubelet_version of this V1NodeSystemInfo. Kubelet Version reported by the node. # noqa: E501 :param kubelet_version: The kubelet_version of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and kubelet_version is None: # noqa: E501 raise ValueError("Invalid value for `kubelet_version`, must not be `None`") # noqa: E501 self._kubelet_version = kubelet_version
[ "def", "kubelet_version", "(", "self", ",", "kubelet_version", ")", ":", "if", "self", ".", "local_vars_configuration", ".", "client_side_validation", "and", "kubelet_version", "is", "None", ":", "# noqa: E501", "raise", "ValueError", "(", "\"Invalid value for `kubelet_...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_node_system_info.py#L227-L238
tztztztztz/eql.detectron2
29224acf4ea549c53264e6229da69868bd5470f3
tools/plain_train_net.py
python
get_evaluator
(cfg, dataset_name, output_folder=None)
return DatasetEvaluators(evaluator_list)
Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here.
Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here.
[ "Create", "evaluator", "(", "s", ")", "for", "a", "given", "dataset", ".", "This", "uses", "the", "special", "metadata", "evaluator_type", "associated", "with", "each", "builtin", "dataset", ".", "For", "your", "own", "dataset", "you", "can", "simply", "crea...
def get_evaluator(cfg, dataset_name, output_folder=None): """ Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here. """ if output_folder is None: output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type if evaluator_type in ["sem_seg", "coco_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, num_classes=cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES, ignore_label=cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE, output_dir=output_folder, ) ) if evaluator_type in ["coco", "coco_panoptic_seg"]: evaluator_list.append(COCOEvaluator(dataset_name, cfg, True, output_folder)) if evaluator_type == "coco_panoptic_seg": evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) if evaluator_type == "cityscapes": assert ( torch.cuda.device_count() >= comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesEvaluator(dataset_name) if evaluator_type == "pascal_voc": return PascalVOCDetectionEvaluator(dataset_name) if evaluator_type == "lvis": return LVISEvaluator(dataset_name, cfg, True, output_folder) if len(evaluator_list) == 0: raise NotImplementedError( "no Evaluator for the dataset {} with the type {}".format(dataset_name, evaluator_type) ) if len(evaluator_list) == 1: return evaluator_list[0] return DatasetEvaluators(evaluator_list)
[ "def", "get_evaluator", "(", "cfg", ",", "dataset_name", ",", "output_folder", "=", "None", ")", ":", "if", "output_folder", "is", "None", ":", "output_folder", "=", "os", ".", "path", ".", "join", "(", "cfg", ".", "OUTPUT_DIR", ",", "\"inference\"", ")", ...
https://github.com/tztztztztz/eql.detectron2/blob/29224acf4ea549c53264e6229da69868bd5470f3/tools/plain_train_net.py#L59-L99
gaasedelen/lighthouse
7245a2d2c4e84351cd259ed81dafa4263167909a
plugins/lighthouse/reader/coverage_reader.py
python
CoverageReader.open
(self, filepath)
return coverage_file
Open and parse a coverage file from disk. Returns a CoverageFile on success, or raises CoverageParsingError on failure.
Open and parse a coverage file from disk.
[ "Open", "and", "parse", "a", "coverage", "file", "from", "disk", "." ]
def open(self, filepath): """ Open and parse a coverage file from disk. Returns a CoverageFile on success, or raises CoverageParsingError on failure. """ coverage_file = None parse_failures = {} # attempt to parse the given coverage file with each available parser for name, parser in iteritems(self._installed_parsers): logger.debug("Attempting parse with '%s'" % name) # attempt to open/parse the coverage file with the given parser try: coverage_file = parser(filepath) break # log the exceptions for each parse failure except Exception as e: parse_failures[name] = traceback.format_exc() logger.debug("| Parse FAILED - " + str(e)) #logger.exception("| Parse FAILED") # # if *all* the coverage file parsers failed, raise an exception with # information for each failure (for debugging) # if not coverage_file: raise CoverageParsingError(filepath, parse_failures) # successful parse logger.debug("| Parse OKAY") return coverage_file
[ "def", "open", "(", "self", ",", "filepath", ")", ":", "coverage_file", "=", "None", "parse_failures", "=", "{", "}", "# attempt to parse the given coverage file with each available parser", "for", "name", ",", "parser", "in", "iteritems", "(", "self", ".", "_instal...
https://github.com/gaasedelen/lighthouse/blob/7245a2d2c4e84351cd259ed81dafa4263167909a/plugins/lighthouse/reader/coverage_reader.py#L31-L65
pdoc3/pdoc
4aa70de2221a34a3003a7e5f52a9b91965f0e359
pdoc/__init__.py
python
link_inheritance
(context: Context = None)
Link inheritance relationsships between `pdoc.Class` objects (and between their members) of all `pdoc.Module` objects that share the provided `context` (`pdoc.Context`). You need to call this if you expect `pdoc.Doc.inherits` and inherited `pdoc.Doc.docstring` to be set correctly.
Link inheritance relationsships between `pdoc.Class` objects (and between their members) of all `pdoc.Module` objects that share the provided `context` (`pdoc.Context`).
[ "Link", "inheritance", "relationsships", "between", "pdoc", ".", "Class", "objects", "(", "and", "between", "their", "members", ")", "of", "all", "pdoc", ".", "Module", "objects", "that", "share", "the", "provided", "context", "(", "pdoc", ".", "Context", ")...
def link_inheritance(context: Context = None): """ Link inheritance relationsships between `pdoc.Class` objects (and between their members) of all `pdoc.Module` objects that share the provided `context` (`pdoc.Context`). You need to call this if you expect `pdoc.Doc.inherits` and inherited `pdoc.Doc.docstring` to be set correctly. """ if context is None: context = _global_context graph = {cls: set(cls.mro(only_documented=True)) for cls in _filter_type(Class, context)} for cls in _toposort(graph): cls._fill_inheritance() for module in _filter_type(Module, context): module._link_inheritance()
[ "def", "link_inheritance", "(", "context", ":", "Context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "_global_context", "graph", "=", "{", "cls", ":", "set", "(", "cls", ".", "mro", "(", "only_documented", "=", "True", ...
https://github.com/pdoc3/pdoc/blob/4aa70de2221a34a3003a7e5f52a9b91965f0e359/pdoc/__init__.py#L454-L473
google/rekall
55d1925f2df9759a989b35271b4fa48fc54a1c86
rekall-core/rekall/plugins/windows/registry/registry.py
python
_CM_KEY_VALUE._decode_data
(self, data)
return data
Decode the data according to our type.
Decode the data according to our type.
[ "Decode", "the", "data", "according", "to", "our", "type", "." ]
def _decode_data(self, data): """Decode the data according to our type.""" valtype = str(self.Type) if valtype in ["REG_DWORD", "REG_DWORD_BIG_ENDIAN", "REG_QWORD"]: if len(data) != struct.calcsize(self.value_formats[valtype]): return obj.NoneObject( "Value data did not match the expected data " "size for a {0}".format(valtype)) if valtype in ["REG_SZ", "REG_EXPAND_SZ", "REG_LINK"]: data = data.decode('utf-16-le', "ignore") elif valtype == "REG_MULTI_SZ": data = data.decode('utf-16-le', "ignore").split('\0') elif valtype in ["REG_DWORD", "REG_DWORD_BIG_ENDIAN", "REG_QWORD"]: data = struct.unpack(self.value_formats[valtype], data)[0] return data
[ "def", "_decode_data", "(", "self", ",", "data", ")", ":", "valtype", "=", "str", "(", "self", ".", "Type", ")", "if", "valtype", "in", "[", "\"REG_DWORD\"", ",", "\"REG_DWORD_BIG_ENDIAN\"", ",", "\"REG_QWORD\"", "]", ":", "if", "len", "(", "data", ")", ...
https://github.com/google/rekall/blob/55d1925f2df9759a989b35271b4fa48fc54a1c86/rekall-core/rekall/plugins/windows/registry/registry.py#L493-L512
karanchahal/distiller
a17ec06cbeafcdd2aea19d7c7663033c951392f5
models/cifar10/resnet.py
python
resnet56
(**kwargs)
return ResNetSmall(BasicBlock, [9, 9, 9], **kwargs)
[]
def resnet56(**kwargs): return ResNetSmall(BasicBlock, [9, 9, 9], **kwargs)
[ "def", "resnet56", "(", "*", "*", "kwargs", ")", ":", "return", "ResNetSmall", "(", "BasicBlock", ",", "[", "9", ",", "9", ",", "9", "]", ",", "*", "*", "kwargs", ")" ]
https://github.com/karanchahal/distiller/blob/a17ec06cbeafcdd2aea19d7c7663033c951392f5/models/cifar10/resnet.py#L274-L275
yt-project/yt
dc7b24f9b266703db4c843e329c6c8644d47b824
yt/frontends/ytdata/data_structures.py
python
YTNonspatialGrid.__repr__
(self)
return "YTNonspatialGrid"
[]
def __repr__(self): return "YTNonspatialGrid"
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"YTNonspatialGrid\"" ]
https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/frontends/ytdata/data_structures.py#L577-L578
ambitioninc/django-query-builder
c7abba65e7c92c2943c8e4e7e0865e1b98a42c34
querybuilder/query.py
python
Query.sum
(self, field)
return list(rows[0].values())[0]
Returns the sum of the field in the result set of the query by wrapping the query and performing a SUM aggregate of the specified field :param field: the field to pass to the SUM aggregate :type field: str :return: The sum of the specified field :rtype: int
Returns the sum of the field in the result set of the query by wrapping the query and performing a SUM aggregate of the specified field :param field: the field to pass to the SUM aggregate :type field: str
[ "Returns", "the", "sum", "of", "the", "field", "in", "the", "result", "set", "of", "the", "query", "by", "wrapping", "the", "query", "and", "performing", "a", "SUM", "aggregate", "of", "the", "specified", "field", ":", "param", "field", ":", "the", "fiel...
def sum(self, field): """ Returns the sum of the field in the result set of the query by wrapping the query and performing a SUM aggregate of the specified field :param field: the field to pass to the SUM aggregate :type field: str :return: The sum of the specified field :rtype: int """ q = Query(self.connection).from_table(self, fields=[ SumField(field) ]) rows = q.select(bypass_safe_limit=True) return list(rows[0].values())[0]
[ "def", "sum", "(", "self", ",", "field", ")", ":", "q", "=", "Query", "(", "self", ".", "connection", ")", ".", "from_table", "(", "self", ",", "fields", "=", "[", "SumField", "(", "field", ")", "]", ")", "rows", "=", "q", ".", "select", "(", "...
https://github.com/ambitioninc/django-query-builder/blob/c7abba65e7c92c2943c8e4e7e0865e1b98a42c34/querybuilder/query.py#L1886-L1900
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/__future__.py
python
_Feature.getMandatoryRelease
(self)
return self.mandatory
Return release in which this feature will become mandatory. This is a 5-tuple, of the same form as sys.version_info, or, if the feature was dropped, is None.
Return release in which this feature will become mandatory.
[ "Return", "release", "in", "which", "this", "feature", "will", "become", "mandatory", "." ]
def getMandatoryRelease(self): """Return release in which this feature will become mandatory. This is a 5-tuple, of the same form as sys.version_info, or, if the feature was dropped, is None. """ return self.mandatory
[ "def", "getMandatoryRelease", "(", "self", ")", ":", "return", "self", ".", "mandatory" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/__future__.py#L88-L95
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/core/utils/numba_utils.py
python
is_numba_compat_strict
()
return STRICT_NUMBA_COMPAT_CHECK
Returns strictness level of numba cuda compatibility checks. If value is true, numba cuda compatibility matrix must be satisfied. If value is false, only cuda availability is checked, not compatibility. Numba Cuda may still compile and run without issues in such a case, or it may fail.
Returns strictness level of numba cuda compatibility checks.
[ "Returns", "strictness", "level", "of", "numba", "cuda", "compatibility", "checks", "." ]
def is_numba_compat_strict() -> bool: """ Returns strictness level of numba cuda compatibility checks. If value is true, numba cuda compatibility matrix must be satisfied. If value is false, only cuda availability is checked, not compatibility. Numba Cuda may still compile and run without issues in such a case, or it may fail. """ return STRICT_NUMBA_COMPAT_CHECK
[ "def", "is_numba_compat_strict", "(", ")", "->", "bool", ":", "return", "STRICT_NUMBA_COMPAT_CHECK" ]
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/core/utils/numba_utils.py#L52-L60
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/google_ads_service/client.py
python
GoogleAdsServiceClient.shared_set_path
(customer_id: str, shared_set_id: str,)
return "customers/{customer_id}/sharedSets/{shared_set_id}".format( customer_id=customer_id, shared_set_id=shared_set_id, )
Return a fully-qualified shared_set string.
Return a fully-qualified shared_set string.
[ "Return", "a", "fully", "-", "qualified", "shared_set", "string", "." ]
def shared_set_path(customer_id: str, shared_set_id: str,) -> str: """Return a fully-qualified shared_set string.""" return "customers/{customer_id}/sharedSets/{shared_set_id}".format( customer_id=customer_id, shared_set_id=shared_set_id, )
[ "def", "shared_set_path", "(", "customer_id", ":", "str", ",", "shared_set_id", ":", "str", ",", ")", "->", "str", ":", "return", "\"customers/{customer_id}/sharedSets/{shared_set_id}\"", ".", "format", "(", "customer_id", "=", "customer_id", ",", "shared_set_id", "...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/google_ads_service/client.py#L2229-L2233
merantix/picasso
d276b9b7408dd1032fe0ccb84ea9b6604a32915e
travis_pypi_setup.py
python
save_yaml_config
(filepath, config)
[]
def save_yaml_config(filepath, config): with open(filepath, 'w') as f: yaml.dump(config, f, default_flow_style=False)
[ "def", "save_yaml_config", "(", "filepath", ",", "config", ")", ":", "with", "open", "(", "filepath", ",", "'w'", ")", "as", "f", ":", "yaml", ".", "dump", "(", "config", ",", "f", ",", "default_flow_style", "=", "False", ")" ]
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/travis_pypi_setup.py#L97-L99
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/data/event_list.py
python
EventList.select_parameter
(self, parameter, band)
return self.select_row_subset(mask)
Select events with respect to a specified parameter. Parameters ---------- parameter : str Parameter used for the selection. Must be present in `self.table`. band : tuple or `astropy.units.Quantity` Min and max value for the parameter to be selected (min <= parameter < max). If parameter is not dimensionless you have to provide a Quantity. Returns ------- event_list : `EventList` Copy of event list with selection applied. Examples -------- >>> from astropy import units as u >>> from gammapy.data import EventList >>> event_list = EventList.read('$GAMMAPY_DATA/fermi_3fhl/fermi_3fhl_events_selected.fits.gz') >>> zd = (0, 30) * u.deg >>> event_list = event_list.select_parameter(parameter='ZENITH_ANGLE', band=zd)
Select events with respect to a specified parameter.
[ "Select", "events", "with", "respect", "to", "a", "specified", "parameter", "." ]
def select_parameter(self, parameter, band): """Select events with respect to a specified parameter. Parameters ---------- parameter : str Parameter used for the selection. Must be present in `self.table`. band : tuple or `astropy.units.Quantity` Min and max value for the parameter to be selected (min <= parameter < max). If parameter is not dimensionless you have to provide a Quantity. Returns ------- event_list : `EventList` Copy of event list with selection applied. Examples -------- >>> from astropy import units as u >>> from gammapy.data import EventList >>> event_list = EventList.read('$GAMMAPY_DATA/fermi_3fhl/fermi_3fhl_events_selected.fits.gz') >>> zd = (0, 30) * u.deg >>> event_list = event_list.select_parameter(parameter='ZENITH_ANGLE', band=zd) """ mask = band[0] <= self.table[parameter].quantity mask &= self.table[parameter].quantity < band[1] return self.select_row_subset(mask)
[ "def", "select_parameter", "(", "self", ",", "parameter", ",", "band", ")", ":", "mask", "=", "band", "[", "0", "]", "<=", "self", ".", "table", "[", "parameter", "]", ".", "quantity", "mask", "&=", "self", ".", "table", "[", "parameter", "]", ".", ...
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/data/event_list.py#L283-L309
corkami/collisions
11d43794e0018538a788c44b95461bc23c4b24d0
scripts/ziphack.py
python
ZipFile._sanitize_windows_name
(cls, arcname, pathsep)
return arcname
Replace bad characters and remove trailing dots from parts.
Replace bad characters and remove trailing dots from parts.
[ "Replace", "bad", "characters", "and", "remove", "trailing", "dots", "from", "parts", "." ]
def _sanitize_windows_name(cls, arcname, pathsep): """Replace bad characters and remove trailing dots from parts.""" table = cls._windows_illegal_name_trans_table if not table: illegal = ':<>|"?*' table = str.maketrans(illegal, '_' * len(illegal)) cls._windows_illegal_name_trans_table = table arcname = arcname.translate(table) # remove trailing dots arcname = (x.rstrip('.') for x in arcname.split(pathsep)) # rejoin, removing empty parts. arcname = pathsep.join(x for x in arcname if x) return arcname
[ "def", "_sanitize_windows_name", "(", "cls", ",", "arcname", ",", "pathsep", ")", ":", "table", "=", "cls", ".", "_windows_illegal_name_trans_table", "if", "not", "table", ":", "illegal", "=", "':<>|\"?*'", "table", "=", "str", ".", "maketrans", "(", "illegal"...
https://github.com/corkami/collisions/blob/11d43794e0018538a788c44b95461bc23c4b24d0/scripts/ziphack.py#L1670-L1682
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/docutils-0.14/docutils/parsers/rst/roles.py
python
set_classes
(options)
Auxiliary function to set options['classes'] and delete options['class'].
Auxiliary function to set options['classes'] and delete options['class'].
[ "Auxiliary", "function", "to", "set", "options", "[", "classes", "]", "and", "delete", "options", "[", "class", "]", "." ]
def set_classes(options): """ Auxiliary function to set options['classes'] and delete options['class']. """ if 'class' in options: assert 'classes' not in options options['classes'] = options['class'] del options['class']
[ "def", "set_classes", "(", "options", ")", ":", "if", "'class'", "in", "options", ":", "assert", "'classes'", "not", "in", "options", "options", "[", "'classes'", "]", "=", "options", "[", "'class'", "]", "del", "options", "[", "'class'", "]" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/docutils-0.14/docutils/parsers/rst/roles.py#L386-L394
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/motifs/minimal.py
python
_read_version
(record, handle)
Read MEME version (PRIVATE).
Read MEME version (PRIVATE).
[ "Read", "MEME", "version", "(", "PRIVATE", ")", "." ]
def _read_version(record, handle): """Read MEME version (PRIVATE).""" for line in handle: if line.startswith("MEME version"): break else: raise ValueError( "Improper input file. File should contain a line starting MEME version." ) line = line.strip() ls = line.split() record.version = ls[2]
[ "def", "_read_version", "(", "record", ",", "handle", ")", ":", "for", "line", "in", "handle", ":", "if", "line", ".", "startswith", "(", "\"MEME version\"", ")", ":", "break", "else", ":", "raise", "ValueError", "(", "\"Improper input file. File should contain ...
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/motifs/minimal.py#L118-L129
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
areacb_t.del_area_cmt
(self, *args)
return _idaapi.areacb_t_del_area_cmt(self, *args)
del_area_cmt(self, a, repeatable)
del_area_cmt(self, a, repeatable)
[ "del_area_cmt", "(", "self", "a", "repeatable", ")" ]
def del_area_cmt(self, *args): """ del_area_cmt(self, a, repeatable) """ return _idaapi.areacb_t_del_area_cmt(self, *args)
[ "def", "del_area_cmt", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "areacb_t_del_area_cmt", "(", "self", ",", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L21225-L21229
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_vendor/urllib3/response.py
python
HTTPResponse.tell
(self)
return self._fp_bytes_read
Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``urllib3.response.HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed).
Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``urllib3.response.HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed).
[ "Obtain", "the", "number", "of", "bytes", "pulled", "over", "the", "wire", "so", "far", ".", "May", "differ", "from", "the", "amount", "of", "content", "returned", "by", ":", "meth", ":", "urllib3", ".", "response", ".", "HTTPResponse", ".", "read", "if"...
def tell(self): """ Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``urllib3.response.HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). """ return self._fp_bytes_read
[ "def", "tell", "(", "self", ")", ":", "return", "self", ".", "_fp_bytes_read" ]
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/urllib3/response.py#L309-L315
geopandas/geopandas
8e7133aef9e6c0d2465e07e92d954e95dedd3881
geopandas/_vectorized.py
python
_binary_op
(op, left, right, *args, **kwargs)
Binary operation on np.array[geoms] that returns a ndarray
Binary operation on np.array[geoms] that returns a ndarray
[ "Binary", "operation", "on", "np", ".", "array", "[", "geoms", "]", "that", "returns", "a", "ndarray" ]
def _binary_op(op, left, right, *args, **kwargs): # type: (str, np.array[geoms], np.array[geoms]/BaseGeometry, args/kwargs) # -> array """Binary operation on np.array[geoms] that returns a ndarray""" # pass empty to shapely (relate handles this correctly, project only # for linestrings and points) if op == "project": null_value = np.nan dtype = float elif op == "relate": null_value = None dtype = object else: raise AssertionError("wrong op") if isinstance(right, BaseGeometry): data = [ getattr(s, op)(right, *args, **kwargs) if s is not None else null_value for s in left ] return np.array(data, dtype=dtype) elif isinstance(right, np.ndarray): if len(left) != len(right): msg = "Lengths of inputs do not match. Left: {0}, Right: {1}".format( len(left), len(right) ) raise ValueError(msg) data = [ getattr(this_elem, op)(other_elem, *args, **kwargs) if not (this_elem is None or other_elem is None) else null_value for this_elem, other_elem in zip(left, right) ] return np.array(data, dtype=dtype) else: raise TypeError("Type not known: {0} vs {1}".format(type(left), type(right)))
[ "def", "_binary_op", "(", "op", ",", "left", ",", "right", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (str, np.array[geoms], np.array[geoms]/BaseGeometry, args/kwargs)", "# -> array", "# pass empty to shapely (relate handles this correctly, project onl...
https://github.com/geopandas/geopandas/blob/8e7133aef9e6c0d2465e07e92d954e95dedd3881/geopandas/_vectorized.py#L389-L424
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/collections.py
python
Counter.elements
(self)
return _chain.from_iterable(_starmap(_repeat, self.iteritems()))
Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836 Note, if an element's count has been set to zero or is a negative number, elements() will ignore it.
Iterator over elements repeating each as many times as its count.
[ "Iterator", "over", "elements", "repeating", "each", "as", "many", "times", "as", "its", "count", "." ]
def elements(self): '''Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836 Note, if an element's count has been set to zero or is a negative number, elements() will ignore it. ''' # Emulate Bag.do from Smalltalk and Multiset.begin from C++. return _chain.from_iterable(_starmap(_repeat, self.iteritems()))
[ "def", "elements", "(", "self", ")", ":", "# Emulate Bag.do from Smalltalk and Multiset.begin from C++.", "return", "_chain", ".", "from_iterable", "(", "_starmap", "(", "_repeat", ",", "self", ".", "iteritems", "(", ")", ")", ")" ]
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/collections.py#L438-L458
mlcommons/ck
558a22c5970eb0d6708d0edc080e62a92566bab0
ck/repo/module/ck-platform/ck_032630d041b4fd8a/main.py
python
update
(force)
return 0
Update/bootstrap cK components.
Update/bootstrap cK components.
[ "Update", "/", "bootstrap", "cK", "components", "." ]
def update(force): ''' Update/bootstrap cK components. ''' from . import config r=config.update({'force':force}) if r['return']>0: process_error(r) return 0
[ "def", "update", "(", "force", ")", ":", "from", ".", "import", "config", "r", "=", "config", ".", "update", "(", "{", "'force'", ":", "force", "}", ")", "if", "r", "[", "'return'", "]", ">", "0", ":", "process_error", "(", "r", ")", "return", "0...
https://github.com/mlcommons/ck/blob/558a22c5970eb0d6708d0edc080e62a92566bab0/ck/repo/module/ck-platform/ck_032630d041b4fd8a/main.py#L239-L248
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
is_autosync
(*args)
return _idaapi.is_autosync(*args)
is_autosync(name, type) -> bool is_autosync(name, tif) -> bool
is_autosync(name, type) -> bool is_autosync(name, tif) -> bool
[ "is_autosync", "(", "name", "type", ")", "-", ">", "bool", "is_autosync", "(", "name", "tif", ")", "-", ">", "bool" ]
def is_autosync(*args): """ is_autosync(name, type) -> bool is_autosync(name, tif) -> bool """ return _idaapi.is_autosync(*args)
[ "def", "is_autosync", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "is_autosync", "(", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L29689-L29694
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
source/openerp/models.py
python
fix_import_export_id_paths
(fieldname)
return fixed_external_id.split('/')
Fixes the id fields in import and exports, and splits field paths on '/'. :param str fieldname: name of the field to import/export :return: split field name :rtype: list of str
Fixes the id fields in import and exports, and splits field paths on '/'.
[ "Fixes", "the", "id", "fields", "in", "import", "and", "exports", "and", "splits", "field", "paths", "on", "/", "." ]
def fix_import_export_id_paths(fieldname): """ Fixes the id fields in import and exports, and splits field paths on '/'. :param str fieldname: name of the field to import/export :return: split field name :rtype: list of str """ fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname) fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id) return fixed_external_id.split('/')
[ "def", "fix_import_export_id_paths", "(", "fieldname", ")", ":", "fixed_db_id", "=", "re", ".", "sub", "(", "r'([^/])\\.id'", ",", "r'\\1/.id'", ",", "fieldname", ")", "fixed_external_id", "=", "re", ".", "sub", "(", "r'([^/]):id'", ",", "r'\\1/id'", ",", "fix...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/source/openerp/models.py#L127-L138
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/uuid.py
python
_random_getnode
()
return random.randrange(0, 1<<48L) | 0x010000000000L
Get a random node ID, with eighth bit set as suggested by RFC 4122.
Get a random node ID, with eighth bit set as suggested by RFC 4122.
[ "Get", "a", "random", "node", "ID", "with", "eighth", "bit", "set", "as", "suggested", "by", "RFC", "4122", "." ]
def _random_getnode(): """Get a random node ID, with eighth bit set as suggested by RFC 4122.""" import random return random.randrange(0, 1<<48L) | 0x010000000000L
[ "def", "_random_getnode", "(", ")", ":", "import", "random", "return", "random", ".", "randrange", "(", "0", ",", "1", "<<", "48L", ")", "|", "0x010000000000L" ]
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/uuid.py#L504-L507
carla-simulator/ros-bridge
dac9e729b70a3db9da665c1fdb843e96e7e25d04
carla_ros_bridge/src/carla_ros_bridge/bridge.py
python
CarlaRosBridge.destroy
(self)
Function to destroy this object. :return:
Function to destroy this object.
[ "Function", "to", "destroy", "this", "object", "." ]
def destroy(self): """ Function to destroy this object. :return: """ self.loginfo("Shutting down...") self.shutdown.set() if not self.sync_mode: if self.on_tick_id: self.carla_world.remove_on_tick(self.on_tick_id) self.actor_factory.thread.join() else: self.synchronous_mode_update_thread.join() self.loginfo("Object update finished.") self.debug_helper.destroy() self.status_publisher.destroy() self.destroy_service(self.spawn_object_service) self.destroy_service(self.destroy_object_service) self.destroy_subscription(self.carla_weather_subscriber) self.carla_control_queue.put(CarlaControl.STEP_ONCE) for uid in self._registered_actors: self.actor_factory.destroy_actor(uid) self.actor_factory.update_available_objects() self.actor_factory.clear() super(CarlaRosBridge, self).destroy()
[ "def", "destroy", "(", "self", ")", ":", "self", ".", "loginfo", "(", "\"Shutting down...\"", ")", "self", ".", "shutdown", ".", "set", "(", ")", "if", "not", "self", ".", "sync_mode", ":", "if", "self", ".", "on_tick_id", ":", "self", ".", "carla_worl...
https://github.com/carla-simulator/ros-bridge/blob/dac9e729b70a3db9da665c1fdb843e96e7e25d04/carla_ros_bridge/src/carla_ros_bridge/bridge.py#L342-L368
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/voiper/sulley/sulley/legos/sip.py
python
q_value.__init__
(self, name, request, value, options={})
[]
def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options # fuzz by default if self.options.has_key('fuzzable'): fuzzable = self.options['fuzzable'] else: fuzzable = True self.push(primitives.string("q" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.string("0", fuzzable=fuzzable)) self.push(primitives.delim(".")) self.push(primitives.dword(5, fuzzable=True, signed=True, format="ascii"))
[ "def", "__init__", "(", "self", ",", "name", ",", "request", ",", "value", ",", "options", "=", "{", "}", ")", ":", "blocks", ".", "block", ".", "__init__", "(", "self", ",", "name", ",", "request", ",", "None", ",", "None", ",", "None", ",", "No...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/voiper/sulley/sulley/legos/sip.py#L5-L21
tanghaibao/goatools
647e9dd833695f688cd16c2f9ea18f1692e5c6bc
goatools/semantic.py
python
deepest_common_ancestor
(goterms, godag)
return max(common_parent_go_ids(goterms, godag), key=lambda t: godag[t].depth)
This function gets the nearest common ancestor using the above function. Only returns single most specific - assumes unique exists.
This function gets the nearest common ancestor using the above function. Only returns single most specific - assumes unique exists.
[ "This", "function", "gets", "the", "nearest", "common", "ancestor", "using", "the", "above", "function", ".", "Only", "returns", "single", "most", "specific", "-", "assumes", "unique", "exists", "." ]
def deepest_common_ancestor(goterms, godag): ''' This function gets the nearest common ancestor using the above function. Only returns single most specific - assumes unique exists. ''' # Take the element at maximum depth. return max(common_parent_go_ids(goterms, godag), key=lambda t: godag[t].depth)
[ "def", "deepest_common_ancestor", "(", "goterms", ",", "godag", ")", ":", "# Take the element at maximum depth.", "return", "max", "(", "common_parent_go_ids", "(", "goterms", ",", "godag", ")", ",", "key", "=", "lambda", "t", ":", "godag", "[", "t", "]", ".",...
https://github.com/tanghaibao/goatools/blob/647e9dd833695f688cd16c2f9ea18f1692e5c6bc/goatools/semantic.py#L204-L211
Telefonica/HomePWN
080398174159f856f4155dcb155c6754d1f85ad8
utils/opendrop/zeroconf.py
python
DNSQuestion.answered_by
(self, rec)
return (self.class_ == rec.class_ and (self.type == rec.type or self.type == _TYPE_ANY) and self.name == rec.name)
Returns true if the question is answered by the record
Returns true if the question is answered by the record
[ "Returns", "true", "if", "the", "question", "is", "answered", "by", "the", "record" ]
def answered_by(self, rec): """Returns true if the question is answered by the record""" return (self.class_ == rec.class_ and (self.type == rec.type or self.type == _TYPE_ANY) and self.name == rec.name)
[ "def", "answered_by", "(", "self", ",", "rec", ")", ":", "return", "(", "self", ".", "class_", "==", "rec", ".", "class_", "and", "(", "self", ".", "type", "==", "rec", ".", "type", "or", "self", ".", "type", "==", "_TYPE_ANY", ")", "and", "self", ...
https://github.com/Telefonica/HomePWN/blob/080398174159f856f4155dcb155c6754d1f85ad8/utils/opendrop/zeroconf.py#L397-L401
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/export/views/download.py
python
DownloadNewSmsExportView.parent_pages
(self)
return []
[]
def parent_pages(self): return []
[ "def", "parent_pages", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/export/views/download.py#L511-L512
XuezheMax/flowseq
8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b
flownmt/modules/posteriors/transformer.py
python
TransformerPosterior.target_embed_weight
(self)
[]
def target_embed_weight(self): if isinstance(self.core, nn.DataParallel): return self.core.module.tgt_embedd.weight else: return self.core.tgt_embed.weight
[ "def", "target_embed_weight", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "core", ",", "nn", ".", "DataParallel", ")", ":", "return", "self", ".", "core", ".", "module", ".", "tgt_embedd", ".", "weight", "else", ":", "return", "self", ...
https://github.com/XuezheMax/flowseq/blob/8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b/flownmt/modules/posteriors/transformer.py#L80-L84
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/tree/timespanTree.py
python
TimespanTree.offset
(self)
return self.lowestPosition()
this is just for mimicking elements as streams. Changed in v7 -- this was always meant to be a property, but was incorrectly a method earlier.
this is just for mimicking elements as streams.
[ "this", "is", "just", "for", "mimicking", "elements", "as", "streams", "." ]
def offset(self): ''' this is just for mimicking elements as streams. Changed in v7 -- this was always meant to be a property, but was incorrectly a method earlier. ''' return self.lowestPosition()
[ "def", "offset", "(", "self", ")", ":", "return", "self", ".", "lowestPosition", "(", ")" ]
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/tree/timespanTree.py#L205-L212
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pkg_resources.py
python
get_default_cache
()
Determine the default cache location This returns the ``PYTHON_EGG_CACHE`` environment variable, if set. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the "Application Data" directory. On all other systems, it's "~/.python-eggs".
Determine the default cache location
[ "Determine", "the", "default", "cache", "location" ]
def get_default_cache(): """Determine the default cache location This returns the ``PYTHON_EGG_CACHE`` environment variable, if set. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the "Application Data" directory. On all other systems, it's "~/.python-eggs". """ try: return os.environ['PYTHON_EGG_CACHE'] except KeyError: pass if os.name!='nt': return os.path.expanduser('~/.python-eggs') app_data = 'Application Data' # XXX this may be locale-specific! app_homes = [ (('APPDATA',), None), # best option, should be locale-safe (('USERPROFILE',), app_data), (('HOMEDRIVE','HOMEPATH'), app_data), (('HOMEPATH',), app_data), (('HOME',), None), (('WINDIR',), app_data), # 95/98/ME ] for keys, subdir in app_homes: dirname = '' for key in keys: if key in os.environ: dirname = os.path.join(dirname, os.environ[key]) else: break else: if subdir: dirname = os.path.join(dirname,subdir) return os.path.join(dirname, 'Python-Eggs') else: raise RuntimeError( "Please set the PYTHON_EGG_CACHE enviroment variable" )
[ "def", "get_default_cache", "(", ")", ":", "try", ":", "return", "os", ".", "environ", "[", "'PYTHON_EGG_CACHE'", "]", "except", "KeyError", ":", "pass", "if", "os", ".", "name", "!=", "'nt'", ":", "return", "os", ".", "path", ".", "expanduser", "(", "...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pkg_resources.py#L1052-L1091
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
Extensions/Outline/Python/pyclbr.py
python
GlobalVariable.__init__
(self, name, lineno)
[]
def __init__(self, name, lineno): self.name = name self.lineno = lineno self.objectType = "GlobalVariable"
[ "def", "__init__", "(", "self", ",", "name", ",", "lineno", ")", ":", "self", ".", "name", "=", "name", "self", ".", "lineno", "=", "lineno", "self", ".", "objectType", "=", "\"GlobalVariable\"" ]
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/Extensions/Outline/Python/pyclbr.py#L52-L56
viewfinderco/viewfinder
453845b5d64ab5b3b826c08b02546d1ca0a07c14
backend/op/build_archive_op.py
python
BuildArchiveOperation._VerifyPhotoExists
(self, folder_path, photo_id)
The file for this photo should already exist.
The file for this photo should already exist.
[ "The", "file", "for", "this", "photo", "should", "already", "exist", "." ]
def _VerifyPhotoExists(self, folder_path, photo_id): """The file for this photo should already exist.""" assert os.path.exists(os.path.join(folder_path, photo_id + '.f.jpg'))
[ "def", "_VerifyPhotoExists", "(", "self", ",", "folder_path", ",", "photo_id", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "folder_path", ",", "photo_id", "+", "'.f.jpg'", ")", ")" ]
https://github.com/viewfinderco/viewfinder/blob/453845b5d64ab5b3b826c08b02546d1ca0a07c14/backend/op/build_archive_op.py#L405-L407
Tafkas/fritzbox-munin
d7929f15fc15d7e132288b262fc025d12a5f498a
fritzbox_uptime.py
python
get_uptime
()
get the current uptime
get the current uptime
[ "get", "the", "current", "uptime" ]
def get_uptime(): """get the current uptime""" server = os.environ["fritzbox_ip"] username = os.environ["fritzbox_username"] password = os.environ["fritzbox_password"] session_id = fh.get_session_id(server, username, password) xhr_data = fh.get_xhr_content(server, session_id, PAGE) data = json.loads(xhr_data) for d in data["data"]["drain"]: if "aktiv" in d["statuses"]: matches = re.finditer(pattern, d["statuses"]) if matches: hours = 0.0 for m in matches: if m.group(2) == dayLoc[locale]: hours += 24 * int(m.group(1)) if m.group(2) == hourLoc[locale]: hours += int(m.group(1)) if m.group(2) == minutesLoc[locale]: hours += int(m.group(1)) / 60.0 uptime = hours / 24 print("uptime.value %.2f" % uptime)
[ "def", "get_uptime", "(", ")", ":", "server", "=", "os", ".", "environ", "[", "\"fritzbox_ip\"", "]", "username", "=", "os", ".", "environ", "[", "\"fritzbox_username\"", "]", "password", "=", "os", ".", "environ", "[", "\"fritzbox_password\"", "]", "session...
https://github.com/Tafkas/fritzbox-munin/blob/d7929f15fc15d7e132288b262fc025d12a5f498a/fritzbox_uptime.py#L36-L59
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/requests/requests/cookies.py
python
RequestsCookieJar.__getitem__
(self, name)
return self._find_no_duplicates(name)
Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1).
Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead.
[ "Dict", "-", "like", "__getitem__", "()", "for", "compatibility", "with", "client", "code", ".", "Throws", "exception", "if", "there", "are", "more", "than", "one", "cookie", "with", "name", ".", "In", "that", "case", "use", "the", "more", "explicit", "get...
def __getitem__(self, name): """Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1).""" return self._find_no_duplicates(name)
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_find_no_duplicates", "(", "name", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/requests/requests/cookies.py#L276-L283
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/analysis/morph.py
python
StemFilter.__getstate__
(self)
return dict([(k, self.__dict__[k]) for k in self.__dict__ if k != "_stem"])
[]
def __getstate__(self): # Can't pickle a dynamic function, so we have to remove the _stem # attribute from the state return dict([(k, self.__dict__[k]) for k in self.__dict__ if k != "_stem"])
[ "def", "__getstate__", "(", "self", ")", ":", "# Can't pickle a dynamic function, so we have to remove the _stem", "# attribute from the state", "return", "dict", "(", "[", "(", "k", ",", "self", ".", "__dict__", "[", "k", "]", ")", "for", "k", "in", "self", ".", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/analysis/morph.py#L92-L96
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/enterprise/enterprise.py
python
EnterpriseWebUserReport.headers
(self)
return [_('Email Address'), _('Name'), _('Role'), _('Last Login [UTC]'), _('Last Access Date [UTC]'), _('Status')] + headers
[]
def headers(self): headers = super(EnterpriseWebUserReport, self).headers return [_('Email Address'), _('Name'), _('Role'), _('Last Login [UTC]'), _('Last Access Date [UTC]'), _('Status')] + headers
[ "def", "headers", "(", "self", ")", ":", "headers", "=", "super", "(", "EnterpriseWebUserReport", ",", "self", ")", ".", "headers", "return", "[", "_", "(", "'Email Address'", ")", ",", "_", "(", "'Name'", ")", ",", "_", "(", "'Role'", ")", ",", "_",...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/enterprise/enterprise.py#L140-L143
yuantailing/ctw-baseline
081c8361b0ed0675bf619ab6316ebf8415e93f46
classification/slim/datasets/build_imagenet_data.py
python
_int64_feature
(value)
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
Wrapper for inserting int64 features into Example proto.
Wrapper for inserting int64 features into Example proto.
[ "Wrapper", "for", "inserting", "int64", "features", "into", "Example", "proto", "." ]
def _int64_feature(value): """Wrapper for inserting int64 features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
[ "def", "_int64_feature", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "value", "]", "return", "tf", ".", "train", ".", "Feature", "(", "int64_list", "=", "tf", ".", "train", ".", "Int64Lis...
https://github.com/yuantailing/ctw-baseline/blob/081c8361b0ed0675bf619ab6316ebf8415e93f46/classification/slim/datasets/build_imagenet_data.py#L158-L162
GermainZ/weechat-vimode
897a33b9fb28c98c4e0a1c292d13536dd57f85c7
vimode.py
python
operator_c
(buf, input_line, pos1, pos2, overwrite=False)
Delete text from `pos1` to `pos2` from the input and enter Insert mode. If `overwrite` is set to True, the character at the cursor's new position is removed as well (the motion is inclusive.) See Also: `operator_base()`.
Delete text from `pos1` to `pos2` from the input and enter Insert mode.
[ "Delete", "text", "from", "pos1", "to", "pos2", "from", "the", "input", "and", "enter", "Insert", "mode", "." ]
def operator_c(buf, input_line, pos1, pos2, overwrite=False): """Delete text from `pos1` to `pos2` from the input and enter Insert mode. If `overwrite` is set to True, the character at the cursor's new position is removed as well (the motion is inclusive.) See Also: `operator_base()`. """ operator_d(buf, input_line, pos1, pos2, overwrite) set_mode("INSERT") set_cur(buf, input_line, pos1)
[ "def", "operator_c", "(", "buf", ",", "input_line", ",", "pos1", ",", "pos2", ",", "overwrite", "=", "False", ")", ":", "operator_d", "(", "buf", ",", "input_line", ",", "pos1", ",", "pos2", ",", "overwrite", ")", "set_mode", "(", "\"INSERT\"", ")", "s...
https://github.com/GermainZ/weechat-vimode/blob/897a33b9fb28c98c4e0a1c292d13536dd57f85c7/vimode.py#L461-L472
weechat/scripts
99ec0e7eceefabb9efb0f11ec26d45d6e8e84335
python/urlgrab.py
python
completion_urls_cb
(data, completion_item, bufferp, completion)
return weechat.WEECHAT_RC_OK
Complete with URLS, for command '/url'.
Complete with URLS, for command '/url'.
[ "Complete", "with", "URLS", "for", "command", "/", "url", "." ]
def completion_urls_cb(data, completion_item, bufferp, completion): """ Complete with URLS, for command '/url'. """ global urlGrab bufferd = hashBufferName( bufferp) for url in urlGrab.globalUrls : if url['buffer'] == bufferd: weechat.hook_completion_list_add(completion, url['url'], 0, weechat.WEECHAT_LIST_POS_SORT) return weechat.WEECHAT_RC_OK
[ "def", "completion_urls_cb", "(", "data", ",", "completion_item", ",", "bufferp", ",", "completion", ")", ":", "global", "urlGrab", "bufferd", "=", "hashBufferName", "(", "bufferp", ")", "for", "url", "in", "urlGrab", ".", "globalUrls", ":", "if", "url", "["...
https://github.com/weechat/scripts/blob/99ec0e7eceefabb9efb0f11ec26d45d6e8e84335/python/urlgrab.py#L661-L668
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/physics/quantum/gate.py
python
Gate._apply_operator_IntQubit
(self, qubits, **options)
return self._apply_operator_Qubit(qubits, **options)
Redirect an apply from IntQubit to Qubit
Redirect an apply from IntQubit to Qubit
[ "Redirect", "an", "apply", "from", "IntQubit", "to", "Qubit" ]
def _apply_operator_IntQubit(self, qubits, **options): """Redirect an apply from IntQubit to Qubit""" return self._apply_operator_Qubit(qubits, **options)
[ "def", "_apply_operator_IntQubit", "(", "self", ",", "qubits", ",", "*", "*", "options", ")", ":", "return", "self", ".", "_apply_operator_Qubit", "(", "qubits", ",", "*", "*", "options", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/physics/quantum/gate.py#L205-L207
PacificBiosciences/FALCON
ab80e88e1278879f28fe83b9fa0382249213444e
falcon_kit/functional.py
python
mapped_readlengths_from_dbdump_output
(output)
return lengths
Given output text from the DBump command, return dict of (id => read-length). There will be alternate lines like these: R # L # # # https://dazzlerblog.wordpress.com/command-guides/dazz_db-command-guide/
Given output text from the DBump command, return dict of (id => read-length). There will be alternate lines like these: R # L # # # https://dazzlerblog.wordpress.com/command-guides/dazz_db-command-guide/
[ "Given", "output", "text", "from", "the", "DBump", "command", "return", "dict", "of", "(", "id", "=", ">", "read", "-", "length", ")", ".", "There", "will", "be", "alternate", "lines", "like", "these", ":", "R", "#", "L", "#", "#", "#", "https", ":...
def mapped_readlengths_from_dbdump_output(output): """Given output text from the DBump command, return dict of (id => read-length). There will be alternate lines like these: R # L # # # https://dazzlerblog.wordpress.com/command-guides/dazz_db-command-guide/ """ lengths = dict() re_rid = re.compile('^R\s+(\d+)$') re_length = re.compile('^L\s+(\d+)\s+(\d+)\s+(\d+)$') for line in output.splitlines(): mo = re_rid.search(line) if mo: idx = int(mo.group(1)) continue mo = re_length.search(line) if mo: well, beg, end = mo.group(1, 2, 3) well = int(idx) beg = int(beg) end = int(end) lengths[idx] = (end - beg) continue return lengths
[ "def", "mapped_readlengths_from_dbdump_output", "(", "output", ")", ":", "lengths", "=", "dict", "(", ")", "re_rid", "=", "re", ".", "compile", "(", "'^R\\s+(\\d+)$'", ")", "re_length", "=", "re", ".", "compile", "(", "'^L\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)$'", ")", ...
https://github.com/PacificBiosciences/FALCON/blob/ab80e88e1278879f28fe83b9fa0382249213444e/falcon_kit/functional.py#L325-L349
openstack/rally
58b12c2e0bfa541bdb038be6e1679c5117b98484
rally/cli/commands/deployment.py
python
DeploymentCommands.use
(self, api, deployment)
Set active deployment.
Set active deployment.
[ "Set", "active", "deployment", "." ]
def use(self, api, deployment): """Set active deployment.""" # TODO(astudenov): make this method platform independent try: if not isinstance(deployment, dict): deployment = api.deployment.get(deployment=deployment) except exceptions.DBRecordNotFound: print("Deployment %s is not found." % deployment) return 1 print("Using deployment: %s" % deployment["uuid"]) envutils.update_globals_file(envutils.ENV_DEPLOYMENT, deployment["uuid"]) envutils.update_globals_file(envutils.ENV_ENV, deployment["uuid"]) if "openstack" in deployment["credentials"]: creds = deployment["credentials"]["openstack"][0] self._update_openrc_deployment_file( deployment["uuid"], creds["admin"] or creds["users"][0]) print("~/.rally/openrc was updated\n\nHINTS:\n" "\n* To use standard OpenStack clients, set up your env by " "running:\n\tsource ~/.rally/openrc\n" " OpenStack clients are now configured, e.g run:\n\t" "openstack image list")
[ "def", "use", "(", "self", ",", "api", ",", "deployment", ")", ":", "# TODO(astudenov): make this method platform independent", "try", ":", "if", "not", "isinstance", "(", "deployment", ",", "dict", ")", ":", "deployment", "=", "api", ".", "deployment", ".", "...
https://github.com/openstack/rally/blob/58b12c2e0bfa541bdb038be6e1679c5117b98484/rally/cli/commands/deployment.py#L315-L339
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/incomfort/water_heater.py
python
IncomfortWaterHeater.max_temp
(self)
return 80.0
Return max valid temperature that can be set.
Return max valid temperature that can be set.
[ "Return", "max", "valid", "temperature", "that", "can", "be", "set", "." ]
def max_temp(self) -> float: """Return max valid temperature that can be set.""" return 80.0
[ "def", "max_temp", "(", "self", ")", "->", "float", ":", "return", "80.0" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/incomfort/water_heater.py#L82-L84
davidhalter/parso
ee5edaf22ff3941cbdfa4efd8cb3e8f69779fd56
parso/python/tree.py
python
ImportFrom.get_defined_names
(self, include_setitem=False)
return [alias or name for name, alias in self._as_name_tuples()]
Returns the a list of `Name` that the import defines. The defined names are set after `import` or in case an alias - `as` - is present that name is returned.
Returns the a list of `Name` that the import defines. The defined names are set after `import` or in case an alias - `as` - is present that name is returned.
[ "Returns", "the", "a", "list", "of", "Name", "that", "the", "import", "defines", ".", "The", "defined", "names", "are", "set", "after", "import", "or", "in", "case", "an", "alias", "-", "as", "-", "is", "present", "that", "name", "is", "returned", "." ...
def get_defined_names(self, include_setitem=False): """ Returns the a list of `Name` that the import defines. The defined names are set after `import` or in case an alias - `as` - is present that name is returned. """ return [alias or name for name, alias in self._as_name_tuples()]
[ "def", "get_defined_names", "(", "self", ",", "include_setitem", "=", "False", ")", ":", "return", "[", "alias", "or", "name", "for", "name", ",", "alias", "in", "self", ".", "_as_name_tuples", "(", ")", "]" ]
https://github.com/davidhalter/parso/blob/ee5edaf22ff3941cbdfa4efd8cb3e8f69779fd56/parso/python/tree.py#L823-L829
getdock/whitelist
704bb41552f71d1a91ecf35e373d8f0b7434f144
app/customerio/signals.py
python
identify_user
(user: User, **_)
[]
def identify_user(user: User, **_): try: customerio.identify(user, ip=user.ip, idm_tid=user.idm_tid) except: log.exception('Customer error')
[ "def", "identify_user", "(", "user", ":", "User", ",", "*", "*", "_", ")", ":", "try", ":", "customerio", ".", "identify", "(", "user", ",", "ip", "=", "user", ".", "ip", ",", "idm_tid", "=", "user", ".", "idm_tid", ")", "except", ":", "log", "."...
https://github.com/getdock/whitelist/blob/704bb41552f71d1a91ecf35e373d8f0b7434f144/app/customerio/signals.py#L17-L21
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/contrib/auth/mixins.py
python
LoginRequiredMixin.dispatch
(self, request, *args, **kwargs)
return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
[]
def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return self.handle_no_permission() return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "request", ".", "user", ".", "is_authenticated", ":", "return", "self", ".", "handle_no_permission", "(", ")", "return", "super", "(", "Lo...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/auth/mixins.py#L53-L56
weewx/weewx
cb594fce224560bd8696050fc5c7843c7839320e
bin/weeimport/weeimport.py
python
Source.__init__
(self, config_dict, import_config_dict, options)
A generic initialisation. Set some realistic default values for options read from the import config file. Obtain objects to handle missing derived obs (if required) and QC on imported data. Parse any --date command line option so we know what records to import.
A generic initialisation.
[ "A", "generic", "initialisation", "." ]
def __init__(self, config_dict, import_config_dict, options): """A generic initialisation. Set some realistic default values for options read from the import config file. Obtain objects to handle missing derived obs (if required) and QC on imported data. Parse any --date command line option so we know what records to import. """ # save our WeeWX config dict self.config_dict = config_dict # get our import config dict settings # interval, default to 'derive' self.interval = import_config_dict.get('interval', 'derive') # do we ignore invalid data, default to True self.ignore_invalid_data = tobool(import_config_dict.get('ignore_invalid_data', True)) # tranche, default to 250 self.tranche = to_int(import_config_dict.get('tranche', 250)) # apply QC, default to True self.apply_qc = tobool(import_config_dict.get('qc', True)) # calc-missing, default to True self.calc_missing = tobool(import_config_dict.get('calc_missing', True)) # Some sources include UV index and solar radiation values even if no # sensor was present. The WeeWX convention is to store the None value # when a sensor or observation does not exist. Record whether UV and/or # solar radiation sensor was present. # UV, default to True self.UV_sensor = tobool(import_config_dict.get('UV_sensor', True)) # solar, default to True self.solar_sensor = tobool(import_config_dict.get('solar_sensor', True)) # initialise ignore extreme > 255.0 values for temperature and # humidity fields for WD imports self.ignore_extr_th = False self.db_binding_wx = get_binding(config_dict) self.dbm = open_manager_with_config(config_dict, self.db_binding_wx, initialize=True, default_binding_dict={'table_name': 'archive', 'manager': 'weewx.wxmanager.DaySummaryManager', 'schema': 'schemas.wview_extended.schema'}) # get the unit system used in our db if self.dbm.std_unit_system is None: # we have a fresh archive (ie no records) so cannot deduce # the unit system in use, so go to our config_dict self.archive_unit_sys = unit_constants[self.config_dict['StdConvert'].get('target_unit', 'US')] else: # get our unit system from the archive db self.archive_unit_sys = self.dbm.std_unit_system # get ourselves a QC object to do QC on imported records self.import_QC = weewx.qc.QC(config_dict, parent='weeimport') # Process our command line options self.dry_run = options.dry_run self.verbose = options.verbose self.no_prompt = options.no_prompt self.suppress = options.suppress # By processing any --date, --from and --to options we need to derive # self.first_ts and self.last_ts; the earliest (exclusive) and latest # (inclusive) timestamps of data to be imported. If we have no --date, # --from or --to then set both to None (we then get the default action # for each import type). # First we see if we have a valid --date, if not then we look for # --from and --to. if options.date or options.date == "": # there is a --date but is it valid try: _first_dt = dt.strptime(options.date, "%Y-%m-%d") except ValueError: # Could not convert --date. If we have a --date it must be # valid otherwise we can't continue so raise it. _msg = "Invalid --date option specified." raise WeeImportOptionError(_msg) else: # we have a valid date so do some date arithmetic _last_dt = _first_dt + datetime.timedelta(days=1) self.first_ts = time.mktime(_first_dt.timetuple()) self.last_ts = time.mktime(_last_dt.timetuple()) elif options.date_from or options.date_to or options.date_from == '' or options.date_to == '': # There is a --from and/or a --to, but do we have both and are # they valid. # try --from first try: if 'T' in options.date_from: _from_dt = dt.strptime(options.date_from, "%Y-%m-%dT%H:%M") else: _from_dt = dt.strptime(options.date_from, "%Y-%m-%d") _from_ts = time.mktime(_from_dt.timetuple()) except TypeError: # --from not specified we can't continue so raise it _msg = "Missing --from option. Both --from and --to must be specified." raise WeeImportOptionError(_msg) except ValueError: # could not convert --from, we can't continue so raise it _msg = "Invalid --from option." raise WeeImportOptionError(_msg) # try --to try: if 'T' in options.date_to: _to_dt = dt.strptime(options.date_to, "%Y-%m-%dT%H:%M") else: _to_dt = dt.strptime(options.date_to, "%Y-%m-%d") # since it is just a date we want the end of the day _to_dt += datetime.timedelta(days=1) _to_ts = time.mktime(_to_dt.timetuple()) except TypeError: # --to not specified , we can't continue so raise it _msg = "Missing --to option. Both --from and --to must be specified." raise WeeImportOptionError(_msg) except ValueError: # could not convert --to, we can't continue so raise it _msg = "Invalid --to option." raise WeeImportOptionError(_msg) # If we made it here we have a _from_ts and _to_ts. Do a simple # error check first. if _from_ts > _to_ts: # from is later than to, raise it _msg = "--from value is later than --to value." raise WeeImportOptionError(_msg) self.first_ts = _from_ts self.last_ts = _to_ts else: # no --date or --from/--to so we take the default, set all to None self.first_ts = None self.last_ts = None # initialise a few properties we will need during the import # answer flags self.ans = None self.interval_ans = None # properties to help with processing multi-period imports self.period_no = None # total records processed self.total_rec_proc = 0 # total unique records identified self.total_unique_rec = 0 # total duplicate records identified self.total_duplicate_rec = 0 # time we started to first save self.t1 = None # time taken to process self.tdiff = None # earliest timestamp imported self.earliest_ts = None # latest timestamp imported self.latest_ts = None # initialise two sets to hold timestamps of records for which we # encountered duplicates # duplicates seen over all periods self.duplicates = set() # duplicates seen over the current period self.period_duplicates = set()
[ "def", "__init__", "(", "self", ",", "config_dict", ",", "import_config_dict", ",", "options", ")", ":", "# save our WeeWX config dict", "self", ".", "config_dict", "=", "config_dict", "# get our import config dict settings", "# interval, default to 'derive'", "self", ".", ...
https://github.com/weewx/weewx/blob/cb594fce224560bd8696050fc5c7843c7839320e/bin/weeimport/weeimport.py#L125-L282
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
official/legacy/detection/utils/input_utils.py
python
resize_and_crop_boxes
(boxes, image_scale, output_size, offset)
return boxes
Resizes boxes to output size with scale and offset. Args: boxes: `Tensor` of shape [N, 4] representing ground truth boxes. image_scale: 2D float `Tensor` representing scale factors that apply to [height, width] of input image. output_size: 2D `Tensor` or `int` representing [height, width] of target output image size. offset: 2D `Tensor` representing top-left corner [y0, x0] to crop scaled boxes. Returns: boxes: `Tensor` of shape [N, 4] representing the scaled boxes.
Resizes boxes to output size with scale and offset.
[ "Resizes", "boxes", "to", "output", "size", "with", "scale", "and", "offset", "." ]
def resize_and_crop_boxes(boxes, image_scale, output_size, offset): """Resizes boxes to output size with scale and offset. Args: boxes: `Tensor` of shape [N, 4] representing ground truth boxes. image_scale: 2D float `Tensor` representing scale factors that apply to [height, width] of input image. output_size: 2D `Tensor` or `int` representing [height, width] of target output image size. offset: 2D `Tensor` representing top-left corner [y0, x0] to crop scaled boxes. Returns: boxes: `Tensor` of shape [N, 4] representing the scaled boxes. """ # Adjusts box coordinates based on image_scale and offset. boxes *= tf.tile(tf.expand_dims(image_scale, axis=0), [1, 2]) boxes -= tf.tile(tf.expand_dims(offset, axis=0), [1, 2]) # Clips the boxes. boxes = box_utils.clip_boxes(boxes, output_size) return boxes
[ "def", "resize_and_crop_boxes", "(", "boxes", ",", "image_scale", ",", "output_size", ",", "offset", ")", ":", "# Adjusts box coordinates based on image_scale and offset.", "boxes", "*=", "tf", ".", "tile", "(", "tf", ".", "expand_dims", "(", "image_scale", ",", "ax...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/legacy/detection/utils/input_utils.py#L305-L325
espnet/espnet
ea411f3f627b8f101c211e107d0ff7053344ac80
espnet/nets/pytorch_backend/e2e_vc_tacotron2.py
python
Tacotron2.add_arguments
(parser)
return parser
Add model-specific arguments to the parser.
Add model-specific arguments to the parser.
[ "Add", "model", "-", "specific", "arguments", "to", "the", "parser", "." ]
def add_arguments(parser): """Add model-specific arguments to the parser.""" group = parser.add_argument_group("tacotron 2 model setting") # encoder group.add_argument( "--elayers", default=1, type=int, help="Number of encoder layers" ) group.add_argument( "--eunits", "-u", default=512, type=int, help="Number of encoder hidden units", ) group.add_argument( "--econv-layers", default=3, type=int, help="Number of encoder convolution layers", ) group.add_argument( "--econv-chans", default=512, type=int, help="Number of encoder convolution channels", ) group.add_argument( "--econv-filts", default=5, type=int, help="Filter size of encoder convolution", ) # attention group.add_argument( "--atype", default="location", type=str, choices=["forward_ta", "forward", "location"], help="Type of attention mechanism", ) group.add_argument( "--adim", default=512, type=int, help="Number of attention transformation dimensions", ) group.add_argument( "--aconv-chans", default=32, type=int, help="Number of attention convolution channels", ) group.add_argument( "--aconv-filts", default=15, type=int, help="Filter size of attention convolution", ) group.add_argument( "--cumulate-att-w", default=True, type=strtobool, help="Whether or not to cumulate attention weights", ) # decoder group.add_argument( "--dlayers", default=2, type=int, help="Number of decoder layers" ) group.add_argument( "--dunits", default=1024, type=int, help="Number of decoder hidden units" ) group.add_argument( "--prenet-layers", default=2, type=int, help="Number of prenet layers" ) group.add_argument( "--prenet-units", default=256, type=int, help="Number of prenet hidden units", ) group.add_argument( "--postnet-layers", default=5, type=int, help="Number of postnet layers" ) group.add_argument( "--postnet-chans", default=512, type=int, help="Number of postnet channels" ) group.add_argument( "--postnet-filts", default=5, type=int, help="Filter size of postnet" ) group.add_argument( "--output-activation", default=None, type=str, nargs="?", help="Output activation function", ) # cbhg group.add_argument( "--use-cbhg", default=False, type=strtobool, help="Whether to use CBHG module", ) group.add_argument( "--cbhg-conv-bank-layers", default=8, type=int, help="Number of convoluional bank layers in CBHG", ) group.add_argument( "--cbhg-conv-bank-chans", default=128, type=int, help="Number of convoluional bank channles in CBHG", ) group.add_argument( "--cbhg-conv-proj-filts", default=3, type=int, help="Filter size of convoluional projection layer in CBHG", ) group.add_argument( "--cbhg-conv-proj-chans", default=256, type=int, help="Number of convoluional projection channels in CBHG", ) group.add_argument( "--cbhg-highway-layers", default=4, type=int, help="Number of highway layers in CBHG", ) group.add_argument( "--cbhg-highway-units", default=128, type=int, help="Number of highway units in CBHG", ) group.add_argument( "--cbhg-gru-units", default=256, type=int, help="Number of GRU units in CBHG", ) # model (parameter) related group.add_argument( "--use-batch-norm", default=True, type=strtobool, help="Whether to use batch normalization", ) group.add_argument( "--use-concate", default=True, type=strtobool, help="Whether to concatenate encoder embedding with decoder outputs", ) group.add_argument( "--use-residual", default=True, type=strtobool, help="Whether to use residual connection in conv layer", ) group.add_argument( "--dropout-rate", default=0.5, type=float, help="Dropout rate" ) group.add_argument( "--zoneout-rate", default=0.1, type=float, help="Zoneout rate" ) group.add_argument( "--reduction-factor", default=1, type=int, help="Reduction factor (for decoder)", ) group.add_argument( "--encoder-reduction-factor", default=1, type=int, help="Reduction factor (for encoder)", ) group.add_argument( "--spk-embed-dim", default=None, type=int, help="Number of speaker embedding dimensions", ) group.add_argument( "--spc-dim", default=None, type=int, help="Number of spectrogram dimensions" ) group.add_argument( "--pretrained-model", default=None, type=str, help="Pretrained model path" ) # loss related group.add_argument( "--use-masking", default=False, type=strtobool, help="Whether to use masking in calculation of loss", ) group.add_argument( "--bce-pos-weight", default=20.0, type=float, help="Positive sample weight in BCE calculation " "(only for use-masking=True)", ) group.add_argument( "--use-guided-attn-loss", default=False, type=strtobool, help="Whether to use guided attention loss", ) group.add_argument( "--guided-attn-loss-sigma", default=0.4, type=float, help="Sigma in guided attention loss", ) group.add_argument( "--guided-attn-loss-lambda", default=1.0, type=float, help="Lambda in guided attention loss", ) group.add_argument( "--src-reconstruction-loss-lambda", default=1.0, type=float, help="Lambda in source reconstruction loss", ) group.add_argument( "--trg-reconstruction-loss-lambda", default=1.0, type=float, help="Lambda in target reconstruction loss", ) return parser
[ "def", "add_arguments", "(", "parser", ")", ":", "group", "=", "parser", ".", "add_argument_group", "(", "\"tacotron 2 model setting\"", ")", "# encoder", "group", ".", "add_argument", "(", "\"--elayers\"", ",", "default", "=", "1", ",", "type", "=", "int", ",...
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet/nets/pytorch_backend/e2e_vc_tacotron2.py#L38-L276
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/noVNC/utils/websocket.py
python
WebSocketServer.send_close
(self, code=1000, reason='')
Send a WebSocket orderly close frame.
Send a WebSocket orderly close frame.
[ "Send", "a", "WebSocket", "orderly", "close", "frame", "." ]
def send_close(self, code=1000, reason=''): """ Send a WebSocket orderly close frame. """ if self.version.startswith("hybi"): msg = pack(">H%ds" % len(reason), code, reason) buf, h, t = self.encode_hybi(msg, opcode=0x08, base64=False) self.client.send(buf) elif self.version == "hixie-76": buf = s2b('\xff\x00') self.client.send(buf)
[ "def", "send_close", "(", "self", ",", "code", "=", "1000", ",", "reason", "=", "''", ")", ":", "if", "self", ".", "version", ".", "startswith", "(", "\"hybi\"", ")", ":", "msg", "=", "pack", "(", "\">H%ds\"", "%", "len", "(", "reason", ")", ",", ...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/noVNC/utils/websocket.py#L560-L571
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/wheel/install.py
python
VerifyingZipFile.open
(self, name_or_info, mode="r", pwd=None)
return ef
Return file-like object for 'name'.
Return file-like object for 'name'.
[ "Return", "file", "-", "like", "object", "for", "name", "." ]
def open(self, name_or_info, mode="r", pwd=None): """Return file-like object for 'name'.""" # A non-monkey-patched version would contain most of zipfile.py ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd) if isinstance(name_or_info, zipfile.ZipInfo): name = name_or_info.filename else: name = name_or_info if (name in self._expected_hashes and self._expected_hashes[name] != None): expected_hash = self._expected_hashes[name] try: _update_crc_orig = ef._update_crc except AttributeError: warnings.warn('Need ZipExtFile._update_crc to implement ' 'file hash verification (in Python >= 2.7)') return ef running_hash = self._hash_algorithm() if hasattr(ef, '_eof'): # py33 def _update_crc(data): _update_crc_orig(data) running_hash.update(data) if ef._eof and running_hash.digest() != expected_hash: raise BadWheelFile("Bad hash for file %r" % ef.name) else: def _update_crc(data, eof=None): _update_crc_orig(data, eof=eof) running_hash.update(data) if eof and running_hash.digest() != expected_hash: raise BadWheelFile("Bad hash for file %r" % ef.name) ef._update_crc = _update_crc elif self.strict and name not in self._expected_hashes: raise BadWheelFile("No expected hash for file %r" % ef.name) return ef
[ "def", "open", "(", "self", ",", "name_or_info", ",", "mode", "=", "\"r\"", ",", "pwd", "=", "None", ")", ":", "# A non-monkey-patched version would contain most of zipfile.py", "ef", "=", "zipfile", ".", "ZipFile", ".", "open", "(", "self", ",", "name_or_info",...
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/wheel/install.py#L434-L467
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/PDB/Chain.py
python
Chain.get_atoms
(self)
Return atoms from residues.
Return atoms from residues.
[ "Return", "atoms", "from", "residues", "." ]
def get_atoms(self): """Return atoms from residues.""" for r in self.get_residues(): yield from r
[ "def", "get_atoms", "(", "self", ")", ":", "for", "r", "in", "self", ".", "get_residues", "(", ")", ":", "yield", "from", "r" ]
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/PDB/Chain.py#L173-L176
spywhere/Javatar
e273ec40c209658247a71b109bb90cd126984a29
commands/settings/project_settings.py
python
JavatarProjectSettingsCommand.remove_dependency
(self, dependency, from_global=True)
Remove specified dependency from the settings @param dependency: a dependency to remove @param from_global: a boolean specified whether the settings will be remove from global settings or not
Remove specified dependency from the settings
[ "Remove", "specified", "dependency", "from", "the", "settings" ]
def remove_dependency(self, dependency, from_global=True): """ Remove specified dependency from the settings @param dependency: a dependency to remove @param from_global: a boolean specified whether the settings will be remove from global settings or not """ dependencies = Settings().get( "dependencies", [], from_global=from_global ) if dependency in dependencies: dependencies.remove(dependency) Settings().set("dependencies", dependencies, to_global=from_global) DependencyManager().refresh_dependencies() menu_name = "global" if from_global else "local" menu_name += "_dependencies" self.show_menu(menu_name) self.show_delayed_status("Dependency \"%s\" has been removed" % ( os.path.basename(dependency) ))
[ "def", "remove_dependency", "(", "self", ",", "dependency", ",", "from_global", "=", "True", ")", ":", "dependencies", "=", "Settings", "(", ")", ".", "get", "(", "\"dependencies\"", ",", "[", "]", ",", "from_global", "=", "from_global", ")", "if", "depend...
https://github.com/spywhere/Javatar/blob/e273ec40c209658247a71b109bb90cd126984a29/commands/settings/project_settings.py#L510-L535
LinkedInAttic/indextank-service
880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e
api/restresource.py
python
get_index_param
(func)
return decorated
Decorator that validates the existence of an index_name param, and parses it into the "index" variable. If no index with that name exist, it parses "None" into the index param, but the decorated function does run.
Decorator that validates the existence of an index_name param, and parses it into the "index" variable. If no index with that name exist, it parses "None" into the index param, but the decorated function does run.
[ "Decorator", "that", "validates", "the", "existence", "of", "an", "index_name", "param", "and", "parses", "it", "into", "the", "index", "variable", ".", "If", "no", "index", "with", "that", "name", "exist", "it", "parses", "None", "into", "the", "index", "...
def get_index_param(func): ''' Decorator that validates the existence of an index_name param, and parses it into the "index" variable. If no index with that name exist, it parses "None" into the index param, but the decorated function does run. ''' def decorated(self, request, **kwargs): if 'index_name' in kwargs: index = self.get_index(kwargs['index_name']) kwargs['index'] = index del kwargs['index_name'] return func(self, request, **kwargs) return decorated
[ "def", "get_index_param", "(", "func", ")", ":", "def", "decorated", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "'index_name'", "in", "kwargs", ":", "index", "=", "self", ".", "get_index", "(", "kwargs", "[", "'index_name'", ...
https://github.com/LinkedInAttic/indextank-service/blob/880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e/api/restresource.py#L496-L509
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
retopoflow/rfmesh/rfmesh.py
python
RFMesh.iter_edges
(self)
[]
def iter_edges(self): wrap = self._wrap_bmedge for bme in self.bme.edges: if not bme.is_valid: continue yield wrap(bme)
[ "def", "iter_edges", "(", "self", ")", ":", "wrap", "=", "self", ".", "_wrap_bmedge", "for", "bme", "in", "self", ".", "bme", ".", "edges", ":", "if", "not", "bme", ".", "is_valid", ":", "continue", "yield", "wrap", "(", "bme", ")" ]
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/retopoflow/rfmesh/rfmesh.py#L947-L951
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/venv/lib/python2.7/site-packages/pip/_vendor/pyparsing.py
python
ParserElement.split
(self, instring, maxsplit=_MAX_INT, includeSeparators=False)
Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
[ "Generator", "method", "to", "split", "a", "string", "using", "the", "given", "expression", "as", "a", "separator", ".", "May", "be", "called", "with", "optional", "C", "{", "maxsplit", "}", "argument", "to", "limit", "the", "number", "of", "splits", ";", ...
def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False): """ Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] """ splits = 0 last = 0 for t,s,e in self.scanString(instring, maxMatches=maxsplit): yield instring[last:s] if includeSeparators: yield t[0] last = e yield instring[last:]
[ "def", "split", "(", "self", ",", "instring", ",", "maxsplit", "=", "_MAX_INT", ",", "includeSeparators", "=", "False", ")", ":", "splits", "=", "0", "last", "=", "0", "for", "t", ",", "s", ",", "e", "in", "self", ".", "scanString", "(", "instring", ...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/venv/lib/python2.7/site-packages/pip/_vendor/pyparsing.py#L1758-L1778
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/gdata/samples/oauth/oauth_on_appengine/main_hmac.py
python
RevokeToken.get
(self)
Revokes the current user's OAuth access token.
Revokes the current user's OAuth access token.
[ "Revokes", "the", "current", "user", "s", "OAuth", "access", "token", "." ]
def get(self): """Revokes the current user's OAuth access token.""" try: gdocs.RevokeOAuthToken() except gdata.service.RevokingOAuthTokenFailed: pass gdocs.token_store.remove_all_tokens() self.redirect('/')
[ "def", "get", "(", "self", ")", ":", "try", ":", "gdocs", ".", "RevokeOAuthToken", "(", ")", "except", "gdata", ".", "service", ".", "RevokingOAuthTokenFailed", ":", "pass", "gdocs", ".", "token_store", ".", "remove_all_tokens", "(", ")", "self", ".", "red...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/gdata/samples/oauth/oauth_on_appengine/main_hmac.py#L182-L191
sdispater/orator
0666e522be914db285b6936e3c36801fc1a9c2e7
orator/connectors/connector.py
python
Connector._get_database_platform_version
(self)
return self.get_server_version()
Returns the version of the related platform if applicable. Returns None if either the connector is not capable to create version specific platform instances, no explicit server version was specified or the underlying driver connection cannot determine the platform version without having to query it (performance reasons). :rtype: str or None
Returns the version of the related platform if applicable.
[ "Returns", "the", "version", "of", "the", "related", "platform", "if", "applicable", "." ]
def _get_database_platform_version(self): """ Returns the version of the related platform if applicable. Returns None if either the connector is not capable to create version specific platform instances, no explicit server version was specified or the underlying driver connection cannot determine the platform version without having to query it (performance reasons). :rtype: str or None """ # Connector does not support version specific platforms. if not self.is_version_aware(): return None return self.get_server_version()
[ "def", "_get_database_platform_version", "(", "self", ")", ":", "# Connector does not support version specific platforms.", "if", "not", "self", ".", "is_version_aware", "(", ")", ":", "return", "None", "return", "self", ".", "get_server_version", "(", ")" ]
https://github.com/sdispater/orator/blob/0666e522be914db285b6936e3c36801fc1a9c2e7/orator/connectors/connector.py#L80-L95
hasgeek/lastuser
fbbb86a08939c952bbd6eb90d0aea8cb1a731f26
lastuser_core/models/user.py
python
User.organizations_owned
(self)
return sorted( { team.organization for team in self.teams if team.organization.owners == team }, key=lambda o: o.title, )
Return the organizations this user is an owner of.
Return the organizations this user is an owner of.
[ "Return", "the", "organizations", "this", "user", "is", "an", "owner", "of", "." ]
def organizations_owned(self): """ Return the organizations this user is an owner of. """ return sorted( { team.organization for team in self.teams if team.organization.owners == team }, key=lambda o: o.title, )
[ "def", "organizations_owned", "(", "self", ")", ":", "return", "sorted", "(", "{", "team", ".", "organization", "for", "team", "in", "self", ".", "teams", "if", "team", ".", "organization", ".", "owners", "==", "team", "}", ",", "key", "=", "lambda", "...
https://github.com/hasgeek/lastuser/blob/fbbb86a08939c952bbd6eb90d0aea8cb1a731f26/lastuser_core/models/user.py#L405-L416
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/mailbox.py
python
_PartialFile.tell
(self)
return _ProxyFile.tell(self) - self._start
Return the position with respect to start.
Return the position with respect to start.
[ "Return", "the", "position", "with", "respect", "to", "start", "." ]
def tell(self): """Return the position with respect to start.""" return _ProxyFile.tell(self) - self._start
[ "def", "tell", "(", "self", ")", ":", "return", "_ProxyFile", ".", "tell", "(", "self", ")", "-", "self", ".", "_start" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/mailbox.py#L2023-L2025
bloomberg/phabricator-tools
09bd1587fe8945d93a891162fd4c89640c6fada7
py/abd/abdt_rbranchnaming.py
python
Naming.make_tracker_branch_from_name
(self, branch_name)
return abdt_naming.TrackerBranch( naming=self, branch=branch_name, review_branch=review_branch, status=parts[0], base=base, description=parts[-2], rev_id=parts[-1], remote=self._remote)
Return the WorkingBranch for 'branch_name' or None if invalid. :branch_name: string name of the working branch :returns: WorkingBranch or None if invalid
Return the WorkingBranch for 'branch_name' or None if invalid.
[ "Return", "the", "WorkingBranch", "for", "branch_name", "or", "None", "if", "invalid", "." ]
def make_tracker_branch_from_name(self, branch_name): """Return the WorkingBranch for 'branch_name' or None if invalid. :branch_name: string name of the working branch :returns: WorkingBranch or None if invalid """ if branch_name == self._reserve_branch_prefix: raise abdt_naming.Error() # ignore the reserved branch suffix = phlsys_string.after_prefix( branch_name, self._tracking_branch_prefix) if not suffix: # review branches must start with the prefix raise abdt_naming.Error() # suffix should be status/r/base(/...)/description/id # 0/1/ 2 (/...)/ -2 /-1 parts = suffix.split("/") if len(parts) < 5: # suffix should be status/base(/...)/description/id raise abdt_naming.Error() review_prefix = parts[1] + '/' if review_prefix != self._review_branch_prefix: # doesn't begin with our review branch prefix raise abdt_naming.Error() base = '/'.join(parts[2:-2]) review_branch = '/'.join(parts[1:-1]) return abdt_naming.TrackerBranch( naming=self, branch=branch_name, review_branch=review_branch, status=parts[0], base=base, description=parts[-2], rev_id=parts[-1], remote=self._remote)
[ "def", "make_tracker_branch_from_name", "(", "self", ",", "branch_name", ")", ":", "if", "branch_name", "==", "self", ".", "_reserve_branch_prefix", ":", "raise", "abdt_naming", ".", "Error", "(", ")", "# ignore the reserved branch", "suffix", "=", "phlsys_string", ...
https://github.com/bloomberg/phabricator-tools/blob/09bd1587fe8945d93a891162fd4c89640c6fada7/py/abd/abdt_rbranchnaming.py#L65-L106
utiasSTARS/liegroups
fe1d376b7d33809dec78724b456f01833507c305
liegroups/_base.py
python
SOMatrixBase.as_matrix
(self)
return self.mat
Return the matrix representation of the rotation.
Return the matrix representation of the rotation.
[ "Return", "the", "matrix", "representation", "of", "the", "rotation", "." ]
def as_matrix(self): """Return the matrix representation of the rotation.""" return self.mat
[ "def", "as_matrix", "(", "self", ")", ":", "return", "self", ".", "mat" ]
https://github.com/utiasSTARS/liegroups/blob/fe1d376b7d33809dec78724b456f01833507c305/liegroups/_base.py#L153-L155
billpmurphy/hask
4609cc8d9d975f51b6ecdbd33640cdffdc28f953
hask/Data/List.py
python
notElem
(x, xs)
return not elem(x, xs)
notElem :: Eq a => a -> [a] -> Bool notElem is the negation of elem.
notElem :: Eq a => a -> [a] -> Bool
[ "notElem", "::", "Eq", "a", "=", ">", "a", "-", ">", "[", "a", "]", "-", ">", "Bool" ]
def notElem(x, xs): """ notElem :: Eq a => a -> [a] -> Bool notElem is the negation of elem. """ return not elem(x, xs)
[ "def", "notElem", "(", "x", ",", "xs", ")", ":", "return", "not", "elem", "(", "x", ",", "xs", ")" ]
https://github.com/billpmurphy/hask/blob/4609cc8d9d975f51b6ecdbd33640cdffdc28f953/hask/Data/List.py#L766-L772
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/pip/_vendor/distro.py
python
os_release_attr
(attribute)
return _distro.os_release_attr(attribute)
Return a single named information item from the os-release file data source of the current OS distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `os-release file`_ for details about these information items.
Return a single named information item from the os-release file data source of the current OS distribution.
[ "Return", "a", "single", "named", "information", "item", "from", "the", "os", "-", "release", "file", "data", "source", "of", "the", "current", "OS", "distribution", "." ]
def os_release_attr(attribute): """ Return a single named information item from the os-release file data source of the current OS distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `os-release file`_ for details about these information items. """ return _distro.os_release_attr(attribute)
[ "def", "os_release_attr", "(", "attribute", ")", ":", "return", "_distro", ".", "os_release_attr", "(", "attribute", ")" ]
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/distro.py#L464-L480
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py
python
_make_table
(db)
return _make_table
[]
def _make_table(db): def _make_table(*args, **kwargs): if len(args) > 1 and isinstance(args[1], db.Column): args = (args[0], db.metadata) + args[1:] info = kwargs.pop('info', None) or {} info.setdefault('bind_key', None) kwargs['info'] = info return sqlalchemy.Table(*args, **kwargs) return _make_table
[ "def", "_make_table", "(", "db", ")", ":", "def", "_make_table", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">", "1", "and", "isinstance", "(", "args", "[", "1", "]", ",", "db", ".", "Column", ")", ":", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py#L48-L56
ethereum/py-evm
026ee20f8d9b70d7c1b6a4fb9484d5489d425e54
eth/_utils/db.py
python
get_block_header_by_hash
(block_hash: Hash32, db: ChainDatabaseAPI)
return db.get_block_header_by_hash(block_hash)
Returns the header for the parent block.
Returns the header for the parent block.
[ "Returns", "the", "header", "for", "the", "parent", "block", "." ]
def get_block_header_by_hash(block_hash: Hash32, db: ChainDatabaseAPI) -> BlockHeaderAPI: """ Returns the header for the parent block. """ return db.get_block_header_by_hash(block_hash)
[ "def", "get_block_header_by_hash", "(", "block_hash", ":", "Hash32", ",", "db", ":", "ChainDatabaseAPI", ")", "->", "BlockHeaderAPI", ":", "return", "db", ".", "get_block_header_by_hash", "(", "block_hash", ")" ]
https://github.com/ethereum/py-evm/blob/026ee20f8d9b70d7c1b6a4fb9484d5489d425e54/eth/_utils/db.py#L22-L26
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/inject/lib/utils/api.py
python
Database.execute
(self, statement, arguments=None)
[]
def execute(self, statement, arguments=None): while True: try: if arguments: self.cursor.execute(statement, arguments) else: self.cursor.execute(statement) except sqlite3.OperationalError, ex: if not "locked" in getSafeExString(ex): raise else: break if statement.lstrip().upper().startswith("SELECT"): return self.cursor.fetchall()
[ "def", "execute", "(", "self", ",", "statement", ",", "arguments", "=", "None", ")", ":", "while", "True", ":", "try", ":", "if", "arguments", ":", "self", ".", "cursor", ".", "execute", "(", "statement", ",", "arguments", ")", "else", ":", "self", "...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/lib/utils/api.py#L83-L97
openai/universe
cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c
universe/remotes/allocator_remote.py
python
AllocatorManager.allocate
(self, handles, initial=False, params={})
Call from main thread. Initiate a request for more environments
Call from main thread. Initiate a request for more environments
[ "Call", "from", "main", "thread", ".", "Initiate", "a", "request", "for", "more", "environments" ]
def allocate(self, handles, initial=False, params={}): """Call from main thread. Initiate a request for more environments""" assert all(re.search('^\d+$', h) for h in handles), "All handles must be numbers: {}".format(handles) self.requests.put(('allocate', (handles, initial, params)))
[ "def", "allocate", "(", "self", ",", "handles", ",", "initial", "=", "False", ",", "params", "=", "{", "}", ")", ":", "assert", "all", "(", "re", ".", "search", "(", "'^\\d+$'", ",", "h", ")", "for", "h", "in", "handles", ")", ",", "\"All handles m...
https://github.com/openai/universe/blob/cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c/universe/remotes/allocator_remote.py#L166-L169
openai/finetune-transformer-lm
a69b5c43b0452462890bca8ff92fb75dee9290cf
text_utils.py
python
get_pairs
(word)
return pairs
Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings)
Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings)
[ "Return", "set", "of", "symbol", "pairs", "in", "a", "word", ".", "word", "is", "represented", "as", "tuple", "of", "symbols", "(", "symbols", "being", "variable", "-", "length", "strings", ")" ]
def get_pairs(word): """ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings) """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
[ "def", "get_pairs", "(", "word", ")", ":", "pairs", "=", "set", "(", ")", "prev_char", "=", "word", "[", "0", "]", "for", "char", "in", "word", "[", "1", ":", "]", ":", "pairs", ".", "add", "(", "(", "prev_char", ",", "char", ")", ")", "prev_ch...
https://github.com/openai/finetune-transformer-lm/blob/a69b5c43b0452462890bca8ff92fb75dee9290cf/text_utils.py#L8-L18
SoCo/SoCo
e83fef84d2645d05265dbd574598518655a9c125
soco/core.py
python
SoCo.supports_fixed_volume
(self)
return response["CurrentSupportsFixed"] == "1"
bool: Whether the device supports fixed volume output.
bool: Whether the device supports fixed volume output.
[ "bool", ":", "Whether", "the", "device", "supports", "fixed", "volume", "output", "." ]
def supports_fixed_volume(self): """bool: Whether the device supports fixed volume output.""" response = self.renderingControl.GetSupportsOutputFixed([("InstanceID", 0)]) return response["CurrentSupportsFixed"] == "1"
[ "def", "supports_fixed_volume", "(", "self", ")", ":", "response", "=", "self", ".", "renderingControl", ".", "GetSupportsOutputFixed", "(", "[", "(", "\"InstanceID\"", ",", "0", ")", "]", ")", "return", "response", "[", "\"CurrentSupportsFixed\"", "]", "==", ...
https://github.com/SoCo/SoCo/blob/e83fef84d2645d05265dbd574598518655a9c125/soco/core.py#L1339-L1343
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/schemes/elliptic_curves/height.py
python
UnionOfIntervals.__str__
(self)
return repr(self)
r""" Return the string representation of this UnionOfIntervals. EXAMPLES:: sage: from sage.schemes.elliptic_curves.height import UnionOfIntervals sage: A = UnionOfIntervals([1,3,5,7]) sage: str(A) '([1, 3] U [5, 7])'
r""" Return the string representation of this UnionOfIntervals.
[ "r", "Return", "the", "string", "representation", "of", "this", "UnionOfIntervals", "." ]
def __str__(self): r""" Return the string representation of this UnionOfIntervals. EXAMPLES:: sage: from sage.schemes.elliptic_curves.height import UnionOfIntervals sage: A = UnionOfIntervals([1,3,5,7]) sage: str(A) '([1, 3] U [5, 7])' """ return repr(self)
[ "def", "__str__", "(", "self", ")", ":", "return", "repr", "(", "self", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/elliptic_curves/height.py#L450-L461
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/decimal.py
python
Decimal._round_half_up
(self, prec)
Rounds 5 up (away from 0)
Rounds 5 up (away from 0)
[ "Rounds", "5", "up", "(", "away", "from", "0", ")" ]
def _round_half_up(self, prec): """Rounds 5 up (away from 0)""" if self._int[prec] in '56789': return 1 elif _all_zeros(self._int, prec): return 0 else: return -1
[ "def", "_round_half_up", "(", "self", ",", "prec", ")", ":", "if", "self", ".", "_int", "[", "prec", "]", "in", "'56789'", ":", "return", "1", "elif", "_all_zeros", "(", "self", ".", "_int", ",", "prec", ")", ":", "return", "0", "else", ":", "retur...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/decimal.py#L1747-L1754
atlassian-api/atlassian-python-api
6d8545a790c3aae10b75bdc225fb5c3a0aee44db
atlassian/bitbucket/server/projects/repos/__init__.py
python
Repositories.get
(self, repository, by="slug")
Returns the requested repository. :param repository: string: The requested repository. :param by: string (default is "slug"): How to interpret project, can be 'slug' or 'name'. :return: The requested Repository object
Returns the requested repository.
[ "Returns", "the", "requested", "repository", "." ]
def get(self, repository, by="slug"): """ Returns the requested repository. :param repository: string: The requested repository. :param by: string (default is "slug"): How to interpret project, can be 'slug' or 'name'. :return: The requested Repository object """ if by == "slug": return self.__get_object(super(Repositories, self).get(repository)) elif by == "name": for r in self.each(): print(r.name) if r.name == repository: return r else: ValueError("Unknown value '{}' for argument [by], expected 'slug' or 'name'".format(by)) raise Exception("Unknown repository {} '{}'".format(by, repository))
[ "def", "get", "(", "self", ",", "repository", ",", "by", "=", "\"slug\"", ")", ":", "if", "by", "==", "\"slug\"", ":", "return", "self", ".", "__get_object", "(", "super", "(", "Repositories", ",", "self", ")", ".", "get", "(", "repository", ")", ")"...
https://github.com/atlassian-api/atlassian-python-api/blob/6d8545a790c3aae10b75bdc225fb5c3a0aee44db/atlassian/bitbucket/server/projects/repos/__init__.py#L38-L57
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
gluon/gluoncv2/models/resnext_cifar.py
python
resnext20_2x64d_cifar10
(classes=10, **kwargs)
return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=64, model_name="resnext20_2x64d_cifar10", **kwargs)
ResNeXt-20 (2x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '~/.mxnet/models' Location for keeping the model parameters.
ResNeXt-20 (2x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431.
[ "ResNeXt", "-", "20", "(", "2x64d", ")", "model", "for", "CIFAR", "-", "10", "from", "Aggregated", "Residual", "Transformations", "for", "Deep", "Neural", "Networks", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1611", ".", "05431", "." ]
def resnext20_2x64d_cifar10(classes=10, **kwargs): """ ResNeXt-20 (2x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '~/.mxnet/models' Location for keeping the model parameters. """ return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=64, model_name="resnext20_2x64d_cifar10", **kwargs)
[ "def", "resnext20_2x64d_cifar10", "(", "classes", "=", "10", ",", "*", "*", "kwargs", ")", ":", "return", "get_resnext_cifar", "(", "classes", "=", "classes", ",", "blocks", "=", "20", ",", "cardinality", "=", "2", ",", "bottleneck_width", "=", "64", ",", ...
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/gluon/gluoncv2/models/resnext_cifar.py#L294-L311
getpatchwork/patchwork
60a7b11d12f9e1a6bd08d787d37066c8d89a52ae
patchwork/templatetags/syntax.py
python
_compile
(value)
return re.compile(regex, re.M | re.I), cls
[]
def _compile(value): regex, cls = value return re.compile(regex, re.M | re.I), cls
[ "def", "_compile", "(", "value", ")", ":", "regex", ",", "cls", "=", "value", "return", "re", ".", "compile", "(", "regex", ",", "re", ".", "M", "|", "re", ".", "I", ")", ",", "cls" ]
https://github.com/getpatchwork/patchwork/blob/60a7b11d12f9e1a6bd08d787d37066c8d89a52ae/patchwork/templatetags/syntax.py#L16-L18
autopkg/recipes
d8777580f50dd511f667a99cd899cce51e1908fb
MSOffice2011Updates/MSOffice2011UpdateInfoProvider.py
python
MSOffice2011UpdateInfoProvider.value_to_os_version_string
(self, value)
return "%s.%s.%s" % (major, minor, patch)
Converts a value to an OS X version number
Converts a value to an OS X version number
[ "Converts", "a", "value", "to", "an", "OS", "X", "version", "number" ]
def value_to_os_version_string(self, value): """Converts a value to an OS X version number""" # Map string type for both Python 2 and Python 3. try: _ = basestring # noqa: F823 except NameError: basestring = str if isinstance(value, int): version_str = hex(value)[2:] elif isinstance(value, basestring): if value.startswith("0x"): version_str = value[2:] # OS versions are encoded as hex: # 4184 = 0x1058 = 10.5.8 # not sure how 10.4.11 would be encoded; # guessing 0x104B ? major = 0 minor = 0 patch = 0 try: if len(version_str) == 1: major = int(version_str[0]) if len(version_str) > 1: major = int(version_str[0:2]) if len(version_str) > 2: minor = int(version_str[2], 16) if len(version_str) > 3: patch = int(version_str[3], 16) except ValueError: raise ProcessorError("Unexpected value in version: %s" % value) return "%s.%s.%s" % (major, minor, patch)
[ "def", "value_to_os_version_string", "(", "self", ",", "value", ")", ":", "# Map string type for both Python 2 and Python 3.", "try", ":", "_", "=", "basestring", "# noqa: F823", "except", "NameError", ":", "basestring", "=", "str", "if", "isinstance", "(", "value", ...
https://github.com/autopkg/recipes/blob/d8777580f50dd511f667a99cd899cce51e1908fb/MSOffice2011Updates/MSOffice2011UpdateInfoProvider.py#L174-L205
cortex-lab/phy
9a330b9437a3d0b40a37a201d147224e6e7fb462
phy/cluster/_history.py
python
History.clear
(self, base_item=None)
Clear the history.
Clear the history.
[ "Clear", "the", "history", "." ]
def clear(self, base_item=None): """Clear the history.""" # List of changes, contains at least the base item. self._history = [base_item] # Index of the current item. self._index = 0
[ "def", "clear", "(", "self", ",", "base_item", "=", "None", ")", ":", "# List of changes, contains at least the base item.", "self", ".", "_history", "=", "[", "base_item", "]", "# Index of the current item.", "self", ".", "_index", "=", "0" ]
https://github.com/cortex-lab/phy/blob/9a330b9437a3d0b40a37a201d147224e6e7fb462/phy/cluster/_history.py#L20-L25
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/dns/name.py
python
Name.to_digestable
(self, origin=None)
return self.to_wire(origin=origin, canonicalize=True)
Convert name to a format suitable for digesting in hashes. The name is canonicalized and converted to uncompressed wire format. All names in wire format are absolute. If the name is a relative name, then an origin must be supplied. *origin* is a ``dns.name.Name`` or ``None``. If the name is relative and origin is not ``None``, then origin will be appended to the name. Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is relative and no origin was provided. Returns a ``bytes``.
Convert name to a format suitable for digesting in hashes.
[ "Convert", "name", "to", "a", "format", "suitable", "for", "digesting", "in", "hashes", "." ]
def to_digestable(self, origin=None): """Convert name to a format suitable for digesting in hashes. The name is canonicalized and converted to uncompressed wire format. All names in wire format are absolute. If the name is a relative name, then an origin must be supplied. *origin* is a ``dns.name.Name`` or ``None``. If the name is relative and origin is not ``None``, then origin will be appended to the name. Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is relative and no origin was provided. Returns a ``bytes``. """ return self.to_wire(origin=origin, canonicalize=True)
[ "def", "to_digestable", "(", "self", ",", "origin", "=", "None", ")", ":", "return", "self", ".", "to_wire", "(", "origin", "=", "origin", ",", "canonicalize", "=", "True", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/dns/name.py#L580-L597
KhronosGroup/NNEF-Tools
c913758ca687dab8cb7b49e8f1556819a2d0ca25
nnef_tools/io/tf/lite/flatbuffers/Model.py
python
Model.MetadataBufferIsNone
(self)
return o == 0
[]
def MetadataBufferIsNone(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) return o == 0
[ "def", "MetadataBufferIsNone", "(", "self", ")", ":", "o", "=", "flatbuffers", ".", "number_types", ".", "UOffsetTFlags", ".", "py_type", "(", "self", ".", "_tab", ".", "Offset", "(", "14", ")", ")", "return", "o", "==", "0" ]
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/io/tf/lite/flatbuffers/Model.py#L139-L141
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/venv/lib/python2.7/site-packages/pip/index.py
python
PackageFinder._find_all_versions
(self, project_name)
return ( file_versions + find_links_versions + page_versions + dependency_versions )
Find all available versions for project_name This checks index_urls, find_links and dependency_links All versions found are returned See _link_package_versions for details on which files are accepted
Find all available versions for project_name
[ "Find", "all", "available", "versions", "for", "project_name" ]
def _find_all_versions(self, project_name): """Find all available versions for project_name This checks index_urls, find_links and dependency_links All versions found are returned 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) dep_file_loc, dep_url_loc = self._sort_locations(self.dependency_links) file_locations = ( Link(url) for url in itertools.chain( index_file_loc, fl_file_loc, dep_file_loc) ) # We trust every url that the user has given us whether it was given # via --index-url or --find-links # We explicitly do not trust links that came from dependency_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, trusted=True) for url in index_url_loc), (Link(url, trusted=True) for url in fl_url_loc), (Link(url) for url in dep_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 = pkg_resources.safe_name(project_name).lower() formats = fmt_ctl_formats(self.format_control, canonical_name) search = Search(project_name.lower(), canonical_name, formats) find_links_versions = self._package_versions( # We trust every directly linked archive in find_links (Link(url, '-f', trusted=True) 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.links, search) ) dependency_versions = self._package_versions( (Link(url) for url in self.dependency_links), search ) if dependency_versions: logger.debug( 'dependency_links found: %s', ', '.join([ version.location.url for version in dependency_versions ]) ) 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 + dependency_versions )
[ "def", "_find_all_versions", "(", "self", ",", "project_name", ")", ":", "index_locations", "=", "self", ".", "_get_index_urls_locations", "(", "project_name", ")", "index_file_loc", ",", "index_url_loc", "=", "self", ".", "_sort_locations", "(", "index_locations", ...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/venv/lib/python2.7/site-packages/pip/index.py#L396-L477
qilingframework/qiling
32cc674f2f6fa4b4c9d64a35a1a57853fe1e4142
qiling/arch/evm/abc.py
python
AccountDatabaseAPI.delete_storage
(self, address: Address)
Delete the storage at ``address``.
Delete the storage at ``address``.
[ "Delete", "the", "storage", "at", "address", "." ]
def delete_storage(self, address: Address) -> None: """ Delete the storage at ``address``. """ ...
[ "def", "delete_storage", "(", "self", ",", "address", ":", "Address", ")", "->", "None", ":", "..." ]
https://github.com/qilingframework/qiling/blob/32cc674f2f6fa4b4c9d64a35a1a57853fe1e4142/qiling/arch/evm/abc.py#L1136-L1140
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
whois_lambda/dns/name.py
python
Name.concatenate
(self, other)
return Name(labels)
Return a new name which is the concatenation of self and other. @rtype: dns.name.Name object @raises AbsoluteConcatenation: self is absolute and other is not the empty name
Return a new name which is the concatenation of self and other.
[ "Return", "a", "new", "name", "which", "is", "the", "concatenation", "of", "self", "and", "other", "." ]
def concatenate(self, other): """Return a new name which is the concatenation of self and other. @rtype: dns.name.Name object @raises AbsoluteConcatenation: self is absolute and other is not the empty name """ if self.is_absolute() and len(other) > 0: raise AbsoluteConcatenation labels = list(self.labels) labels.extend(list(other.labels)) return Name(labels)
[ "def", "concatenate", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_absolute", "(", ")", "and", "len", "(", "other", ")", ">", "0", ":", "raise", "AbsoluteConcatenation", "labels", "=", "list", "(", "self", ".", "labels", ")", "labels", ...
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/whois_lambda/dns/name.py#L672-L683
ulule/django-linguist
dad1ccacb02ab9aa3b05da3bcfbade6e1da70ddb
linguist/utils.py
python
get_supported_languages
()
return [code.replace("-", "_") for code, name in settings.SUPPORTED_LANGUAGES]
Returns supported languages list.
Returns supported languages list.
[ "Returns", "supported", "languages", "list", "." ]
def get_supported_languages(): """ Returns supported languages list. """ return [code.replace("-", "_") for code, name in settings.SUPPORTED_LANGUAGES]
[ "def", "get_supported_languages", "(", ")", ":", "return", "[", "code", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "for", "code", ",", "name", "in", "settings", ".", "SUPPORTED_LANGUAGES", "]" ]
https://github.com/ulule/django-linguist/blob/dad1ccacb02ab9aa3b05da3bcfbade6e1da70ddb/linguist/utils.py#L70-L74
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/tornado/locale.py
python
load_translations
(directory)
Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular". A given string can have both singular and plural forms. For example ``%(name)s liked this`` may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural". For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all). The file is read using the `csv` module in the default "excel" dialect. In this format there should not be spaces after the commas. Example translation ``es_LA.csv``:: "I love you","Te amo" "%(name)s liked this","A %(name)s les gustó esto","plural" "%(name)s liked this","A %(name)s le gustó esto","singular"
Loads translations from CSV files in a directory.
[ "Loads", "translations", "from", "CSV", "files", "in", "a", "directory", "." ]
def load_translations(directory): """Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular". A given string can have both singular and plural forms. For example ``%(name)s liked this`` may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural". For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all). The file is read using the `csv` module in the default "excel" dialect. In this format there should not be spaces after the commas. Example translation ``es_LA.csv``:: "I love you","Te amo" "%(name)s liked this","A %(name)s les gustó esto","plural" "%(name)s liked this","A %(name)s le gustó esto","singular" """ global _translations global _supported_locales _translations = {} for path in os.listdir(directory): if not path.endswith(".csv"): continue locale, extension = path.split(".") if not re.match("[a-z]+(_[A-Z]+)?$", locale): gen_log.error("Unrecognized locale %r (path: %s)", locale, os.path.join(directory, path)) continue full_path = os.path.join(directory, path) try: # python 3: csv.reader requires a file open in text mode. # Force utf8 to avoid dependence on $LANG environment variable. f = open(full_path, "r", encoding="utf-8") except TypeError: # python 2: files return byte strings, which are decoded below. f = open(full_path, "r") _translations[locale] = {} for i, row in enumerate(csv.reader(f)): if not row or len(row) < 2: continue row = [escape.to_unicode(c).strip() for c in row] english, translation = row[:2] if len(row) > 2: plural = row[2] or "unknown" else: plural = "unknown" if plural not in ("plural", "singular", "unknown"): gen_log.error("Unrecognized plural indicator %r in %s line %d", plural, path, i + 1) continue _translations[locale].setdefault(plural, {})[english] = translation f.close() _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) gen_log.debug("Supported locales: %s", sorted(_supported_locales))
[ "def", "load_translations", "(", "directory", ")", ":", "global", "_translations", "global", "_supported_locales", "_translations", "=", "{", "}", "for", "path", "in", "os", ".", "listdir", "(", "directory", ")", ":", "if", "not", "path", ".", "endswith", "(...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/tornado/locale.py#L88-L151
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
ibm_was/datadog_checks/ibm_was/config_models/defaults.py
python
shared_proxy
(field, value)
return get_default_field_value(field, value)
[]
def shared_proxy(field, value): return get_default_field_value(field, value)
[ "def", "shared_proxy", "(", "field", ",", "value", ")", ":", "return", "get_default_field_value", "(", "field", ",", "value", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/ibm_was/datadog_checks/ibm_was/config_models/defaults.py#L13-L14
keras-team/keras
5caa668b6a415675064a730f5eb46ecc08e40f65
keras/utils/data_utils.py
python
get_file
(fname=None, origin=None, untar=False, md5_hash=None, file_hash=None, cache_subdir='datasets', hash_algorithm='auto', extract=False, archive_format='auto', cache_dir=None)
return fpath
Downloads a file from a URL if it not already in the cache. By default the file at the url `origin` is downloaded to the cache_dir `~/.keras`, placed in the cache_subdir `datasets`, and given the filename `fname`. The final location of a file `example.txt` would therefore be `~/.keras/datasets/example.txt`. Files in tar, tar.gz, tar.bz, and zip formats can also be extracted. Passing a hash will verify the file after download. The command line programs `shasum` and `sha256sum` can compute the hash. Example: ```python path_to_downloaded_file = tf.keras.utils.get_file( "flower_photos", "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz", untar=True) ``` Args: fname: Name of the file. If an absolute path `/path/to/file.txt` is specified the file will be saved at that location. If `None`, the name of the file at `origin` will be used. origin: Original URL of the file. untar: Deprecated in favor of `extract` argument. boolean, whether the file should be decompressed md5_hash: Deprecated in favor of `file_hash` argument. md5 hash of the file for verification file_hash: The expected hash string of the file after download. The sha256 and md5 hash algorithms are both supported. cache_subdir: Subdirectory under the Keras cache dir where the file is saved. If an absolute path `/path/to/folder` is specified the file will be saved at that location. hash_algorithm: Select the hash algorithm to verify the file. options are `'md5'`, `'sha256'`, and `'auto'`. The default 'auto' detects the hash algorithm in use. extract: True tries extracting the file as an Archive, like tar or zip. archive_format: Archive format to try for extracting the file. Options are `'auto'`, `'tar'`, `'zip'`, and `None`. `'tar'` includes tar, tar.gz, and tar.bz files. The default `'auto'` corresponds to `['tar', 'zip']`. None or an empty list will return no matches found. cache_dir: Location to store cached files, when None it defaults to the default directory `~/.keras/`. Returns: Path to the downloaded file
Downloads a file from a URL if it not already in the cache.
[ "Downloads", "a", "file", "from", "a", "URL", "if", "it", "not", "already", "in", "the", "cache", "." ]
def get_file(fname=None, origin=None, untar=False, md5_hash=None, file_hash=None, cache_subdir='datasets', hash_algorithm='auto', extract=False, archive_format='auto', cache_dir=None): """Downloads a file from a URL if it not already in the cache. By default the file at the url `origin` is downloaded to the cache_dir `~/.keras`, placed in the cache_subdir `datasets`, and given the filename `fname`. The final location of a file `example.txt` would therefore be `~/.keras/datasets/example.txt`. Files in tar, tar.gz, tar.bz, and zip formats can also be extracted. Passing a hash will verify the file after download. The command line programs `shasum` and `sha256sum` can compute the hash. Example: ```python path_to_downloaded_file = tf.keras.utils.get_file( "flower_photos", "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz", untar=True) ``` Args: fname: Name of the file. If an absolute path `/path/to/file.txt` is specified the file will be saved at that location. If `None`, the name of the file at `origin` will be used. origin: Original URL of the file. untar: Deprecated in favor of `extract` argument. boolean, whether the file should be decompressed md5_hash: Deprecated in favor of `file_hash` argument. md5 hash of the file for verification file_hash: The expected hash string of the file after download. The sha256 and md5 hash algorithms are both supported. cache_subdir: Subdirectory under the Keras cache dir where the file is saved. If an absolute path `/path/to/folder` is specified the file will be saved at that location. hash_algorithm: Select the hash algorithm to verify the file. options are `'md5'`, `'sha256'`, and `'auto'`. The default 'auto' detects the hash algorithm in use. extract: True tries extracting the file as an Archive, like tar or zip. archive_format: Archive format to try for extracting the file. Options are `'auto'`, `'tar'`, `'zip'`, and `None`. `'tar'` includes tar, tar.gz, and tar.bz files. The default `'auto'` corresponds to `['tar', 'zip']`. None or an empty list will return no matches found. cache_dir: Location to store cached files, when None it defaults to the default directory `~/.keras/`. Returns: Path to the downloaded file """ if origin is None: raise ValueError('Please specify the "origin" argument (URL of the file ' 'to download).') if cache_dir is None: cache_dir = os.path.join(os.path.expanduser('~'), '.keras') if md5_hash is not None and file_hash is None: file_hash = md5_hash hash_algorithm = 'md5' datadir_base = os.path.expanduser(cache_dir) if not os.access(datadir_base, os.W_OK): datadir_base = os.path.join('/tmp', '.keras') datadir = os.path.join(datadir_base, cache_subdir) _makedirs_exist_ok(datadir) fname = io_utils.path_to_string(fname) if not fname: fname = os.path.basename(urlsplit(origin).path) if not fname: raise ValueError( f"Can't parse the file name from the origin provided: '{origin}'." "Please specify the `fname` as the input param.") if untar: if fname.endswith('.tar.gz'): fname = pathlib.Path(fname) # The 2 `.with_suffix()` are because of `.tar.gz` as pathlib # considers it as 2 suffixes. fname = fname.with_suffix('').with_suffix('') fname = str(fname) untar_fpath = os.path.join(datadir, fname) fpath = untar_fpath + '.tar.gz' else: fpath = os.path.join(datadir, fname) download = False if os.path.exists(fpath): # File found; verify integrity if a hash was provided. if file_hash is not None: if not validate_file(fpath, file_hash, algorithm=hash_algorithm): io_utils.print_msg( 'A local file was found, but it seems to be ' f'incomplete or outdated because the {hash_algorithm} ' f'file hash does not match the original value of {file_hash} ' 'so we will re-download the data.') download = True else: download = True if download: io_utils.print_msg(f'Downloading data from {origin}') class ProgressTracker: # Maintain progbar for the lifetime of download. # This design was chosen for Python 2.7 compatibility. progbar = None def dl_progress(count, block_size, total_size): if ProgressTracker.progbar is None: if total_size == -1: total_size = None ProgressTracker.progbar = Progbar(total_size) else: ProgressTracker.progbar.update(count * block_size) error_msg = 'URL fetch failure on {}: {} -- {}' try: try: urlretrieve(origin, fpath, dl_progress) except urllib.error.HTTPError as e: raise Exception(error_msg.format(origin, e.code, e.msg)) except urllib.error.URLError as e: raise Exception(error_msg.format(origin, e.errno, e.reason)) except (Exception, KeyboardInterrupt) as e: if os.path.exists(fpath): os.remove(fpath) raise ProgressTracker.progbar = None if untar: if not os.path.exists(untar_fpath): _extract_archive(fpath, datadir, archive_format='tar') return untar_fpath if extract: _extract_archive(fpath, datadir, archive_format) return fpath
[ "def", "get_file", "(", "fname", "=", "None", ",", "origin", "=", "None", ",", "untar", "=", "False", ",", "md5_hash", "=", "None", ",", "file_hash", "=", "None", ",", "cache_subdir", "=", "'datasets'", ",", "hash_algorithm", "=", "'auto'", ",", "extract...
https://github.com/keras-team/keras/blob/5caa668b6a415675064a730f5eb46ecc08e40f65/keras/utils/data_utils.py#L150-L296
mlcommons/inference
078e21f2bc0a37c7fd0e435d64f5a49760dca823
speech_recognition/rnnt/pytorch/parts/text/cleaners.py
python
transliteration_cleaners
(text)
return text
Pipeline for non-English text that transliterates to ASCII.
Pipeline for non-English text that transliterates to ASCII.
[ "Pipeline", "for", "non", "-", "English", "text", "that", "transliterates", "to", "ASCII", "." ]
def transliteration_cleaners(text): '''Pipeline for non-English text that transliterates to ASCII.''' text = convert_to_ascii(text) text = lowercase(text) text = collapse_whitespace(text) return text
[ "def", "transliteration_cleaners", "(", "text", ")", ":", "text", "=", "convert_to_ascii", "(", "text", ")", "text", "=", "lowercase", "(", "text", ")", "text", "=", "collapse_whitespace", "(", "text", ")", "return", "text" ]
https://github.com/mlcommons/inference/blob/078e21f2bc0a37c7fd0e435d64f5a49760dca823/speech_recognition/rnnt/pytorch/parts/text/cleaners.py#L99-L104
glinscott/fishtest
8d2b823a63fbe7be169a2177a130018c389d7aea
worker/packages/requests/models.py
python
Response.__iter__
(self)
return self.iter_content(128)
Allows you to use a response as an iterator.
Allows you to use a response as an iterator.
[ "Allows", "you", "to", "use", "a", "response", "as", "an", "iterator", "." ]
def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128)
[ "def", "__iter__", "(", "self", ")", ":", "return", "self", ".", "iter_content", "(", "128", ")" ]
https://github.com/glinscott/fishtest/blob/8d2b823a63fbe7be169a2177a130018c389d7aea/worker/packages/requests/models.py#L691-L693
CellProfiler/CellProfiler
a90e17e4d258c6f3900238be0f828e0b4bd1b293
cellprofiler/modules/rescaleintensity.py
python
RescaleIntensity.is_aggregation_module
(self)
return (self.wants_automatic_high == HIGH_ALL_IMAGES) or ( self.wants_automatic_low == LOW_ALL_IMAGES )
We scan through all images in a group in some cases
We scan through all images in a group in some cases
[ "We", "scan", "through", "all", "images", "in", "a", "group", "in", "some", "cases" ]
def is_aggregation_module(self): """We scan through all images in a group in some cases""" return (self.wants_automatic_high == HIGH_ALL_IMAGES) or ( self.wants_automatic_low == LOW_ALL_IMAGES )
[ "def", "is_aggregation_module", "(", "self", ")", ":", "return", "(", "self", ".", "wants_automatic_high", "==", "HIGH_ALL_IMAGES", ")", "or", "(", "self", ".", "wants_automatic_low", "==", "LOW_ALL_IMAGES", ")" ]
https://github.com/CellProfiler/CellProfiler/blob/a90e17e4d258c6f3900238be0f828e0b4bd1b293/cellprofiler/modules/rescaleintensity.py#L395-L399
snipsco/snips-nlu
74b2893c91fc0bafc919a7e088ecb0b2bd611acf
snips_nlu/pipeline/processing_unit.py
python
ProcessingUnit.get_config
(cls, unit_config)
Returns the :class:`.ProcessingUnitConfig` corresponding to *unit_config*
Returns the :class:`.ProcessingUnitConfig` corresponding to *unit_config*
[ "Returns", "the", ":", "class", ":", ".", "ProcessingUnitConfig", "corresponding", "to", "*", "unit_config", "*" ]
def get_config(cls, unit_config): """Returns the :class:`.ProcessingUnitConfig` corresponding to *unit_config*""" if isinstance(unit_config, ProcessingUnitConfig): return unit_config elif isinstance(unit_config, dict): unit_name = unit_config["unit_name"] processing_unit_type = cls.by_name(unit_name) return processing_unit_type.config_type.from_dict(unit_config) elif isinstance(unit_config, (str, bytes)): unit_name = unit_config unit_config = {"unit_name": unit_name} processing_unit_type = cls.by_name(unit_name) return processing_unit_type.config_type.from_dict(unit_config) else: raise ValueError( "Expected `unit_config` to be an instance of " "ProcessingUnitConfig or dict or str but found: %s" % type(unit_config))
[ "def", "get_config", "(", "cls", ",", "unit_config", ")", ":", "if", "isinstance", "(", "unit_config", ",", "ProcessingUnitConfig", ")", ":", "return", "unit_config", "elif", "isinstance", "(", "unit_config", ",", "dict", ")", ":", "unit_name", "=", "unit_conf...
https://github.com/snipsco/snips-nlu/blob/74b2893c91fc0bafc919a7e088ecb0b2bd611acf/snips_nlu/pipeline/processing_unit.py#L104-L122
samuelclay/NewsBlur
2c45209df01a1566ea105e04d499367f32ac9ad2
utils/ratelimit.py
python
ratelimit.current_key
(self, request)
return '%s%s-%s' % ( self.prefix, self.key_extra(request), datetime.now().strftime('%Y%m%d%H%M') )
[]
def current_key(self, request): return '%s%s-%s' % ( self.prefix, self.key_extra(request), datetime.now().strftime('%Y%m%d%H%M') )
[ "def", "current_key", "(", "self", ",", "request", ")", ":", "return", "'%s%s-%s'", "%", "(", "self", ".", "prefix", ",", "self", ".", "key_extra", "(", "request", ")", ",", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y%m%d%H%M'", ")", ...
https://github.com/samuelclay/NewsBlur/blob/2c45209df01a1566ea105e04d499367f32ac9ad2/utils/ratelimit.py#L70-L75
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/util.py
python
normalize_path
(path)
return os.path.normcase(os.path.realpath(path))
Convert a path to its canonical, case-normalized, absolute version.
Convert a path to its canonical, case-normalized, absolute version.
[ "Convert", "a", "path", "to", "its", "canonical", "case", "-", "normalized", "absolute", "version", "." ]
def normalize_path(path): """ Convert a path to its canonical, case-normalized, absolute version. """ return os.path.normcase(os.path.realpath(path))
[ "def", "normalize_path", "(", "path", ")", ":", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "realpath", "(", "path", ")", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/util.py#L249-L254
maurosoria/dirsearch
b83e68c8fdf360ab06be670d7b92b263262ee5b1
thirdparty/jinja2/environment.py
python
Template.render_async
(self, *args: t.Any, **kwargs: t.Any)
This works similar to :meth:`render` but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled. Example usage:: await template.render_async(knights='that say nih; asynchronously')
This works similar to :meth:`render` but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled.
[ "This", "works", "similar", "to", ":", "meth", ":", "render", "but", "returns", "a", "coroutine", "that", "when", "awaited", "returns", "the", "entire", "rendered", "template", "string", ".", "This", "requires", "the", "async", "feature", "to", "be", "enable...
async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str: """This works similar to :meth:`render` but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled. Example usage:: await template.render_async(knights='that say nih; asynchronously') """ if not self.environment.is_async: raise RuntimeError( "The environment was not created with async mode enabled." ) ctx = self.new_context(dict(*args, **kwargs)) try: return concat([n async for n in self.root_render_func(ctx)]) # type: ignore except Exception: return self.environment.handle_exception()
[ "async", "def", "render_async", "(", "self", ",", "*", "args", ":", "t", ".", "Any", ",", "*", "*", "kwargs", ":", "t", ".", "Any", ")", "->", "str", ":", "if", "not", "self", ".", "environment", ".", "is_async", ":", "raise", "RuntimeError", "(", ...
https://github.com/maurosoria/dirsearch/blob/b83e68c8fdf360ab06be670d7b92b263262ee5b1/thirdparty/jinja2/environment.py#L1306-L1325
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/experimental/NH1_Integration/HDF5_SimResults/lib/NE1_Simulation/SimResultsDataStore.py
python
SimResultsDataStore.getFrameExtDataInt
(self, frameSetName, frameIndex, extDataSetName, key)
Returns an integer value stored in the specified frame for the given key.
Returns an integer value stored in the specified frame for the given key.
[ "Returns", "an", "integer", "value", "stored", "in", "the", "specified", "frame", "for", "the", "given", "key", "." ]
def getFrameExtDataInt(self, frameSetName, frameIndex, extDataSetName, key): """ Returns an integer value stored in the specified frame for the given key. """ pass
[ "def", "getFrameExtDataInt", "(", "self", ",", "frameSetName", ",", "frameIndex", ",", "extDataSetName", ",", "key", ")", ":", "pass" ]
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/experimental/NH1_Integration/HDF5_SimResults/lib/NE1_Simulation/SimResultsDataStore.py#L405-L410
p-christ/Deep-Reinforcement-Learning-Algorithms-with-PyTorch
135d3e2e06bbde2868047d738e3fc2d73fd8cc93
agents/Base_Agent.py
python
Base_Agent.set_random_seeds
(self, random_seed)
Sets all possible random seeds so results can be reproduced
Sets all possible random seeds so results can be reproduced
[ "Sets", "all", "possible", "random", "seeds", "so", "results", "can", "be", "reproduced" ]
def set_random_seeds(self, random_seed): """Sets all possible random seeds so results can be reproduced""" os.environ['PYTHONHASHSEED'] = str(random_seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.manual_seed(random_seed) # tf.set_random_seed(random_seed) random.seed(random_seed) np.random.seed(random_seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(random_seed) torch.cuda.manual_seed(random_seed) if hasattr(gym.spaces, 'prng'): gym.spaces.prng.seed(random_seed)
[ "def", "set_random_seeds", "(", "self", ",", "random_seed", ")", ":", "os", ".", "environ", "[", "'PYTHONHASHSEED'", "]", "=", "str", "(", "random_seed", ")", "torch", ".", "backends", ".", "cudnn", ".", "deterministic", "=", "True", "torch", ".", "backend...
https://github.com/p-christ/Deep-Reinforcement-Learning-Algorithms-with-PyTorch/blob/135d3e2e06bbde2868047d738e3fc2d73fd8cc93/agents/Base_Agent.py#L140-L153
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cr/v20180321/models.py
python
DownloadRecordListResponse.__init__
(self)
r""" :param RecordListUrl: 录音列表下载地址 :type RecordListUrl: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param RecordListUrl: 录音列表下载地址 :type RecordListUrl: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "RecordListUrl", ":", "录音列表下载地址", ":", "type", "RecordListUrl", ":", "str", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时需要提供该次请求的", "RequestId。", ":", "type", "RequestId", ":", "str" ]
def __init__(self): r""" :param RecordListUrl: 录音列表下载地址 :type RecordListUrl: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RecordListUrl = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "RecordListUrl", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cr/v20180321/models.py#L1261-L1269
ellmetha/django-machina
b38e3fdee9b5f7ea7f6ef980f764c563b67f719a
machina/apps/forum_conversation/views.py
python
TopicView.get_context_data
(self, **kwargs)
return context
Returns the context data to provide to the template.
Returns the context data to provide to the template.
[ "Returns", "the", "context", "data", "to", "provide", "to", "the", "template", "." ]
def get_context_data(self, **kwargs): """ Returns the context data to provide to the template. """ context = super().get_context_data(**kwargs) # Insert the considered topic and the associated forum into the context topic = self.get_topic() context['topic'] = topic context['forum'] = topic.forum # Handles the case when a poll is associated to the topic try: if hasattr(topic, 'poll') and topic.poll.options.exists(): context['poll'] = topic.poll context['poll_form'] = self.poll_form_class(poll=topic.poll) context['view_results_action'] = self.request.GET.get('view_results', None) context['change_vote_action'] = self.request.GET.get('change_vote', None) except ObjectDoesNotExist: # pragma: no cover pass return context
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "# Insert the considered topic and the associated forum into the context", "topic", "=", "self", "....
https://github.com/ellmetha/django-machina/blob/b38e3fdee9b5f7ea7f6ef980f764c563b67f719a/machina/apps/forum_conversation/views.py#L97-L116
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/ellipse.py
python
Ellipse.tangent_lines
(self, p)
Tangent lines between `p` and the ellipse. If `p` is on the ellipse, returns the tangent line through point `p`. Otherwise, returns the tangent line(s) from `p` to the ellipse, or None if no tangent line is possible (e.g., `p` inside ellipse). Parameters ========== p : Point Returns ======= tangent_lines : list with 1 or 2 Lines Raises ====== NotImplementedError Can only find tangent lines for a point, `p`, on the ellipse. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Line Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.tangent_lines(Point(3, 0)) [Line(Point(3, 0), Point(3, -12))] >>> # This will plot an ellipse together with a tangent line. >>> from sympy.plotting.pygletplot import PygletPlot as Plot >>> from sympy import Point, Ellipse >>> e = Ellipse(Point(0,0), 3, 2) >>> t = e.tangent_lines(e.random_point()) >>> p = Plot() >>> p[0] = e # doctest: +SKIP >>> p[1] = t # doctest: +SKIP
Tangent lines between `p` and the ellipse.
[ "Tangent", "lines", "between", "p", "and", "the", "ellipse", "." ]
def tangent_lines(self, p): """Tangent lines between `p` and the ellipse. If `p` is on the ellipse, returns the tangent line through point `p`. Otherwise, returns the tangent line(s) from `p` to the ellipse, or None if no tangent line is possible (e.g., `p` inside ellipse). Parameters ========== p : Point Returns ======= tangent_lines : list with 1 or 2 Lines Raises ====== NotImplementedError Can only find tangent lines for a point, `p`, on the ellipse. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Line Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.tangent_lines(Point(3, 0)) [Line(Point(3, 0), Point(3, -12))] >>> # This will plot an ellipse together with a tangent line. >>> from sympy.plotting.pygletplot import PygletPlot as Plot >>> from sympy import Point, Ellipse >>> e = Ellipse(Point(0,0), 3, 2) >>> t = e.tangent_lines(e.random_point()) >>> p = Plot() >>> p[0] = e # doctest: +SKIP >>> p[1] = t # doctest: +SKIP """ p = Point(p) if self.encloses_point(p): return [] if p in self: delta = self.center - p rise = (self.vradius ** 2)*delta.x run = -(self.hradius ** 2)*delta.y p2 = Point(simplify(p.x + run), simplify(p.y + rise)) return [Line(p, p2)] else: if len(self.foci) == 2: f1, f2 = self.foci maj = self.hradius test = (2*maj - Point.distance(f1, p) - Point.distance(f2, p)) else: test = self.radius - Point.distance(self.center, p) if test.is_number and test.is_positive: return [] # else p is outside the ellipse or we can't tell. In case of the # latter, the solutions returned will only be valid if # the point is not inside the ellipse; if it is, nan will result. x, y = Dummy('x'), Dummy('y') eq = self.equation(x, y) dydx = idiff(eq, y, x) slope = Line(p, Point(x, y)).slope tangent_points = solve([slope - dydx, eq], [x, y]) # handle horizontal and vertical tangent lines if len(tangent_points) == 1: assert tangent_points[0][ 0] == p.x or tangent_points[0][1] == p.y return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))] # others return [Line(p, tangent_points[0]), Line(p, tangent_points[1])]
[ "def", "tangent_lines", "(", "self", ",", "p", ")", ":", "p", "=", "Point", "(", "p", ")", "if", "self", ".", "encloses_point", "(", "p", ")", ":", "return", "[", "]", "if", "p", "in", "self", ":", "delta", "=", "self", ".", "center", "-", "p",...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/ellipse.py#L643-L727