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
4shadoww/hakkuframework
409a11fc3819d251f86faa3473439f8c19066a21
lib/future/standard_library/__init__.py
python
is_py2_stdlib_module
(m)
return False
Tries to infer whether the module m is from the Python 2 standard library. This may not be reliable on all systems.
Tries to infer whether the module m is from the Python 2 standard library. This may not be reliable on all systems.
[ "Tries", "to", "infer", "whether", "the", "module", "m", "is", "from", "the", "Python", "2", "standard", "library", ".", "This", "may", "not", "be", "reliable", "on", "all", "systems", "." ]
def is_py2_stdlib_module(m): """ Tries to infer whether the module m is from the Python 2 standard library. This may not be reliable on all systems. """ if PY3: return False if not 'stdlib_path' in is_py2_stdlib_module.__dict__: stdlib_files = [contextlib.__file__, os.__file__, copy.__file__] stdlib_paths = [os.path.split(f)[0] for f in stdlib_files] if not len(set(stdlib_paths)) == 1: # This seems to happen on travis-ci.org. Very strange. We'll try to # ignore it. flog.warn('Multiple locations found for the Python standard ' 'library: %s' % stdlib_paths) # Choose the first one arbitrarily is_py2_stdlib_module.stdlib_path = stdlib_paths[0] if m.__name__ in sys.builtin_module_names: return True if hasattr(m, '__file__'): modpath = os.path.split(m.__file__) if (modpath[0].startswith(is_py2_stdlib_module.stdlib_path) and 'site-packages' not in modpath[0]): return True return False
[ "def", "is_py2_stdlib_module", "(", "m", ")", ":", "if", "PY3", ":", "return", "False", "if", "not", "'stdlib_path'", "in", "is_py2_stdlib_module", ".", "__dict__", ":", "stdlib_files", "=", "[", "contextlib", ".", "__file__", ",", "os", ".", "__file__", ","...
https://github.com/4shadoww/hakkuframework/blob/409a11fc3819d251f86faa3473439f8c19066a21/lib/future/standard_library/__init__.py#L342-L369
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
contrib/paramiko/tasks.py
python
release
(ctx, sdist=True, wheel=True, sign=True, dry_run=False)
Wraps invocations.packaging.release to add baked-in docs folder.
Wraps invocations.packaging.release to add baked-in docs folder.
[ "Wraps", "invocations", ".", "packaging", ".", "release", "to", "add", "baked", "-", "in", "docs", "folder", "." ]
def release(ctx, sdist=True, wheel=True, sign=True, dry_run=False): """ Wraps invocations.packaging.release to add baked-in docs folder. """ # Build docs first. Use terribad workaround pending invoke #146 ctx.run("inv docs") # Move the built docs into where Epydocs used to live target = 'docs' rmtree(target, ignore_errors=True) # TODO: make it easier to yank out this config val from the docs coll copytree('sites/docs/_build', target) # Publish publish(ctx, sdist=sdist, wheel=wheel, sign=sign, dry_run=dry_run) # Remind print("\n\nDon't forget to update RTD's versions page for new minor releases!")
[ "def", "release", "(", "ctx", ",", "sdist", "=", "True", ",", "wheel", "=", "True", ",", "sign", "=", "True", ",", "dry_run", "=", "False", ")", ":", "# Build docs first. Use terribad workaround pending invoke #146", "ctx", ".", "run", "(", "\"inv docs\"", ")"...
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/contrib/paramiko/tasks.py#L28-L42
spulec/moto
a688c0032596a7dfef122b69a08f2bec3be2e481
moto/utilities/tagging_service.py
python
TaggingService.delete_all_tags_for_resource
(self, arn)
Delete all tags associated with given ARN.
Delete all tags associated with given ARN.
[ "Delete", "all", "tags", "associated", "with", "given", "ARN", "." ]
def delete_all_tags_for_resource(self, arn): """Delete all tags associated with given ARN.""" if self.has_tags(arn): del self.tags[arn]
[ "def", "delete_all_tags_for_resource", "(", "self", ",", "arn", ")", ":", "if", "self", ".", "has_tags", "(", "arn", ")", ":", "del", "self", ".", "tags", "[", "arn", "]" ]
https://github.com/spulec/moto/blob/a688c0032596a7dfef122b69a08f2bec3be2e481/moto/utilities/tagging_service.py#L34-L37
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_namespace_spec.py
python
V1NamespaceSpec.finalizers
(self)
return self._finalizers
Gets the finalizers of this V1NamespaceSpec. Finalizers is an opaque list of values that must be empty to permanently remove object from storage. More info: https://git.k8s.io/community/contributors/design-proposals/namespaces.md#finalizers :return: The finalizers of this V1NamespaceSpec. :rtype: list[str]
Gets the finalizers of this V1NamespaceSpec. Finalizers is an opaque list of values that must be empty to permanently remove object from storage. More info: https://git.k8s.io/community/contributors/design-proposals/namespaces.md#finalizers
[ "Gets", "the", "finalizers", "of", "this", "V1NamespaceSpec", ".", "Finalizers", "is", "an", "opaque", "list", "of", "values", "that", "must", "be", "empty", "to", "permanently", "remove", "object", "from", "storage", ".", "More", "info", ":", "https", ":", ...
def finalizers(self): """ Gets the finalizers of this V1NamespaceSpec. Finalizers is an opaque list of values that must be empty to permanently remove object from storage. More info: https://git.k8s.io/community/contributors/design-proposals/namespaces.md#finalizers :return: The finalizers of this V1NamespaceSpec. :rtype: list[str] """ return self._finalizers
[ "def", "finalizers", "(", "self", ")", ":", "return", "self", ".", "_finalizers" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_namespace_spec.py#L44-L52
danecjensen/subscribely
4d6ac60358b5fe26f0c01be68f1ba063df3b1ea0
src/werkzeug/contrib/sessions.py
python
SessionStore.new
(self)
return self.session_class({}, self.generate_key(), True)
Generate a new session.
Generate a new session.
[ "Generate", "a", "new", "session", "." ]
def new(self): """Generate a new session.""" return self.session_class({}, self.generate_key(), True)
[ "def", "new", "(", "self", ")", ":", "return", "self", ".", "session_class", "(", "{", "}", ",", "self", ".", "generate_key", "(", ")", ",", "True", ")" ]
https://github.com/danecjensen/subscribely/blob/4d6ac60358b5fe26f0c01be68f1ba063df3b1ea0/src/werkzeug/contrib/sessions.py#L162-L164
smiley/steamapi
eb1cf49ecabc2de892f6581168a84c07a19cb36f
steamapi/user.py
python
SteamUser.time_created
(self)
return datetime.datetime.fromtimestamp(self._summary.timecreated)
:rtype: datetime
:rtype: datetime
[ ":", "rtype", ":", "datetime" ]
def time_created(self): """ :rtype: datetime """ return datetime.datetime.fromtimestamp(self._summary.timecreated)
[ "def", "time_created", "(", "self", ")", ":", "return", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "self", ".", "_summary", ".", "timecreated", ")" ]
https://github.com/smiley/steamapi/blob/eb1cf49ecabc2de892f6581168a84c07a19cb36f/steamapi/user.py#L277-L281
NVIDIA/hpc-container-maker
6780d3ba048fc986d45e3b79a8af97c013824aa7
hpccm/building_blocks/cgns.py
python
cgns.__distro
(self)
Based on the Linux distribution, set values accordingly. A user specified value overrides any defaults.
Based on the Linux distribution, set values accordingly. A user specified value overrides any defaults.
[ "Based", "on", "the", "Linux", "distribution", "set", "values", "accordingly", ".", "A", "user", "specified", "value", "overrides", "any", "defaults", "." ]
def __distro(self): """Based on the Linux distribution, set values accordingly. A user specified value overrides any defaults.""" if hpccm.config.g_linux_distro == linux_distro.UBUNTU: if not self.__ospackages: self.__ospackages = ['file', 'make', 'wget', 'zlib1g-dev'] self.__runtime_ospackages = ['zlib1g'] elif hpccm.config.g_linux_distro == linux_distro.CENTOS: if not self.__ospackages: self.__ospackages = ['bzip2', 'file', 'make', 'wget', 'zlib-devel'] if self.__check: self.__ospackages.append('diffutils') self.__runtime_ospackages = ['zlib'] else: # pragma: no cover raise RuntimeError('Unknown Linux distribution')
[ "def", "__distro", "(", "self", ")", ":", "if", "hpccm", ".", "config", ".", "g_linux_distro", "==", "linux_distro", ".", "UBUNTU", ":", "if", "not", "self", ".", "__ospackages", ":", "self", ".", "__ospackages", "=", "[", "'file'", ",", "'make'", ",", ...
https://github.com/NVIDIA/hpc-container-maker/blob/6780d3ba048fc986d45e3b79a8af97c013824aa7/hpccm/building_blocks/cgns.py#L155-L171
oddt/oddt
8cf555820d97a692ade81c101ebe10e28bcb3722
oddt/scoring/__init__.py
python
ensemble_descriptor.__init__
(self, descriptor_generators)
Proxy class to build an ensemble of destriptors with an API as one Parameters ---------- models: array An array of models
Proxy class to build an ensemble of destriptors with an API as one
[ "Proxy", "class", "to", "build", "an", "ensemble", "of", "destriptors", "with", "an", "API", "as", "one" ]
def __init__(self, descriptor_generators): """Proxy class to build an ensemble of destriptors with an API as one Parameters ---------- models: array An array of models """ self._desc_gens = (descriptor_generators if len(descriptor_generators) else None) self.titles = list(chain(*(desc_gen.titles for desc_gen in self._desc_gens)))
[ "def", "__init__", "(", "self", ",", "descriptor_generators", ")", ":", "self", ".", "_desc_gens", "=", "(", "descriptor_generators", "if", "len", "(", "descriptor_generators", ")", "else", "None", ")", "self", ".", "titles", "=", "list", "(", "chain", "(", ...
https://github.com/oddt/oddt/blob/8cf555820d97a692ade81c101ebe10e28bcb3722/oddt/scoring/__init__.py#L406-L417
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_user.py
python
OpenShiftCLI._replace_content
(self, resource, rname, content, edits=None, force=False, sep='.')
return {'returncode': 0, 'updated': False}
replace the current object with the content
replace the current object with the content
[ "replace", "the", "current", "object", "with", "the", "content" ]
def _replace_content(self, resource, rname, content, edits=None, force=False, sep='.'): ''' replace the current object with the content ''' res = self._get(resource, rname) if not res['results']: return res fname = Utils.create_tmpfile(rname + '-') yed = Yedit(fname, res['results'][0], separator=sep) updated = False if content is not None: changes = [] for key, value in content.items(): changes.append(yed.put(key, value)) if any([change[0] for change in changes]): updated = True elif edits is not None: results = Yedit.process_edits(edits, yed) if results['changed']: updated = True if updated: yed.write() atexit.register(Utils.cleanup, [fname]) return self._replace(fname, force) return {'returncode': 0, 'updated': False}
[ "def", "_replace_content", "(", "self", ",", "resource", ",", "rname", ",", "content", ",", "edits", "=", "None", ",", "force", "=", "False", ",", "sep", "=", "'.'", ")", ":", "res", "=", "self", ".", "_get", "(", "resource", ",", "rname", ")", "if...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_user.py#L944-L975
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventTypeArg.is_paper_content_create
(self)
return self._tag == 'paper_content_create'
Check if the union tag is ``paper_content_create``. :rtype: bool
Check if the union tag is ``paper_content_create``.
[ "Check", "if", "the", "union", "tag", "is", "paper_content_create", "." ]
def is_paper_content_create(self): """ Check if the union tag is ``paper_content_create``. :rtype: bool """ return self._tag == 'paper_content_create'
[ "def", "is_paper_content_create", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'paper_content_create'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L41303-L41309
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/priorities/tasks/velocity/postural.py
python
PosturalTask.x_desired
(self)
return self._q_d
Get the desired joint positions.
Get the desired joint positions.
[ "Get", "the", "desired", "joint", "positions", "." ]
def x_desired(self): """Get the desired joint positions.""" return self._q_d
[ "def", "x_desired", "(", "self", ")", ":", "return", "self", ".", "_q_d" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/priorities/tasks/velocity/postural.py#L124-L126
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/modules/common/structures/partitioning.py
python
PartitioningRequest.pbkdf_memory
(self, memory: Int)
Set the memory cost for PBKDF. :param memory: the memory cost in kilobytes
Set the memory cost for PBKDF.
[ "Set", "the", "memory", "cost", "for", "PBKDF", "." ]
def pbkdf_memory(self, memory: Int): """Set the memory cost for PBKDF. :param memory: the memory cost in kilobytes """ self._pbkdf_memory = memory
[ "def", "pbkdf_memory", "(", "self", ",", "memory", ":", "Int", ")", ":", "self", ".", "_pbkdf_memory", "=", "memory" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/modules/common/structures/partitioning.py#L175-L180
linkchecker/linkchecker
d1078ed8480e5cfc4264d0dbf026b45b45aede4d
linkcheck/checker/httpurl.py
python
HttpUrl.content_allows_robots
(self)
return not soup.find("meta", attrs={"name": "robots", "content": nofollow_re})
Return False if the content of this URL forbids robots to search for recursive links.
Return False if the content of this URL forbids robots to search for recursive links.
[ "Return", "False", "if", "the", "content", "of", "this", "URL", "forbids", "robots", "to", "search", "for", "recursive", "links", "." ]
def content_allows_robots(self): """ Return False if the content of this URL forbids robots to search for recursive links. """ if not self.is_html(): return True soup = self.get_soup() return not soup.find("meta", attrs={"name": "robots", "content": nofollow_re})
[ "def", "content_allows_robots", "(", "self", ")", ":", "if", "not", "self", ".", "is_html", "(", ")", ":", "return", "True", "soup", "=", "self", ".", "get_soup", "(", ")", "return", "not", "soup", ".", "find", "(", "\"meta\"", ",", "attrs", "=", "{"...
https://github.com/linkchecker/linkchecker/blob/d1078ed8480e5cfc4264d0dbf026b45b45aede4d/linkcheck/checker/httpurl.py#L88-L97
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
examples/research_projects/seq2seq-distillation/utils.py
python
any_requires_grad
(model: nn.Module)
return any(grad_status(model))
[]
def any_requires_grad(model: nn.Module) -> bool: return any(grad_status(model))
[ "def", "any_requires_grad", "(", "model", ":", "nn", ".", "Module", ")", "->", "bool", ":", "return", "any", "(", "grad_status", "(", "model", ")", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/examples/research_projects/seq2seq-distillation/utils.py#L569-L570
RiskSense-Ops/CVE-2016-6366
0ba7426a9bf2a01c807608b7e1b63f87fe2699a5
extrabacon-2.0/scapy/layers/inet6.py
python
defragment6
(pktlist)
return IPv6(str(q))
Performs defragmentation of a list of IPv6 packets. Packets are reordered. Crap is dropped. What lacks is completed by 'X' characters.
Performs defragmentation of a list of IPv6 packets. Packets are reordered. Crap is dropped. What lacks is completed by 'X' characters.
[ "Performs", "defragmentation", "of", "a", "list", "of", "IPv6", "packets", ".", "Packets", "are", "reordered", ".", "Crap", "is", "dropped", ".", "What", "lacks", "is", "completed", "by", "X", "characters", "." ]
def defragment6(pktlist): """ Performs defragmentation of a list of IPv6 packets. Packets are reordered. Crap is dropped. What lacks is completed by 'X' characters. """ l = filter(lambda x: IPv6ExtHdrFragment in x, pktlist) # remove non fragments if not l: return [] id = l[0][IPv6ExtHdrFragment].id llen = len(l) l = filter(lambda x: x[IPv6ExtHdrFragment].id == id, l) if len(l) != llen: warning("defragment6: some fragmented packets have been removed from list") llen = len(l) # reorder fragments i = 0 res = [] while l: min_pos = 0 min_offset = l[0][IPv6ExtHdrFragment].offset for p in l: cur_offset = p[IPv6ExtHdrFragment].offset if cur_offset < min_offset: min_pos = 0 min_offset = cur_offset res.append(l[min_pos]) del(l[min_pos]) # regenerate the fragmentable part fragmentable = "" for p in res: q=p[IPv6ExtHdrFragment] offset = 8*q.offset if offset != len(fragmentable): warning("Expected an offset of %d. Found %d. Padding with XXXX" % (len(fragmentable), offset)) fragmentable += "X"*(offset - len(fragmentable)) fragmentable += str(q.payload) # Regenerate the unfragmentable part. q = res[0] nh = q[IPv6ExtHdrFragment].nh q[IPv6ExtHdrFragment].underlayer.nh = nh q[IPv6ExtHdrFragment].underlayer.payload = None q /= Raw(load=fragmentable) return IPv6(str(q))
[ "def", "defragment6", "(", "pktlist", ")", ":", "l", "=", "filter", "(", "lambda", "x", ":", "IPv6ExtHdrFragment", "in", "x", ",", "pktlist", ")", "# remove non fragments", "if", "not", "l", ":", "return", "[", "]", "id", "=", "l", "[", "0", "]", "["...
https://github.com/RiskSense-Ops/CVE-2016-6366/blob/0ba7426a9bf2a01c807608b7e1b63f87fe2699a5/extrabacon-2.0/scapy/layers/inet6.py#L891-L940
nodesign/weio
1d67d705a5c36a2e825ad13feab910b0aca9a2e8
openWrt/files/usr/lib/python2.7/site-packages/tornado/concurrent.py
python
_DummyFuture._set_done
(self)
[]
def _set_done(self): self._done = True for cb in self._callbacks: # TODO: error handling cb(self) self._callbacks = None
[ "def", "_set_done", "(", "self", ")", ":", "self", ".", "_done", "=", "True", "for", "cb", "in", "self", ".", "_callbacks", ":", "# TODO: error handling", "cb", "(", "self", ")", "self", ".", "_callbacks", "=", "None" ]
https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/openWrt/files/usr/lib/python2.7/site-packages/tornado/concurrent.py#L93-L98
cloudant/bigcouch
8e9c1ec0ed1676ff152f10658f5c83a1a91fa8fe
couchjs/scons/scons-local-2.0.1/SCons/Environment.py
python
SubstitutionEnvironment.Override
(self, overrides)
return env
Produce a modified environment whose variables are overriden by the overrides dictionaries. "overrides" is a dictionary that will override the variables of this environment. This function is much more efficient than Clone() or creating a new Environment because it doesn't copy the construction environment dictionary, it just wraps the underlying construction environment, and doesn't even create a wrapper object if there are no overrides.
Produce a modified environment whose variables are overriden by the overrides dictionaries. "overrides" is a dictionary that will override the variables of this environment.
[ "Produce", "a", "modified", "environment", "whose", "variables", "are", "overriden", "by", "the", "overrides", "dictionaries", ".", "overrides", "is", "a", "dictionary", "that", "will", "override", "the", "variables", "of", "this", "environment", "." ]
def Override(self, overrides): """ Produce a modified environment whose variables are overriden by the overrides dictionaries. "overrides" is a dictionary that will override the variables of this environment. This function is much more efficient than Clone() or creating a new Environment because it doesn't copy the construction environment dictionary, it just wraps the underlying construction environment, and doesn't even create a wrapper object if there are no overrides. """ if not overrides: return self o = copy_non_reserved_keywords(overrides) if not o: return self overrides = {} merges = None for key, value in o.items(): if key == 'parse_flags': merges = value else: overrides[key] = SCons.Subst.scons_subst_once(value, self, key) env = OverrideEnvironment(self, overrides) if merges: env.MergeFlags(merges) return env
[ "def", "Override", "(", "self", ",", "overrides", ")", ":", "if", "not", "overrides", ":", "return", "self", "o", "=", "copy_non_reserved_keywords", "(", "overrides", ")", "if", "not", "o", ":", "return", "self", "overrides", "=", "{", "}", "merges", "="...
https://github.com/cloudant/bigcouch/blob/8e9c1ec0ed1676ff152f10658f5c83a1a91fa8fe/couchjs/scons/scons-local-2.0.1/SCons/Environment.py#L612-L636
geopy/geopy
af0eedcfeb4e3eec88f19e2f822e7f14ac3468eb
geopy/units.py
python
meters
(kilometers=0, miles=0, feet=0, nautical=0)
return (kilometers + km(nautical=nautical, miles=miles, feet=feet)) * 1000
Convert distance to meters.
Convert distance to meters.
[ "Convert", "distance", "to", "meters", "." ]
def meters(kilometers=0, miles=0, feet=0, nautical=0): """ Convert distance to meters. """ return (kilometers + km(nautical=nautical, miles=miles, feet=feet)) * 1000
[ "def", "meters", "(", "kilometers", "=", "0", ",", "miles", "=", "0", ",", "feet", "=", "0", ",", "nautical", "=", "0", ")", ":", "return", "(", "kilometers", "+", "km", "(", "nautical", "=", "nautical", ",", "miles", "=", "miles", ",", "feet", "...
https://github.com/geopy/geopy/blob/af0eedcfeb4e3eec88f19e2f822e7f14ac3468eb/geopy/units.py#L77-L81
elfi-dev/elfi
07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c
elfi/examples/gauss.py
python
ss_var
(y)
return ss
Return the variance summary statistic. Parameters ---------- y : array_like Yielded points. Returns ------- array_like of the shape (batch_size, dim_point)
Return the variance summary statistic.
[ "Return", "the", "variance", "summary", "statistic", "." ]
def ss_var(y): """Return the variance summary statistic. Parameters ---------- y : array_like Yielded points. Returns ------- array_like of the shape (batch_size, dim_point) """ ss = np.var(y, axis=1) return ss
[ "def", "ss_var", "(", "y", ")", ":", "ss", "=", "np", ".", "var", "(", "y", ",", "axis", "=", "1", ")", "return", "ss" ]
https://github.com/elfi-dev/elfi/blob/07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c/elfi/examples/gauss.py#L159-L173
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail/wagtailadmin/widgets.py
python
AdminPageChooser.__init__
(self, target_models=None, can_choose_root=False, user_perms=None, **kwargs)
[]
def __init__(self, target_models=None, can_choose_root=False, user_perms=None, **kwargs): super(AdminPageChooser, self).__init__(**kwargs) if target_models: models = ', '.join([model._meta.verbose_name.title() for model in target_models if model is not Page]) if models: self.choose_one_text += ' (' + models + ')' self.user_perms = user_perms self.target_models = list(target_models or [Page]) self.can_choose_root = can_choose_root
[ "def", "__init__", "(", "self", ",", "target_models", "=", "None", ",", "can_choose_root", "=", "False", ",", "user_perms", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "AdminPageChooser", ",", "self", ")", ".", "__init__", "(", "*", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail/wagtailadmin/widgets.py#L158-L168
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Tools/gdb/libpython.py
python
PyDictObjectPtr.iteritems
(self)
Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs, analogous to dict.iteritems()
Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs, analogous to dict.iteritems()
[ "Yields", "a", "sequence", "of", "(", "PyObjectPtr", "key", "PyObjectPtr", "value", ")", "pairs", "analogous", "to", "dict", ".", "iteritems", "()" ]
def iteritems(self): ''' Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs, analogous to dict.iteritems() ''' keys = self.field('ma_keys') values = self.field('ma_values') for i in safe_range(keys['dk_size']): ep = keys['dk_entries'].address + i if long(values): pyop_value = PyObjectPtr.from_pyobject_ptr(values[i]) else: pyop_value = PyObjectPtr.from_pyobject_ptr(ep['me_value']) if not pyop_value.is_null(): pyop_key = PyObjectPtr.from_pyobject_ptr(ep['me_key']) yield (pyop_key, pyop_value)
[ "def", "iteritems", "(", "self", ")", ":", "keys", "=", "self", ".", "field", "(", "'ma_keys'", ")", "values", "=", "self", ".", "field", "(", "'ma_values'", ")", "for", "i", "in", "safe_range", "(", "keys", "[", "'dk_size'", "]", ")", ":", "ep", "...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Tools/gdb/libpython.py#L649-L664
ioflo/ioflo
177ac656d7c4ff801aebb0d8b401db365a5248ce
ioflo/aid/vectoring.py
python
mag2
(v)
return (sum(e*e for e in v))
Returns the magnitude squared of vector v
Returns the magnitude squared of vector v
[ "Returns", "the", "magnitude", "squared", "of", "vector", "v" ]
def mag2(v): """ Returns the magnitude squared of vector v """ return (sum(e*e for e in v))
[ "def", "mag2", "(", "v", ")", ":", "return", "(", "sum", "(", "e", "*", "e", "for", "e", "in", "v", ")", ")" ]
https://github.com/ioflo/ioflo/blob/177ac656d7c4ff801aebb0d8b401db365a5248ce/ioflo/aid/vectoring.py#L27-L31
ClementPinard/Pytorch-Correlation-extension
3e8ce16124844cd7892ec965cf0ad18fdd8e6a02
check.py
python
get_grads
(variables)
return [var.grad.clone() for var in variables]
[]
def get_grads(variables): return [var.grad.clone() for var in variables]
[ "def", "get_grads", "(", "variables", ")", ":", "return", "[", "var", ".", "grad", ".", "clone", "(", ")", "for", "var", "in", "variables", "]" ]
https://github.com/ClementPinard/Pytorch-Correlation-extension/blob/3e8ce16124844cd7892ec965cf0ad18fdd8e6a02/check.py#L29-L30
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
release/fabfile.py
python
get_previous_version_tag
()
Get the version of the previous release
Get the version of the previous release
[ "Get", "the", "version", "of", "the", "previous", "release" ]
def get_previous_version_tag(): """ Get the version of the previous release """ # We try, probably too hard, to portably get the number of the previous # release of SymPy. Our strategy is to look at the git tags. The # following assumptions are made about the git tags: # - The only tags are for releases # - The tags are given the consistent naming: # sympy-major.minor.micro[.rcnumber] # (e.g., sympy-0.7.2 or sympy-0.7.2.rc1) # In particular, it goes back in the tag history and finds the most recent # tag that doesn't contain the current short version number as a substring. shortversion = get_sympy_short_version() curcommit = "HEAD" with cd("/home/vagrant/repos/sympy"): while True: curtag = run("git describe --abbrev=0 --tags " + curcommit).strip() if shortversion in curtag: # If the tagged commit is a merge commit, we cannot be sure # that it will go back in the right direction. This almost # never happens, so just error parents = local("git rev-list --parents -n 1 " + curtag, capture=True).strip().split() # rev-list prints the current commit and then all its parents # If the tagged commit *is* a merge commit, just comment this # out, and make sure `fab vagrant get_previous_version_tag` is correct assert len(parents) == 2, curtag curcommit = curtag + "^" # The parent of the tagged commit else: print(blue("Using {tag} as the tag for the previous " "release.".format(tag=curtag), bold=True)) return curtag error("Could not find the tag for the previous release.")
[ "def", "get_previous_version_tag", "(", ")", ":", "# We try, probably too hard, to portably get the number of the previous", "# release of SymPy. Our strategy is to look at the git tags. The", "# following assumptions are made about the git tags:", "# - The only tags are for releases", "# - The t...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/release/fabfile.py#L644-L679
uqfoundation/pathos
6d9b8cb1717a36eb72cb8c328f6c12b2326413ac
pathos/hosts.py
python
get_profiles
()
return _profiles
get $PROFILE for each registered host
get $PROFILE for each registered host
[ "get", "$PROFILE", "for", "each", "registered", "host" ]
def get_profiles(): '''get $PROFILE for each registered host''' return _profiles
[ "def", "get_profiles", "(", ")", ":", "return", "_profiles" ]
https://github.com/uqfoundation/pathos/blob/6d9b8cb1717a36eb72cb8c328f6c12b2326413ac/pathos/hosts.py#L34-L36
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/containeractions.py
python
UnrenderedCreationThread.progress_thread_complete
(self, dialog, some_number)
[]
def progress_thread_complete(self, dialog, some_number): # Gdk.threads_enter() is done before this is called from "motion_progress_update" thread. dialog.destroy()
[ "def", "progress_thread_complete", "(", "self", ",", "dialog", ",", "some_number", ")", ":", "# Gdk.threads_enter() is done before this is called from \"motion_progress_update\" thread.", "dialog", ".", "destroy", "(", ")" ]
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/containeractions.py#L1191-L1193
Pylons/pyramid_cookbook
19b62fb7c36a2b8c5866df784fda0ccd04805995
docs/traversal_tutorial/zodb/tutorial/views.py
python
TutorialViews.add_document
(self)
return HTTPFound(location=url)
[]
def add_document(self): # Make a new Document title = self.request.POST['document_title'] name = str(randint(0, 999999)) new_document = Document(title) new_document.__name__ = name new_document.__parent__ = self.context self.context[name] = new_document # Redirect to the new document url = self.request.resource_url(new_document) return HTTPFound(location=url)
[ "def", "add_document", "(", "self", ")", ":", "# Make a new Document", "title", "=", "self", ".", "request", ".", "POST", "[", "'document_title'", "]", "name", "=", "str", "(", "randint", "(", "0", ",", "999999", ")", ")", "new_document", "=", "Document", ...
https://github.com/Pylons/pyramid_cookbook/blob/19b62fb7c36a2b8c5866df784fda0ccd04805995/docs/traversal_tutorial/zodb/tutorial/views.py#L47-L58
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/pip/_vendor/distlib/metadata.py
python
LegacyMetadata._default_value
(self, name)
return 'UNKNOWN'
[]
def _default_value(self, name): if name in _LISTFIELDS or name in _ELEMENTSFIELD: return [] return 'UNKNOWN'
[ "def", "_default_value", "(", "self", ",", "name", ")", ":", "if", "name", "in", "_LISTFIELDS", "or", "name", "in", "_ELEMENTSFIELD", ":", "return", "[", "]", "return", "'UNKNOWN'" ]
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/distlib/metadata.py#L293-L296
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/statistics/distribution.py
python
Discrete.__idiv__
(self, other)
return self
[]
def __idiv__(self, other): super().__imul__(other) if isinstance(other, Real): self.unknowns /= other return self
[ "def", "__idiv__", "(", "self", ",", "other", ")", ":", "super", "(", ")", ".", "__imul__", "(", "other", ")", "if", "isinstance", "(", "other", ",", "Real", ")", ":", "self", ".", "unknowns", "/=", "other", "return", "self" ]
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/statistics/distribution.py#L214-L218
caffeinehit/django-oauth2-provider
6b5bc0d3ad706d2aaa47fa476f38406cddd01236
provider/views.py
python
Authorize.get_authorization_form
(self, request, client, data, client_data)
Return a form that is capable of authorizing the client to the resource owner. :return: :attr:`django.forms.Form`
Return a form that is capable of authorizing the client to the resource owner.
[ "Return", "a", "form", "that", "is", "capable", "of", "authorizing", "the", "client", "to", "the", "resource", "owner", "." ]
def get_authorization_form(self, request, client, data, client_data): """ Return a form that is capable of authorizing the client to the resource owner. :return: :attr:`django.forms.Form` """ raise NotImplementedError
[ "def", "get_authorization_form", "(", "self", ",", "request", ",", "client", ",", "data", ",", "client_data", ")", ":", "raise", "NotImplementedError" ]
https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/views.py#L172-L179
dreadatour/Flake8Lint
8703c5633ac3fab4bd116da82aae7ff7bbc795c0
Flake8Lint.py
python
log
(msg, level=None)
Log to ST python console. If log level 'debug' (or None) print only if debug setting is enabled.
Log to ST python console.
[ "Log", "to", "ST", "python", "console", "." ]
def log(msg, level=None): """Log to ST python console. If log level 'debug' (or None) print only if debug setting is enabled. """ if level is None: level = 'debug' if level == 'debug' and not settings.debug: return print("[Flake8Lint {0}] {1}".format(level.upper(), msg))
[ "def", "log", "(", "msg", ",", "level", "=", "None", ")", ":", "if", "level", "is", "None", ":", "level", "=", "'debug'", "if", "level", "==", "'debug'", "and", "not", "settings", ".", "debug", ":", "return", "print", "(", "\"[Flake8Lint {0}] {1}\"", "...
https://github.com/dreadatour/Flake8Lint/blob/8703c5633ac3fab4bd116da82aae7ff7bbc795c0/Flake8Lint.py#L242-L253
tmr232/Sark
bf961ec840530e16eac7a9027d2115276ee52387
sark/code/instruction.py
python
Operand.size
(self)
return base.dtype_to_size(self._operand.dtype)
Size of the operand.
Size of the operand.
[ "Size", "of", "the", "operand", "." ]
def size(self): """Size of the operand.""" return base.dtype_to_size(self._operand.dtype)
[ "def", "size", "(", "self", ")", ":", "return", "base", ".", "dtype_to_size", "(", "self", ".", "_operand", ".", "dtype", ")" ]
https://github.com/tmr232/Sark/blob/bf961ec840530e16eac7a9027d2115276ee52387/sark/code/instruction.py#L250-L252
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/email/_header_value_parser.py
python
_get_ptext_to_endchars
(value, endchars)
return ''.join(vchars), ''.join([fragment[pos:]] + remainder), had_qp
Scan printables/quoted-pairs until endchars and return unquoted ptext. This function turns a run of qcontent, ccontent-without-comments, or dtext-with-quoted-printables into a single string by unquoting any quoted printables. It returns the string, the remaining value, and a flag that is True iff there were any quoted printables decoded.
Scan printables/quoted-pairs until endchars and return unquoted ptext.
[ "Scan", "printables", "/", "quoted", "-", "pairs", "until", "endchars", "and", "return", "unquoted", "ptext", "." ]
def _get_ptext_to_endchars(value, endchars): """Scan printables/quoted-pairs until endchars and return unquoted ptext. This function turns a run of qcontent, ccontent-without-comments, or dtext-with-quoted-printables into a single string by unquoting any quoted printables. It returns the string, the remaining value, and a flag that is True iff there were any quoted printables decoded. """ fragment, *remainder = _wsp_splitter(value, 1) vchars = [] escape = False had_qp = False for pos in range(len(fragment)): if fragment[pos] == '\\': if escape: escape = False had_qp = True else: escape = True continue if escape: escape = False elif fragment[pos] in endchars: break vchars.append(fragment[pos]) else: pos = pos + 1 return ''.join(vchars), ''.join([fragment[pos:]] + remainder), had_qp
[ "def", "_get_ptext_to_endchars", "(", "value", ",", "endchars", ")", ":", "fragment", ",", "", "*", "remainder", "=", "_wsp_splitter", "(", "value", ",", "1", ")", "vchars", "=", "[", "]", "escape", "=", "False", "had_qp", "=", "False", "for", "pos", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/email/_header_value_parser.py#L970-L998
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/functions/elementary/exponential.py
python
ExpBase.inverse
(self, argindex=1)
return log
Returns the inverse function of ``exp(x)``.
Returns the inverse function of ``exp(x)``.
[ "Returns", "the", "inverse", "function", "of", "exp", "(", "x", ")", "." ]
def inverse(self, argindex=1): """ Returns the inverse function of ``exp(x)``. """ return log
[ "def", "inverse", "(", "self", ",", "argindex", "=", "1", ")", ":", "return", "log" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/functions/elementary/exponential.py#L31-L35
cbrgm/telegram-robot-rss
58fe98de427121fdc152c8df0721f1891174e6c9
venv/lib/python2.7/site-packages/telegram/vendor/ptb_urllib3/urllib3/connectionpool.py
python
HTTPConnectionPool.urlopen
(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw)
return response
Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param chunked: If True, urllib3 will send the body using chunked transfer encoding. Otherwise, urllib3 will send the body using the standard content-length form. Defaults to False. :param int body_pos: Position to seek to in file-like body in the event of a retry or redirect. Typically this won't need to be set because urllib3 will auto-populate the value when needed. :param \\**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib`
Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details.
[ "Get", "a", "connection", "from", "the", "pool", "and", "perform", "an", "HTTP", "request", ".", "This", "is", "the", "lowest", "level", "call", "for", "making", "a", "request", "so", "you", "ll", "need", "to", "specify", "all", "the", "raw", "details", ...
def urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw): """ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param chunked: If True, urllib3 will send the body using chunked transfer encoding. Otherwise, urllib3 will send the body using the standard content-length form. Defaults to False. :param int body_pos: Position to seek to in file-like body in the event of a retry or redirect. Typically this won't need to be set because urllib3 will auto-populate the value when needed. :param \\**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib` """ if headers is None: headers = self.headers if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect, default=self.retries) if release_conn is None: release_conn = response_kw.get('preload_content', True) # Check host if assert_same_host and not self.is_same_host(url): raise HostChangedError(self, url, retries) conn = None # Track whether `conn` needs to be released before # returning/raising/recursing. Update this variable if necessary, and # leave `release_conn` constant throughout the function. That way, if # the function recurses, the original value of `release_conn` will be # passed down into the recursive call, and its value will be respected. # # See issue #651 [1] for details. # # [1] <https://github.com/shazow/urllib3/issues/651> release_this_conn = release_conn # Merge the proxy headers. Only do this in HTTP. We have to copy the # headers dict so we can safely change it without those changes being # reflected in anyone else's copy. if self.scheme == 'http': headers = headers.copy() headers.update(self.proxy_headers) # Must keep the exception bound to a separate variable or else Python 3 # complains about UnboundLocalError. err = None # Keep track of whether we cleanly exited the except block. This # ensures we do proper cleanup in finally. clean_exit = False # Rewind body position, if needed. Record current position # for future rewinds in the event of a redirect/retry. body_pos = set_file_position(body, body_pos) try: # Request a connection from the queue. timeout_obj = self._get_timeout(timeout) conn = self._get_conn(timeout=pool_timeout) conn.timeout = timeout_obj.connect_timeout is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None) if is_new_proxy_conn: self._prepare_proxy(conn) # Make the request on the httplib connection object. httplib_response = self._make_request(conn, method, url, timeout=timeout_obj, body=body, headers=headers, chunked=chunked) # If we're going to release the connection in ``finally:``, then # the response doesn't need to know about the connection. Otherwise # it will also try to release it and we'll have a double-release # mess. response_conn = conn if not release_conn else None # Pass method to Response for length checking response_kw['request_method'] = method # Import httplib's response into our own wrapper object response = self.ResponseCls.from_httplib(httplib_response, pool=self, connection=response_conn, retries=retries, **response_kw) # Everything went great! clean_exit = True except queue.Empty: # Timed out by queue. raise EmptyPoolError(self, "No pool connections are available.") except (BaseSSLError, CertificateError) as e: # Close the connection. If a connection is reused on which there # was a Certificate error, the next request will certainly raise # another Certificate error. clean_exit = False raise SSLError(e) except SSLError: # Treat SSLError separately from BaseSSLError to preserve # traceback. clean_exit = False raise except (TimeoutError, HTTPException, SocketError, ProtocolError) as e: # Discard the connection for these exceptions. It will be # be replaced during the next _get_conn() call. clean_exit = False if isinstance(e, (SocketError, NewConnectionError)) and self.proxy: e = ProxyError('Cannot connect to proxy.', e) elif isinstance(e, (SocketError, HTTPException)): e = ProtocolError('Connection aborted.', e) retries = retries.increment(method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]) retries.sleep() # Keep track of the error for the retry warning. err = e finally: if not clean_exit: # We hit some kind of exception, handled or otherwise. We need # to throw the connection away unless explicitly told not to. # Close the connection, set the variable to None, and make sure # we put the None back in the pool to avoid leaking it. conn = conn and conn.close() release_this_conn = True if release_this_conn: # Put the connection back to be reused. If the connection is # expired then it will be None, which will get replaced with a # fresh connection during _get_conn. self._put_conn(conn) if not conn: # Try again log.warning("Retrying (%r) after connection " "broken by '%r': %s", retries, err, url) return self.urlopen(method, url, body, headers, retries, redirect, assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, body_pos=body_pos, **response_kw) # Handle redirect? redirect_location = redirect and response.get_redirect_location() if redirect_location: if response.status == 303: method = 'GET' try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_redirect: # Release the connection for this response, since we're not # returning it to be released manually. response.release_conn() raise return response retries.sleep_for_retry(response) log.debug("Redirecting %s -> %s", url, redirect_location) return self.urlopen( method, redirect_location, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, body_pos=body_pos, **response_kw) # Check if we should retry the HTTP response. has_retry_after = bool(response.getheader('Retry-After')) if retries.is_retry(method, response.status, has_retry_after): try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_status: # Release the connection for this response, since we're not # returning it to be released manually. response.release_conn() raise return response retries.sleep(response) log.debug("Retry: %s", url) return self.urlopen( method, url, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, body_pos=body_pos, **response_kw) return response
[ "def", "urlopen", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "retries", "=", "None", ",", "redirect", "=", "True", ",", "assert_same_host", "=", "True", ",", "timeout", "=", "_Default", ",", "p...
https://github.com/cbrgm/telegram-robot-rss/blob/58fe98de427121fdc152c8df0721f1891174e6c9/venv/lib/python2.7/site-packages/telegram/vendor/ptb_urllib3/urllib3/connectionpool.py#L463-L745
Kronuz/esprima-python
809cb6e257b1d3d5b0d23f2bca7976e21f02fc3d
esprima/scanner.py
python
Scanner.scanStringLiteral
(self)
return RawToken( type=Token.StringLiteral, value=str, octal=octal, lineNumber=self.lineNumber, lineStart=self.lineStart, start=start, end=self.index )
[]
def scanStringLiteral(self): start = self.index quote = self.source[start] assert quote in ('\'', '"'), 'String literal must starts with a quote' self.index += 1 octal = False str = '' while not self.eof(): ch = self.source[self.index] self.index += 1 if ch == quote: quote = '' break elif ch == '\\': ch = self.source[self.index] self.index += 1 if not ch or not Character.isLineTerminator(ch): if ch == 'u': if self.source[self.index] == '{': self.index += 1 str += self.scanUnicodeCodePointEscape() else: unescapedChar = self.scanHexEscape(ch) if not unescapedChar: self.throwUnexpectedToken() str += unescapedChar elif ch == 'x': unescaped = self.scanHexEscape(ch) if not unescaped: self.throwUnexpectedToken(Messages.InvalidHexEscapeSequence) str += unescaped elif ch == 'n': str += '\n' elif ch == 'r': str += '\r' elif ch == 't': str += '\t' elif ch == 'b': str += '\b' elif ch == 'f': str += '\f' elif ch == 'v': str += '\x0B' elif ch in ( '8', '9', ): str += ch self.tolerateUnexpectedToken() else: if ch and Character.isOctalDigit(ch): octToDec = self.octalToDecimal(ch) octal = octToDec.octal or octal str += uchr(octToDec.code) else: str += ch else: self.lineNumber += 1 if ch == '\r' and self.source[self.index] == '\n': self.index += 1 self.lineStart = self.index elif Character.isLineTerminator(ch): break else: str += ch if quote != '': self.index = start self.throwUnexpectedToken() return RawToken( type=Token.StringLiteral, value=str, octal=octal, lineNumber=self.lineNumber, lineStart=self.lineStart, start=start, end=self.index )
[ "def", "scanStringLiteral", "(", "self", ")", ":", "start", "=", "self", ".", "index", "quote", "=", "self", ".", "source", "[", "start", "]", "assert", "quote", "in", "(", "'\\''", ",", "'\"'", ")", ",", "'String literal must starts with a quote'", "self", ...
https://github.com/Kronuz/esprima-python/blob/809cb6e257b1d3d5b0d23f2bca7976e21f02fc3d/esprima/scanner.py#L801-L890
OpenMDAO/OpenMDAO-Framework
f2e37b7de3edeaaeb2d251b375917adec059db9b
openmdao.main/src/openmdao/main/resource.py
python
ResourceAllocationManager.add_allocator
(allocator)
Add an allocator to the list of resource allocators. allocator: ResourceAllocator The allocator to be added.
Add an allocator to the list of resource allocators.
[ "Add", "an", "allocator", "to", "the", "list", "of", "resource", "allocators", "." ]
def add_allocator(allocator): """ Add an allocator to the list of resource allocators. allocator: ResourceAllocator The allocator to be added. """ ram = ResourceAllocationManager._get_instance() with ResourceAllocationManager._lock: name = allocator.name for alloc in ram._allocators: if alloc.name == name: raise RuntimeError('allocator named %r already exists' % name) ram._allocators.append(allocator)
[ "def", "add_allocator", "(", "allocator", ")", ":", "ram", "=", "ResourceAllocationManager", ".", "_get_instance", "(", ")", "with", "ResourceAllocationManager", ".", "_lock", ":", "name", "=", "allocator", ".", "name", "for", "alloc", "in", "ram", ".", "_allo...
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.main/src/openmdao/main/resource.py#L221-L234
machinalis/quepy
c0a83fab9b11056f6951ee65046a72ac5d025136
quepy/quepyapp.py
python
QuepyApp._save_settings_values
(self)
Persists the settings values of the app to the settings module so it can be accesible from another part of the software.
Persists the settings values of the app to the settings module so it can be accesible from another part of the software.
[ "Persists", "the", "settings", "values", "of", "the", "app", "to", "the", "settings", "module", "so", "it", "can", "be", "accesible", "from", "another", "part", "of", "the", "software", "." ]
def _save_settings_values(self): """ Persists the settings values of the app to the settings module so it can be accesible from another part of the software. """ for key in dir(self._settings_module): if key.upper() == key: value = getattr(self._settings_module, key) if isinstance(value, str): value = encoding_flexible_conversion(value) setattr(settings, key, value)
[ "def", "_save_settings_values", "(", "self", ")", ":", "for", "key", "in", "dir", "(", "self", ".", "_settings_module", ")", ":", "if", "key", ".", "upper", "(", ")", "==", "key", ":", "value", "=", "getattr", "(", "self", ".", "_settings_module", ",",...
https://github.com/machinalis/quepy/blob/c0a83fab9b11056f6951ee65046a72ac5d025136/quepy/quepyapp.py#L151-L162
lpty/tensorflow_tutorial
5369e34ef0af4133547327514e1f4d3db998dfb6
captchaCnn/cnn_train.py
python
train
(height=CAPTCHA_HEIGHT, width=CAPTCHA_WIDTH, y_size=len(CAPTCHA_LIST)*CAPTCHA_LEN)
cnn训练 :param height: :param width: :param y_size: :return:
cnn训练 :param height: :param width: :param y_size: :return:
[ "cnn训练", ":", "param", "height", ":", ":", "param", "width", ":", ":", "param", "y_size", ":", ":", "return", ":" ]
def train(height=CAPTCHA_HEIGHT, width=CAPTCHA_WIDTH, y_size=len(CAPTCHA_LIST)*CAPTCHA_LEN): ''' cnn训练 :param height: :param width: :param y_size: :return: ''' # cnn在图像大小是2的倍数时性能最高, 如果图像大小不是2的倍数,可以在图像边缘补无用像素 # 在图像上补2行,下补3行,左补2行,右补2行 # np.pad(image,((2,3),(2,2)), 'constant', constant_values=(255,)) acc_rate = 0.95 # 按照图片大小申请占位符 x = tf.placeholder(tf.float32, [None, height * width]) y = tf.placeholder(tf.float32, [None, y_size]) # 防止过拟合 训练时启用 测试时不启用 keep_prob = tf.placeholder(tf.float32) # cnn模型 y_conv = cnn_graph(x, keep_prob, (height, width)) # 最优化 optimizer = optimize_graph(y, y_conv) # 偏差 accuracy = accuracy_graph(y, y_conv) # 启动会话.开始训练 saver = tf.train.Saver() sess = tf.Session() sess.run(tf.global_variables_initializer()) step = 0 while 1: batch_x, batch_y = next_batch(64) sess.run(optimizer, feed_dict={x: batch_x, y: batch_y, keep_prob: 0.75}) # 每训练一百次测试一次 if step % 100 == 0: batch_x_test, batch_y_test = next_batch(100) acc = sess.run(accuracy, feed_dict={x: batch_x_test, y: batch_y_test, keep_prob: 1.0}) print(datetime.now().strftime('%c'), ' step:', step, ' accuracy:', acc) # 偏差满足要求,保存模型 if acc > acc_rate: model_path = os.getcwd() + os.sep + str(acc_rate) + "captcha.model" saver.save(sess, model_path, global_step=step) acc_rate += 0.01 if acc_rate > 0.99: break step += 1 sess.close()
[ "def", "train", "(", "height", "=", "CAPTCHA_HEIGHT", ",", "width", "=", "CAPTCHA_WIDTH", ",", "y_size", "=", "len", "(", "CAPTCHA_LIST", ")", "*", "CAPTCHA_LEN", ")", ":", "# cnn在图像大小是2的倍数时性能最高, 如果图像大小不是2的倍数,可以在图像边缘补无用像素", "# 在图像上补2行,下补3行,左补2行,右补2行", "# np.pad(image,((...
https://github.com/lpty/tensorflow_tutorial/blob/5369e34ef0af4133547327514e1f4d3db998dfb6/captchaCnn/cnn_train.py#L141-L185
collinsctk/PyQYT
7af3673955f94ff1b2df2f94220cd2dab2e252af
ExtentionPackages/pycparser/c_parser.py
python
CParser.p_primary_expression_2
(self, p)
primary_expression : constant
primary_expression : constant
[ "primary_expression", ":", "constant" ]
def p_primary_expression_2(self, p): """ primary_expression : constant """ p[0] = p[1]
[ "def", "p_primary_expression_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/collinsctk/PyQYT/blob/7af3673955f94ff1b2df2f94220cd2dab2e252af/ExtentionPackages/pycparser/c_parser.py#L1572-L1574
hasanirtiza/Pedestron
3bdcf8476edc0741f28a80dd4cb161ac532507ee
tools/ECPB/statistics.py
python
MrFppiMultiPlot.add_result
(self, result, label, linestyle=None, color=None, linewidth=None)
return self
[]
def add_result(self, result, label, linestyle=None, color=None, linewidth=None): mr_fppi = MrFppi(result) score = self.score_method(mr_fppi) if self.append_score_to_label else None self.__helper.add_plot(mr_fppi.fppi, mr_fppi.mr, label=label, score=score, linestyle=linestyle, color=color, linewidth=linewidth) return self
[ "def", "add_result", "(", "self", ",", "result", ",", "label", ",", "linestyle", "=", "None", ",", "color", "=", "None", ",", "linewidth", "=", "None", ")", ":", "mr_fppi", "=", "MrFppi", "(", "result", ")", "score", "=", "self", ".", "score_method", ...
https://github.com/hasanirtiza/Pedestron/blob/3bdcf8476edc0741f28a80dd4cb161ac532507ee/tools/ECPB/statistics.py#L78-L84
dmis-lab/biobert
036f683797251328893b8f1dd6b0a3f5af29c922
modeling.py
python
embedding_lookup
(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False)
return (output, embedding_table)
Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. word_embedding_name: string. Name of the embedding table. use_one_hot_embeddings: bool. If True, use one-hot method for word embeddings. If False, use `tf.nn.embedding_lookup()`. One hot is better for TPUs. Returns: float Tensor of shape [batch_size, seq_length, embedding_size].
Looks up words embeddings for id tensor.
[ "Looks", "up", "words", "embeddings", "for", "id", "tensor", "." ]
def embedding_lookup(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False): """Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. word_embedding_name: string. Name of the embedding table. use_one_hot_embeddings: bool. If True, use one-hot method for word embeddings. If False, use `tf.nn.embedding_lookup()`. One hot is better for TPUs. Returns: float Tensor of shape [batch_size, seq_length, embedding_size]. """ # This function assumes that the input is of shape [batch_size, seq_length, # num_inputs]. # # If the input is a 2D tensor of shape [batch_size, seq_length], we # reshape to [batch_size, seq_length, 1]. if input_ids.shape.ndims == 2: input_ids = tf.expand_dims(input_ids, axis=[-1]) embedding_table = tf.get_variable( name=word_embedding_name, shape=[vocab_size, embedding_size], initializer=create_initializer(initializer_range)) if use_one_hot_embeddings: flat_input_ids = tf.reshape(input_ids, [-1]) one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size) output = tf.matmul(one_hot_input_ids, embedding_table) else: output = tf.nn.embedding_lookup(embedding_table, input_ids) input_shape = get_shape_list(input_ids) output = tf.reshape(output, input_shape[0:-1] + [input_shape[-1] * embedding_size]) return (output, embedding_table)
[ "def", "embedding_lookup", "(", "input_ids", ",", "vocab_size", ",", "embedding_size", "=", "128", ",", "initializer_range", "=", "0.02", ",", "word_embedding_name", "=", "\"word_embeddings\"", ",", "use_one_hot_embeddings", "=", "False", ")", ":", "# This function as...
https://github.com/dmis-lab/biobert/blob/036f683797251328893b8f1dd6b0a3f5af29c922/modeling.py#L381-L427
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/distutils/ccompiler.py
python
CCompiler.library_dir_option
(self, dir)
Return the compiler option to add 'dir' to the list of directories searched for libraries.
Return the compiler option to add 'dir' to the list of directories searched for libraries.
[ "Return", "the", "compiler", "option", "to", "add", "dir", "to", "the", "list", "of", "directories", "searched", "for", "libraries", "." ]
def library_dir_option(self, dir): """Return the compiler option to add 'dir' to the list of directories searched for libraries. """ raise NotImplementedError
[ "def", "library_dir_option", "(", "self", ",", "dir", ")", ":", "raise", "NotImplementedError" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/distutils/ccompiler.py#L742-L746
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/plugins/bitbox02/qt.py
python
BitBox02_Handler._name_multisig_account
(self)
return name.text().strip()
[]
def _name_multisig_account(self): dialog = WindowModalDialog(None, "Create Multisig Account") vbox = QVBoxLayout() label = QLabel( _( "Enter a descriptive name for your multisig account.\nYou should later be able to use the name to uniquely identify this multisig account" ) ) hl = QHBoxLayout() hl.addWidget(label) name = QLineEdit() name.setMaxLength(30) name.resize(200, 40) he = QHBoxLayout() he.addWidget(name) okButton = OkButton(dialog) hlb = QHBoxLayout() hlb.addWidget(okButton) hlb.addStretch(2) vbox.addLayout(hl) vbox.addLayout(he) vbox.addLayout(hlb) dialog.setLayout(vbox) dialog.exec_() return name.text().strip()
[ "def", "_name_multisig_account", "(", "self", ")", ":", "dialog", "=", "WindowModalDialog", "(", "None", ",", "\"Create Multisig Account\"", ")", "vbox", "=", "QVBoxLayout", "(", ")", "label", "=", "QLabel", "(", "_", "(", "\"Enter a descriptive name for your multis...
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/plugins/bitbox02/qt.py#L92-L116
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/trace.py
python
Trace.globaltrace_lt
(self, frame, why, arg)
Handler for call events. If the code block being entered is to be ignored, returns `None', else returns self.localtrace.
Handler for call events.
[ "Handler", "for", "call", "events", "." ]
def globaltrace_lt(self, frame, why, arg): """Handler for call events. If the code block being entered is to be ignored, returns `None', else returns self.localtrace. """ if why == 'call': code = frame.f_code filename = frame.f_globals.get('__file__', None) if filename: # XXX modname() doesn't work right for packages, so # the ignore support won't work right for packages modulename = modname(filename) if modulename is not None: ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: print (" --- modulename: %s, funcname: %s" % (modulename, code.co_name)) return self.localtrace else: return None
[ "def", "globaltrace_lt", "(", "self", ",", "frame", ",", "why", ",", "arg", ")", ":", "if", "why", "==", "'call'", ":", "code", "=", "frame", ".", "f_code", "filename", "=", "frame", ".", "f_globals", ".", "get", "(", "'__file__'", ",", "None", ")", ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/trace.py#L598-L619
sosreport/sos
900e8bea7f3cd36c1dd48f3cbb351ab92f766654
sos/report/plugins/__init__.py
python
Plugin.get_process_pids
(self, process)
return pids
Get a list of all PIDs that match a specified name :param process: The name of the process the get PIDs for :type process: ``str`` :returns: A list of PIDs :rtype: ``list``
Get a list of all PIDs that match a specified name
[ "Get", "a", "list", "of", "all", "PIDs", "that", "match", "a", "specified", "name" ]
def get_process_pids(self, process): """Get a list of all PIDs that match a specified name :param process: The name of the process the get PIDs for :type process: ``str`` :returns: A list of PIDs :rtype: ``list`` """ pids = [] cmd_line_glob = "/proc/[0-9]*/cmdline" cmd_line_paths = glob.glob(cmd_line_glob) for path in cmd_line_paths: try: with open(path, 'r') as f: cmd_line = f.read().strip() if process in cmd_line: pids.append(path.split("/")[2]) except IOError: continue return pids
[ "def", "get_process_pids", "(", "self", ",", "process", ")", ":", "pids", "=", "[", "]", "cmd_line_glob", "=", "\"/proc/[0-9]*/cmdline\"", "cmd_line_paths", "=", "glob", ".", "glob", "(", "cmd_line_glob", ")", "for", "path", "in", "cmd_line_paths", ":", "try",...
https://github.com/sosreport/sos/blob/900e8bea7f3cd36c1dd48f3cbb351ab92f766654/sos/report/plugins/__init__.py#L2929-L2949
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/protocols/basic.py
python
IntNStringReceiver.dataReceived
(self, data)
Convert int prefixed strings into calls to stringReceived.
Convert int prefixed strings into calls to stringReceived.
[ "Convert", "int", "prefixed", "strings", "into", "calls", "to", "stringReceived", "." ]
def dataReceived(self, data): """ Convert int prefixed strings into calls to stringReceived. """ # Try to minimize string copying (via slices) by keeping one buffer # containing all the data we have so far and a separate offset into that # buffer. alldata = self._unprocessed + data currentOffset = 0 prefixLength = self.prefixLength fmt = self.structFormat self._unprocessed = alldata while len(alldata) >= (currentOffset + prefixLength) and not self.paused: messageStart = currentOffset + prefixLength length, = unpack(fmt, alldata[currentOffset:messageStart]) if length > self.MAX_LENGTH: self._unprocessed = alldata self._compatibilityOffset = currentOffset self.lengthLimitExceeded(length) return messageEnd = messageStart + length if len(alldata) < messageEnd: break # Here we have to slice the working buffer so we can send just the # netstring into the stringReceived callback. packet = alldata[messageStart:messageEnd] currentOffset = messageEnd self._compatibilityOffset = currentOffset self.stringReceived(packet) # Check to see if the backwards compat "recvd" attribute got written # to by application code. If so, drop the current data buffer and # switch to the new buffer given by that attribute's value. if 'recvd' in self.__dict__: alldata = self.__dict__.pop('recvd') self._unprocessed = alldata self._compatibilityOffset = currentOffset = 0 if alldata: continue return # Slice off all the data that has been processed, avoiding holding onto # memory to store it, and update the compatibility attributes to reflect # that change. self._unprocessed = alldata[currentOffset:] self._compatibilityOffset = 0
[ "def", "dataReceived", "(", "self", ",", "data", ")", ":", "# Try to minimize string copying (via slices) by keeping one buffer", "# containing all the data we have so far and a separate offset into that", "# buffer.", "alldata", "=", "self", ".", "_unprocessed", "+", "data", "cu...
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/protocols/basic.py#L725-L772
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/connection.py
python
create_connection
(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None)
Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default.
Connect to *address* and return the socket object.
[ "Connect", "to", "*", "address", "*", "and", "return", "the", "socket", "object", "." ]
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address if host.startswith('['): host = host.strip('[]') err = None for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. # This is the only addition urllib3 makes to this function. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as e: err = e if sock is not None: sock.close() sock = None if err is not None: raise err raise socket.error("getaddrinfo returns an empty list")
[ "def", "create_connection", "(", "address", ",", "timeout", "=", "socket", ".", "_GLOBAL_DEFAULT_TIMEOUT", ",", "source_address", "=", "None", ",", "socket_options", "=", "None", ")", ":", "host", ",", "port", "=", "address", "if", "host", ".", "startswith", ...
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/connection.py#L49-L93
SFDO-Tooling/CumulusCI
825ae1f122b25dc41761c52a4ddfa1938d2a4b6e
cumulusci/tasks/bulkdata/snowfakery.py
python
Snowfakery._loop
( self, template_path, tempdir, org_record_counts_thread, portions: PortionGenerator, )
return upload_status
The inner loop that controls when data is generated and when we are done.
The inner loop that controls when data is generated and when we are done.
[ "The", "inner", "loop", "that", "controls", "when", "data", "is", "generated", "and", "when", "we", "are", "done", "." ]
def _loop( self, template_path, tempdir, org_record_counts_thread, portions: PortionGenerator, ): """The inner loop that controls when data is generated and when we are done.""" upload_status = self.get_upload_status( portions.next_batch_size, ) while not portions.done(upload_status.total_sets_working_on_or_uploaded): if self.debug_mode: self.logger.info(f"Working Directory: {tempdir}") self.queue_manager.tick( upload_status, template_path, tempdir, portions, self.get_upload_status, ) self.update_running_totals() self.print_running_totals() time.sleep(WAIT_TIME) upload_status = self._report_status( portions.batch_size, org_record_counts_thread, template_path, ) return upload_status
[ "def", "_loop", "(", "self", ",", "template_path", ",", "tempdir", ",", "org_record_counts_thread", ",", "portions", ":", "PortionGenerator", ",", ")", ":", "upload_status", "=", "self", ".", "get_upload_status", "(", "portions", ".", "next_batch_size", ",", ")"...
https://github.com/SFDO-Tooling/CumulusCI/blob/825ae1f122b25dc41761c52a4ddfa1938d2a4b6e/cumulusci/tasks/bulkdata/snowfakery.py#L331-L365
piergiaj/representation-flow-cvpr19
b9dcb0a7750732210bccf84dbe6044cc33b48c17
baseline_2d_resnets.py
python
resnet152
(pretrained=False, **kwargs)
return model
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "Constructs", "a", "ResNet", "-", "152", "model", ".", "Args", ":", "pretrained", "(", "bool", ")", ":", "If", "True", "returns", "a", "model", "pre", "-", "trained", "on", "ImageNet" ]
def resnet152(pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
[ "def", "resnet152", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "8", ",", "36", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ...
https://github.com/piergiaj/representation-flow-cvpr19/blob/b9dcb0a7750732210bccf84dbe6044cc33b48c17/baseline_2d_resnets.py#L255-L263
alteryx/featuretools
d59e11082962f163540fd6e185901f65c506326a
featuretools/utils/cli_utils.py
python
get_featuretools_root
()
return os.path.dirname(featuretools.__file__)
[]
def get_featuretools_root(): return os.path.dirname(featuretools.__file__)
[ "def", "get_featuretools_root", "(", ")", ":", "return", "os", ".", "path", ".", "dirname", "(", "featuretools", ".", "__file__", ")" ]
https://github.com/alteryx/featuretools/blob/d59e11082962f163540fd6e185901f65c506326a/featuretools/utils/cli_utils.py#L86-L87
PyCQA/astroid
a815443f62faae05249621a396dcf0afd884a619
astroid/inference.py
python
infer_attribute
(self, context=None)
return dict(node=self, context=context)
infer an Attribute node by using getattr on the associated object
infer an Attribute node by using getattr on the associated object
[ "infer", "an", "Attribute", "node", "by", "using", "getattr", "on", "the", "associated", "object" ]
def infer_attribute(self, context=None): """infer an Attribute node by using getattr on the associated object""" for owner in self.expr.infer(context): if owner is util.Uninferable: yield owner continue if not context: context = InferenceContext() old_boundnode = context.boundnode try: context.boundnode = owner yield from owner.igetattr(self.attrname, context) except ( AttributeInferenceError, InferenceError, AttributeError, ): pass finally: context.boundnode = old_boundnode return dict(node=self, context=context)
[ "def", "infer_attribute", "(", "self", ",", "context", "=", "None", ")", ":", "for", "owner", "in", "self", ".", "expr", ".", "infer", "(", "context", ")", ":", "if", "owner", "is", "util", ".", "Uninferable", ":", "yield", "owner", "continue", "if", ...
https://github.com/PyCQA/astroid/blob/a815443f62faae05249621a396dcf0afd884a619/astroid/inference.py#L311-L333
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
var/spack/repos/builtin/packages/hypre/package.py
python
Hypre.headers
(self)
return hdrs or None
Export the main hypre header, HYPRE.h; all other headers can be found in the same directory. Sample usage: spec['hypre'].headers.cpp_flags
Export the main hypre header, HYPRE.h; all other headers can be found in the same directory. Sample usage: spec['hypre'].headers.cpp_flags
[ "Export", "the", "main", "hypre", "header", "HYPRE", ".", "h", ";", "all", "other", "headers", "can", "be", "found", "in", "the", "same", "directory", ".", "Sample", "usage", ":", "spec", "[", "hypre", "]", ".", "headers", ".", "cpp_flags" ]
def headers(self): """Export the main hypre header, HYPRE.h; all other headers can be found in the same directory. Sample usage: spec['hypre'].headers.cpp_flags """ hdrs = find_headers('HYPRE', self.prefix.include, recursive=False) return hdrs or None
[ "def", "headers", "(", "self", ")", ":", "hdrs", "=", "find_headers", "(", "'HYPRE'", ",", "self", ".", "prefix", ".", "include", ",", "recursive", "=", "False", ")", "return", "hdrs", "or", "None" ]
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/var/spack/repos/builtin/packages/hypre/package.py#L264-L270
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
calendarserver/tools/calverify.py
python
CalVerifyService.getAllResourceInfo
(self, inbox=False)
[]
def getAllResourceInfo(self, inbox=False): co = schema.CALENDAR_OBJECT cb = schema.CALENDAR_BIND ch = schema.CALENDAR_HOME if inbox: cojoin = (cb.CALENDAR_RESOURCE_ID == co.CALENDAR_RESOURCE_ID).And( cb.BIND_MODE == _BIND_MODE_OWN) else: cojoin = (cb.CALENDAR_RESOURCE_ID == co.CALENDAR_RESOURCE_ID).And( cb.BIND_MODE == _BIND_MODE_OWN).And( cb.CALENDAR_RESOURCE_NAME != "inbox") kwds = {} rows = (yield Select( [ch.OWNER_UID, co.RESOURCE_ID, co.ICALENDAR_UID, cb.CALENDAR_RESOURCE_NAME, co.MD5, co.ORGANIZER, co.CREATED, co.MODIFIED], From=ch.join( cb, type="inner", on=(ch.RESOURCE_ID == cb.CALENDAR_HOME_RESOURCE_ID)).join( co, type="inner", on=cojoin), GroupBy=(ch.OWNER_UID, co.RESOURCE_ID, co.ICALENDAR_UID, cb.CALENDAR_RESOURCE_NAME, co.MD5, co.ORGANIZER, co.CREATED, co.MODIFIED,), ).on(self.txn, **kwds)) returnValue(tuple(rows))
[ "def", "getAllResourceInfo", "(", "self", ",", "inbox", "=", "False", ")", ":", "co", "=", "schema", ".", "CALENDAR_OBJECT", "cb", "=", "schema", ".", "CALENDAR_BIND", "ch", "=", "schema", ".", "CALENDAR_HOME", "if", "inbox", ":", "cojoin", "=", "(", "cb...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/calendarserver/tools/calverify.py#L483-L504
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/operator.py
python
le
(a, b)
return a <= b
Same as a <= b.
Same as a <= b.
[ "Same", "as", "a", "<", "=", "b", "." ]
def le(a, b): "Same as a <= b." return a <= b
[ "def", "le", "(", "a", ",", "b", ")", ":", "return", "a", "<=", "b" ]
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/operator.py#L32-L34
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/pycryptodomex-3.9.7/lib/Cryptodome/Hash/SHA3_384.py
python
SHA3_384_Hash.new
(self)
return type(self)(None, self._update_after_digest)
Create a fresh SHA3-384 hash object.
Create a fresh SHA3-384 hash object.
[ "Create", "a", "fresh", "SHA3", "-", "384", "hash", "object", "." ]
def new(self): """Create a fresh SHA3-384 hash object.""" return type(self)(None, self._update_after_digest)
[ "def", "new", "(", "self", ")", ":", "return", "type", "(", "self", ")", "(", "None", ",", "self", ".", "_update_after_digest", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/pycryptodomex-3.9.7/lib/Cryptodome/Hash/SHA3_384.py#L114-L117
google-research/language
61fa7260ac7d690d11ef72ca863e45a37c0bdc80
language/conpono/evals/run_squad.py
python
get_final_text
(pred_text, orig_text, do_lower_case)
return output_text
Project the tokenized prediction back to the original text.
Project the tokenized prediction back to the original text.
[ "Project", "the", "tokenized", "prediction", "back", "to", "the", "original", "text", "." ]
def get_final_text(pred_text, orig_text, do_lower_case): """Project the tokenized prediction back to the original text.""" # When we created the data, we kept track of the alignment between original # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So # now `orig_text` contains the span of our original text corresponding to the # span that we predicted. # # However, `orig_text` may contain extra characters that we don't want in # our prediction. # # For example, let's say: # pred_text = steve smith # orig_text = Steve Smith's # # We don't want to return `orig_text` because it contains the extra "'s". # # We don't want to return `pred_text` because it's already been normalized # (the SQuAD eval script also does punctuation stripping/lower casing but # our tokenizer does additional normalization like stripping accent # characters). # # What we really want to return is "Steve Smith". # # Therefore, we have to apply a semi-complicated alignment heruistic between # `pred_text` and `orig_text` to get a character-to-charcter alignment. This # can fail in certain cases in which case we just return `orig_text`. def _strip_spaces(text): ns_chars = [] ns_to_s_map = collections.OrderedDict() for (i, c) in enumerate(text): if c == " ": continue ns_to_s_map[len(ns_chars)] = i ns_chars.append(c) ns_text = "".join(ns_chars) return (ns_text, ns_to_s_map) # We first tokenize `orig_text`, strip whitespace from the result # and `pred_text`, and check if they are the same length. If they are # NOT the same length, the heuristic has failed. If they are the same # length, we assume the characters are one-to-one aligned. tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case) tok_text = " ".join(tokenizer.tokenize(orig_text)) start_position = tok_text.find(pred_text) if start_position == -1: if FLAGS.verbose_logging: tf.logging.info("Unable to find text: '%s' in '%s'" % (pred_text, orig_text)) return orig_text end_position = start_position + len(pred_text) - 1 (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text) (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text) if len(orig_ns_text) != len(tok_ns_text): if FLAGS.verbose_logging: tf.logging.info("Length not equal after stripping spaces: '%s' vs '%s'", orig_ns_text, tok_ns_text) return orig_text # We then project the characters in `pred_text` back to `orig_text` using # the character-to-character alignment. tok_s_to_ns_map = {} for (i, tok_index) in tok_ns_to_s_map.items(): tok_s_to_ns_map[tok_index] = i orig_start_position = None if start_position in tok_s_to_ns_map: ns_start_position = tok_s_to_ns_map[start_position] if ns_start_position in orig_ns_to_s_map: orig_start_position = orig_ns_to_s_map[ns_start_position] if orig_start_position is None: if FLAGS.verbose_logging: tf.logging.info("Couldn't map start position") return orig_text orig_end_position = None if end_position in tok_s_to_ns_map: ns_end_position = tok_s_to_ns_map[end_position] if ns_end_position in orig_ns_to_s_map: orig_end_position = orig_ns_to_s_map[ns_end_position] if orig_end_position is None: if FLAGS.verbose_logging: tf.logging.info("Couldn't map end position") return orig_text output_text = orig_text[orig_start_position:(orig_end_position + 1)] return output_text
[ "def", "get_final_text", "(", "pred_text", ",", "orig_text", ",", "do_lower_case", ")", ":", "# When we created the data, we kept track of the alignment between original", "# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So", "# now `orig_text` contains the span of our or...
https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/conpono/evals/run_squad.py#L927-L1020
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
hazelcast/datadog_checks/hazelcast/config_models/shared.py
python
SharedConfig._ensure_defaults
(cls, v, field)
return getattr(defaults, f'shared_{field.name}')(field, v)
[]
def _ensure_defaults(cls, v, field): if v is not None or field.required: return v return getattr(defaults, f'shared_{field.name}')(field, v)
[ "def", "_ensure_defaults", "(", "cls", ",", "v", ",", "field", ")", ":", "if", "v", "is", "not", "None", "or", "field", ".", "required", ":", "return", "v", "return", "getattr", "(", "defaults", ",", "f'shared_{field.name}'", ")", "(", "field", ",", "v...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/hazelcast/datadog_checks/hazelcast/config_models/shared.py#L50-L54
cltk/cltk
1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1
src/cltk/phonology/non/utils.py
python
Rule.__init__
(self, position, temp_sound, estimated_sound)
:param position: AbstractPosition :param temp_sound: Vowel or Consonant :param estimated_sound: Vowel or Consonant
:param position: AbstractPosition :param temp_sound: Vowel or Consonant :param estimated_sound: Vowel or Consonant
[ ":", "param", "position", ":", "AbstractPosition", ":", "param", "temp_sound", ":", "Vowel", "or", "Consonant", ":", "param", "estimated_sound", ":", "Vowel", "or", "Consonant" ]
def __init__(self, position, temp_sound, estimated_sound): """ :param position: AbstractPosition :param temp_sound: Vowel or Consonant :param estimated_sound: Vowel or Consonant """ assert isinstance(position, AbstractPosition) self.position = position assert isinstance(temp_sound, Vowel) or isinstance(temp_sound, Consonant) self.temp_sound = temp_sound assert isinstance(estimated_sound, Vowel) or isinstance( estimated_sound, Consonant ) self.estimated_sound = estimated_sound
[ "def", "__init__", "(", "self", ",", "position", ",", "temp_sound", ",", "estimated_sound", ")", ":", "assert", "isinstance", "(", "position", ",", "AbstractPosition", ")", "self", ".", "position", "=", "position", "assert", "isinstance", "(", "temp_sound", ",...
https://github.com/cltk/cltk/blob/1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1/src/cltk/phonology/non/utils.py#L430-L443
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/sklearn/feature_extraction/text.py
python
CountVectorizer.fit_transform
(self, raw_documents, y=None)
return X
Learn the vocabulary dictionary and return term-document matrix. This is equivalent to fit followed by transform, but more efficiently implemented. Parameters ---------- raw_documents : iterable An iterable which yields either str, unicode or file objects. Returns ------- X : array, [n_samples, n_features] Document-term matrix.
Learn the vocabulary dictionary and return term-document matrix.
[ "Learn", "the", "vocabulary", "dictionary", "and", "return", "term", "-", "document", "matrix", "." ]
def fit_transform(self, raw_documents, y=None): """Learn the vocabulary dictionary and return term-document matrix. This is equivalent to fit followed by transform, but more efficiently implemented. Parameters ---------- raw_documents : iterable An iterable which yields either str, unicode or file objects. Returns ------- X : array, [n_samples, n_features] Document-term matrix. """ # We intentionally don't call the transform method to make # fit_transform overridable without unwanted side effects in # TfidfVectorizer. if isinstance(raw_documents, six.string_types): raise ValueError( "Iterable over raw text documents expected, " "string object received.") self._validate_vocabulary() max_df = self.max_df min_df = self.min_df max_features = self.max_features vocabulary, X = self._count_vocab(raw_documents, self.fixed_vocabulary_) if self.binary: X.data.fill(1) if not self.fixed_vocabulary_: X = self._sort_features(X, vocabulary) n_doc = X.shape[0] max_doc_count = (max_df if isinstance(max_df, numbers.Integral) else max_df * n_doc) min_doc_count = (min_df if isinstance(min_df, numbers.Integral) else min_df * n_doc) if max_doc_count < min_doc_count: raise ValueError( "max_df corresponds to < documents than min_df") X, self.stop_words_ = self._limit_features(X, vocabulary, max_doc_count, min_doc_count, max_features) self.vocabulary_ = vocabulary return X
[ "def", "fit_transform", "(", "self", ",", "raw_documents", ",", "y", "=", "None", ")", ":", "# We intentionally don't call the transform method to make", "# fit_transform overridable without unwanted side effects in", "# TfidfVectorizer.", "if", "isinstance", "(", "raw_documents"...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/sklearn/feature_extraction/text.py#L809-L864
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/coverage/phystokens.py
python
source_token_lines
(source)
Generate a series of lines, one for each line in `source`. Each line is a list of pairs, each pair is a token:: [('key', 'def'), ('ws', ' '), ('nam', 'hello'), ('op', '('), ... ] Each pair has a token class, and the token text. If you concatenate all the token texts, and then join them with newlines, you should have your original `source` back, with two differences: trailing whitespace is not preserved, and a final line with no newline is indistinguishable from a final line with a newline.
Generate a series of lines, one for each line in `source`.
[ "Generate", "a", "series", "of", "lines", "one", "for", "each", "line", "in", "source", "." ]
def source_token_lines(source): """Generate a series of lines, one for each line in `source`. Each line is a list of pairs, each pair is a token:: [('key', 'def'), ('ws', ' '), ('nam', 'hello'), ('op', '('), ... ] Each pair has a token class, and the token text. If you concatenate all the token texts, and then join them with newlines, you should have your original `source` back, with two differences: trailing whitespace is not preserved, and a final line with no newline is indistinguishable from a final line with a newline. """ ws_tokens = set([token.INDENT, token.DEDENT, token.NEWLINE, tokenize.NL]) line = [] col = 0 source = source.expandtabs(8).replace('\r\n', '\n') tokgen = generate_tokens(source) for ttype, ttext, (_, scol), (_, ecol), _ in phys_tokens(tokgen): mark_start = True for part in re.split('(\n)', ttext): if part == '\n': yield line line = [] col = 0 mark_end = False elif part == '': mark_end = False elif ttype in ws_tokens: mark_end = False else: if mark_start and scol > col: line.append(("ws", u" " * (scol - col))) mark_start = False tok_class = tokenize.tok_name.get(ttype, 'xx').lower()[:3] if ttype == token.NAME and keyword.iskeyword(ttext): tok_class = "key" line.append((tok_class, part)) mark_end = True scol = 0 if mark_end: col = ecol if line: yield line
[ "def", "source_token_lines", "(", "source", ")", ":", "ws_tokens", "=", "set", "(", "[", "token", ".", "INDENT", ",", "token", ".", "DEDENT", ",", "token", ".", "NEWLINE", ",", "tokenize", ".", "NL", "]", ")", "line", "=", "[", "]", "col", "=", "0"...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/coverage/phystokens.py#L75-L124
obspy/obspy
0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f
obspy/signal/spectral_estimation.py
python
PPSD.get_percentile
(self, percentile=50)
return (self.period_bin_centers, percentile_values)
Returns periods and approximate psd values for given percentile value. :type percentile: int :param percentile: percentile for which to return approximate psd value. (e.g. a value of 50 is equal to the median.) :returns: (periods, percentile_values)
Returns periods and approximate psd values for given percentile value.
[ "Returns", "periods", "and", "approximate", "psd", "values", "for", "given", "percentile", "value", "." ]
def get_percentile(self, percentile=50): """ Returns periods and approximate psd values for given percentile value. :type percentile: int :param percentile: percentile for which to return approximate psd value. (e.g. a value of 50 is equal to the median.) :returns: (periods, percentile_values) """ hist_cum = self.current_histogram_cumulative if hist_cum is None: return None # go to percent percentile = percentile / 100.0 if percentile == 0: # only for this special case we have to search from the other side # (otherwise we always get index 0 in .searchsorted()) side = "right" else: side = "left" percentile_values = [col.searchsorted(percentile, side=side) for col in hist_cum] # map to power db values percentile_values = self.db_bin_edges[percentile_values] return (self.period_bin_centers, percentile_values)
[ "def", "get_percentile", "(", "self", ",", "percentile", "=", "50", ")", ":", "hist_cum", "=", "self", ".", "current_histogram_cumulative", "if", "hist_cum", "is", "None", ":", "return", "None", "# go to percent", "percentile", "=", "percentile", "/", "100.0", ...
https://github.com/obspy/obspy/blob/0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f/obspy/signal/spectral_estimation.py#L1307-L1331
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_scale.py
python
Utils.find_result
(results, _name)
return rval
Find the specified result by name
Find the specified result by name
[ "Find", "the", "specified", "result", "by", "name" ]
def find_result(results, _name): ''' Find the specified result by name''' rval = None for result in results: if 'metadata' in result and result['metadata']['name'] == _name: rval = result break return rval
[ "def", "find_result", "(", "results", ",", "_name", ")", ":", "rval", "=", "None", "for", "result", "in", "results", ":", "if", "'metadata'", "in", "result", "and", "result", "[", "'metadata'", "]", "[", "'name'", "]", "==", "_name", ":", "rval", "=", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_scale.py#L1242-L1250
lazylibrarian/LazyLibrarian
ae3c14e9db9328ce81765e094ab2a14ed7155624
lazylibrarian/notifiers/pushbullet2.py
python
PushBullet.pushLink
(self, recipient, title, url, recipient_type="device_iden")
return self._request("POST", HOST + "/pushes", data)
Push a link https://docs.pushbullet.com/v2/pushes Arguments: recipient -- a recipient title -- link title url -- link url recipient_type -- a type of recipient (device, email, channel or client)
Push a link https://docs.pushbullet.com/v2/pushes Arguments: recipient -- a recipient title -- link title url -- link url recipient_type -- a type of recipient (device, email, channel or client)
[ "Push", "a", "link", "https", ":", "//", "docs", ".", "pushbullet", ".", "com", "/", "v2", "/", "pushes", "Arguments", ":", "recipient", "--", "a", "recipient", "title", "--", "link", "title", "url", "--", "link", "url", "recipient_type", "--", "a", "t...
def pushLink(self, recipient, title, url, recipient_type="device_iden"): """ Push a link https://docs.pushbullet.com/v2/pushes Arguments: recipient -- a recipient title -- link title url -- link url recipient_type -- a type of recipient (device, email, channel or client) """ data = {"type": "link", "title": title, "url": url, recipient_type: recipient} return self._request("POST", HOST + "/pushes", data)
[ "def", "pushLink", "(", "self", ",", "recipient", ",", "title", ",", "url", ",", "recipient_type", "=", "\"device_iden\"", ")", ":", "data", "=", "{", "\"type\"", ":", "\"link\"", ",", "\"title\"", ":", "title", ",", "\"url\"", ":", "url", ",", "recipien...
https://github.com/lazylibrarian/LazyLibrarian/blob/ae3c14e9db9328ce81765e094ab2a14ed7155624/lazylibrarian/notifiers/pushbullet2.py#L125-L137
glumpy/glumpy
46a7635c08d3a200478397edbe0371a6c59cd9d7
glumpy/transforms/trackball.py
python
Trackball.__init__
(self, *args, **kwargs)
Initialize the transform.
Initialize the transform.
[ "Initialize", "the", "transform", "." ]
def __init__(self, *args, **kwargs): """ Initialize the transform. """ code = library.get("transforms/trackball.glsl") Transform.__init__(self, code, *args, **kwargs) self._aspect = Transform._get_kwarg("aspect", kwargs) or 1 self._znear = Transform._get_kwarg("znear", kwargs) or 2.0 self._zfar = Transform._get_kwarg("zfar", kwargs) or 1000.0 theta = Transform._get_kwarg("theta", kwargs) or 45 phi = Transform._get_kwarg("phi", kwargs) or 45 self._distance = Transform._get_kwarg("distance", kwargs) or 8 self._zoom = Transform._get_kwarg("zoom", kwargs) or 35 self._width = 1 self._height = 1 self._window_aspect = 1 self._trackball = _trackball.Trackball(45,45) aspect = self._window_aspect * self._aspect self._projection = glm.perspective(self._zoom, aspect, self._znear, self._zfar) self._view = np.eye(4, dtype=np.float32) glm.translate(self._view, 0, 0, -abs(self._distance))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "code", "=", "library", ".", "get", "(", "\"transforms/trackball.glsl\"", ")", "Transform", ".", "__init__", "(", "self", ",", "code", ",", "*", "args", ",", "*", "*...
https://github.com/glumpy/glumpy/blob/46a7635c08d3a200478397edbe0371a6c59cd9d7/glumpy/transforms/trackball.py#L72-L96
Arelle/Arelle
20f3d8a8afd41668e1520799acd333349ce0ba17
arelle/ModelInstanceObject.py
python
ModelFact.value
(self)
return v
(str) -- Text value of fact or default or fixed if any, otherwise None
(str) -- Text value of fact or default or fixed if any, otherwise None
[ "(", "str", ")", "--", "Text", "value", "of", "fact", "or", "default", "or", "fixed", "if", "any", "otherwise", "None" ]
def value(self): """(str) -- Text value of fact or default or fixed if any, otherwise None""" v = self.textValue if not v and self.concept is not None: if self.concept.default is not None: v = self.concept.default elif self.concept.fixed is not None: v = self.concept.fixed return v
[ "def", "value", "(", "self", ")", ":", "v", "=", "self", ".", "textValue", "if", "not", "v", "and", "self", ".", "concept", "is", "not", "None", ":", "if", "self", ".", "concept", ".", "default", "is", "not", "None", ":", "v", "=", "self", ".", ...
https://github.com/Arelle/Arelle/blob/20f3d8a8afd41668e1520799acd333349ce0ba17/arelle/ModelInstanceObject.py#L359-L367
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
src/ezdxf/entities/dimstyleoverride.py
python
DimStyleOverride.get_renderer
(self, ucs: "UCS" = None)
return self.doc.dimension_renderer.dispatch(self, ucs)
Get designated DIMENSION renderer. (internal API)
Get designated DIMENSION renderer. (internal API)
[ "Get", "designated", "DIMENSION", "renderer", ".", "(", "internal", "API", ")" ]
def get_renderer(self, ucs: "UCS" = None): """Get designated DIMENSION renderer. (internal API)""" return self.doc.dimension_renderer.dispatch(self, ucs)
[ "def", "get_renderer", "(", "self", ",", "ucs", ":", "\"UCS\"", "=", "None", ")", ":", "return", "self", ".", "doc", ".", "dimension_renderer", ".", "dispatch", "(", "self", ",", "ucs", ")" ]
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/entities/dimstyleoverride.py#L509-L511
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/xml/sax/saxutils.py
python
XMLGenerator.ignorableWhitespace
(self, content)
[]
def ignorableWhitespace(self, content): if content: self._finish_pending_start_element() if not isinstance(content, str): content = str(content, self._encoding) self._write(content)
[ "def", "ignorableWhitespace", "(", "self", ",", "content", ")", ":", "if", "content", ":", "self", ".", "_finish_pending_start_element", "(", ")", "if", "not", "isinstance", "(", "content", ",", "str", ")", ":", "content", "=", "str", "(", "content", ",", ...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/xml/sax/saxutils.py#L215-L220
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
rope/contrib/fixsyntax.py
python
_Commenter.comment
(self, lineno)
[]
def comment(self, lineno): start = _logical_start(self.lines, lineno, check_prev=True) - 1 # using self._get_stmt_end() instead of self._get_block_end() # to lower commented lines end = self._get_stmt_end(start) indents = _get_line_indents(self.lines[start]) if 0 < start: last_lineno = self._last_non_blank(start - 1) last_line = self.lines[last_lineno] if last_line.rstrip().endswith(':'): indents = _get_line_indents(last_line) + 4 self._set(start, ' ' * indents + 'pass') for line in range(start + 1, end + 1): self._set(line, self.lines[start]) self._fix_incomplete_try_blocks(lineno, indents)
[ "def", "comment", "(", "self", ",", "lineno", ")", ":", "start", "=", "_logical_start", "(", "self", ".", "lines", ",", "lineno", ",", "check_prev", "=", "True", ")", "-", "1", "# using self._get_stmt_end() instead of self._get_block_end()", "# to lower commented li...
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/contrib/fixsyntax.py#L79-L93
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/returners/pushover_returner.py
python
returner
(ret)
return
Send an PushOver message with the data
Send an PushOver message with the data
[ "Send", "an", "PushOver", "message", "with", "the", "data" ]
def returner(ret): """ Send an PushOver message with the data """ _options = _get_options(ret) user = _options.get("user") device = _options.get("device") token = _options.get("token") title = _options.get("title") priority = _options.get("priority") expire = _options.get("expire") retry = _options.get("retry") sound = _options.get("sound") if not token: raise SaltInvocationError("Pushover token is unavailable.") if not user: raise SaltInvocationError("Pushover user key is unavailable.") if priority and priority == 2: if not expire and not retry: raise SaltInvocationError( "Priority 2 requires pushover.expire and pushover.retry options." ) message = "id: {}\r\nfunction: {}\r\nfunction args: {}\r\njid: {}\r\nreturn: {}\r\n".format( ret.get("id"), ret.get("fun"), ret.get("fun_args"), ret.get("jid"), pprint.pformat(ret.get("return")), ) result = _post_message( user=user, device=device, message=message, title=title, priority=priority, expire=expire, retry=retry, sound=sound, token=token, ) log.debug("pushover result %s", result) if not result["res"]: log.info("Error: %s", result["message"]) return
[ "def", "returner", "(", "ret", ")", ":", "_options", "=", "_get_options", "(", "ret", ")", "user", "=", "_options", ".", "get", "(", "\"user\"", ")", "device", "=", "_options", ".", "get", "(", "\"device\"", ")", "token", "=", "_options", ".", "get", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/returners/pushover_returner.py#L205-L256
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_adm_csr.py
python
Yedit.process_edits
(edits, yamlfile)
return {'changed': len(results) > 0, 'results': results}
run through a list of edits and process them one-by-one
run through a list of edits and process them one-by-one
[ "run", "through", "a", "list", "of", "edits", "and", "process", "them", "one", "-", "by", "-", "one" ]
def process_edits(edits, yamlfile): '''run through a list of edits and process them one-by-one''' results = [] for edit in edits: value = Yedit.parse_value(edit['value'], edit.get('value_type', '')) if edit.get('action') == 'update': # pylint: disable=line-too-long curr_value = Yedit.get_curr_value( Yedit.parse_value(edit.get('curr_value')), edit.get('curr_value_format')) rval = yamlfile.update(edit['key'], value, edit.get('index'), curr_value) elif edit.get('action') == 'append': rval = yamlfile.append(edit['key'], value) else: rval = yamlfile.put(edit['key'], value) if rval[0]: results.append({'key': edit['key'], 'edit': rval[1]}) return {'changed': len(results) > 0, 'results': results}
[ "def", "process_edits", "(", "edits", ",", "yamlfile", ")", ":", "results", "=", "[", "]", "for", "edit", "in", "edits", ":", "value", "=", "Yedit", ".", "parse_value", "(", "edit", "[", "'value'", "]", ",", "edit", ".", "get", "(", "'value_type'", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_adm_csr.py#L711-L736
yoda-pa/yoda
e6b4325737b877488af4d1bf0b86eb1d98b88aed
modules/love.py
python
setup
()
create new setup :return:
create new setup :return:
[ "create", "new", "setup", ":", "return", ":" ]
def setup(): """ create new setup :return: """ create_folder(LOVE_CONFIG_FOLDER_PATH) if ask_overwrite(LOVE_CONFIG_FILE_PATH): return click.echo(chalk.blue("Enter their name:")) name = input().strip() click.echo(chalk.blue("Enter sex(M/F):")) sex = input().strip() click.echo(chalk.blue("Where do they live?")) place = input().strip() setup_data = dict(name=name, place=place, sex=sex) input_data(setup_data, LOVE_CONFIG_FILE_PATH)
[ "def", "setup", "(", ")", ":", "create_folder", "(", "LOVE_CONFIG_FOLDER_PATH", ")", "if", "ask_overwrite", "(", "LOVE_CONFIG_FILE_PATH", ")", ":", "return", "click", ".", "echo", "(", "chalk", ".", "blue", "(", "\"Enter their name:\"", ")", ")", "name", "=", ...
https://github.com/yoda-pa/yoda/blob/e6b4325737b877488af4d1bf0b86eb1d98b88aed/modules/love.py#L47-L68
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/loader/lazy.py
python
LazyLoader._run_as
(self, _func_or_method, *args, **kwargs)
Handle setting up the context properly and call the method
Handle setting up the context properly and call the method
[ "Handle", "setting", "up", "the", "context", "properly", "and", "call", "the", "method" ]
def _run_as(self, _func_or_method, *args, **kwargs): """ Handle setting up the context properly and call the method """ self.parent_loader = None try: current_loader = salt.loader.context.loader_ctxvar.get() except LookupError: current_loader = None if current_loader is not self: self.parent_loader = current_loader token = salt.loader.context.loader_ctxvar.set(self) try: return _func_or_method(*args, **kwargs) finally: self.parent_loader = None salt.loader.context.loader_ctxvar.reset(token)
[ "def", "_run_as", "(", "self", ",", "_func_or_method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parent_loader", "=", "None", "try", ":", "current_loader", "=", "salt", ".", "loader", ".", "context", ".", "loader_ctxvar", ".", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/loader/lazy.py#L1203-L1219
steemit/steem-python
57fb0f1436fbea27a74386d35815f45fb3076814
steem/wallet.py
python
Wallet.locked
(self)
return False if self.decryptedKEK else True
Is the wallet database locked?
Is the wallet database locked?
[ "Is", "the", "wallet", "database", "locked?" ]
def locked(self): """ Is the wallet database locked? """ return False if self.decryptedKEK else True
[ "def", "locked", "(", "self", ")", ":", "return", "False", "if", "self", ".", "decryptedKEK", "else", "True" ]
https://github.com/steemit/steem-python/blob/57fb0f1436fbea27a74386d35815f45fb3076814/steem/wallet.py#L113-L116
JustDoPython/python-100-day
4e75007195aa4cdbcb899aeb06b9b08996a4606c
day-005/def.py
python
reduce
(a,b)
return a-b
[]
def reduce(a,b) : return a-b
[ "def", "reduce", "(", "a", ",", "b", ")", ":", "return", "a", "-", "b" ]
https://github.com/JustDoPython/python-100-day/blob/4e75007195aa4cdbcb899aeb06b9b08996a4606c/day-005/def.py#L19-L20
django-oscar/django-oscar-accounts
8a6dc3b42306979779f048b4d3ed0a9fd4a2f794
src/oscar_accounts/abstract_models.py
python
Transfer.as_dict
(self)
return { 'reference': self.reference, 'source_code': self.source.code, 'source_name': self.source.name, 'destination_code': self.destination.code, 'destination_name': self.destination.name, 'amount': "%.2f" % self.amount, 'available_to_refund': "%.2f" % self.max_refund(), 'datetime': self.date_created.isoformat(), 'merchant_reference': self.merchant_reference, 'description': self.description, 'reverse_url': reverse( 'oscar_accounts_api:transfer-reverse', kwargs={'reference': self.reference}), 'refunds_url': reverse( 'oscar_accounts_api:transfer-refunds', kwargs={'reference': self.reference})}
[]
def as_dict(self): return { 'reference': self.reference, 'source_code': self.source.code, 'source_name': self.source.name, 'destination_code': self.destination.code, 'destination_name': self.destination.name, 'amount': "%.2f" % self.amount, 'available_to_refund': "%.2f" % self.max_refund(), 'datetime': self.date_created.isoformat(), 'merchant_reference': self.merchant_reference, 'description': self.description, 'reverse_url': reverse( 'oscar_accounts_api:transfer-reverse', kwargs={'reference': self.reference}), 'refunds_url': reverse( 'oscar_accounts_api:transfer-refunds', kwargs={'reference': self.reference})}
[ "def", "as_dict", "(", "self", ")", ":", "return", "{", "'reference'", ":", "self", ".", "reference", ",", "'source_code'", ":", "self", ".", "source", ".", "code", ",", "'source_name'", ":", "self", ".", "source", ".", "name", ",", "'destination_code'", ...
https://github.com/django-oscar/django-oscar-accounts/blob/8a6dc3b42306979779f048b4d3ed0a9fd4a2f794/src/oscar_accounts/abstract_models.py#L407-L424
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/font_manager.py
python
FontProperties.get_file
(self)
return self._file
Return the filename of the associated font.
Return the filename of the associated font.
[ "Return", "the", "filename", "of", "the", "associated", "font", "." ]
def get_file(self): """ Return the filename of the associated font. """ return self._file
[ "def", "get_file", "(", "self", ")", ":", "return", "self", ".", "_file" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/font_manager.py#L688-L692
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/apigateway/v20180808/apigateway_client.py
python
ApigatewayClient.CreateApiApp
(self, request)
本接口(CreateApiApp)用于创建应用。 :param request: Request instance for CreateApiApp. :type request: :class:`tencentcloud.apigateway.v20180808.models.CreateApiAppRequest` :rtype: :class:`tencentcloud.apigateway.v20180808.models.CreateApiAppResponse`
本接口(CreateApiApp)用于创建应用。
[ "本接口(CreateApiApp)用于创建应用。" ]
def CreateApiApp(self, request): """本接口(CreateApiApp)用于创建应用。 :param request: Request instance for CreateApiApp. :type request: :class:`tencentcloud.apigateway.v20180808.models.CreateApiAppRequest` :rtype: :class:`tencentcloud.apigateway.v20180808.models.CreateApiAppResponse` """ try: params = request._serialize() body = self.call("CreateApiApp", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateApiAppResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "CreateApiApp", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"CreateApiApp\"", ",", "params", ")", "response", "=", "json", ".", "loads", "(", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/apigateway/v20180808/apigateway_client.py#L285-L310
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/cookies.py
python
parse_value
(value, allow_spaces=True, unquote=default_unquote)
return value
Process a cookie value
Process a cookie value
[ "Process", "a", "cookie", "value" ]
def parse_value(value, allow_spaces=True, unquote=default_unquote): "Process a cookie value" if value is None: return None value = strip_spaces_and_quotes(value) value = parse_string(value, unquote=unquote) if not allow_spaces: assert ' ' not in value return value
[ "def", "parse_value", "(", "value", ",", "allow_spaces", "=", "True", ",", "unquote", "=", "default_unquote", ")", ":", "if", "value", "is", "None", ":", "return", "None", "value", "=", "strip_spaces_and_quotes", "(", "value", ")", "value", "=", "parse_strin...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/cookies.py#L419-L427
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
bin/x86/Debug/scripting_engine/Lib/smtplib.py
python
SMTP.verify
(self, address)
return self.getreply()
SMTP 'verify' command -- checks for address validity.
SMTP 'verify' command -- checks for address validity.
[ "SMTP", "verify", "command", "--", "checks", "for", "address", "validity", "." ]
def verify(self, address): """SMTP 'verify' command -- checks for address validity.""" self.putcmd("vrfy", quoteaddr(address)) return self.getreply()
[ "def", "verify", "(", "self", ",", "address", ")", ":", "self", ".", "putcmd", "(", "\"vrfy\"", ",", "quoteaddr", "(", "address", ")", ")", "return", "self", ".", "getreply", "(", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/smtplib.py#L498-L501
microsoft/botbuilder-python
3d410365461dc434df59bdfeaa2f16d28d9df868
libraries/botbuilder-schema/botbuilder/schema/_models_py3.py
python
Activity.create_contact_relation_update_activity
()
return Activity(type=ActivityTypes.contact_relation_update)
Creates an instance of the :class:`Activity` class as aContactRelationUpdateActivity object. :returns: The new contact relation update activity.
Creates an instance of the :class:`Activity` class as aContactRelationUpdateActivity object.
[ "Creates", "an", "instance", "of", "the", ":", "class", ":", "Activity", "class", "as", "aContactRelationUpdateActivity", "object", "." ]
def create_contact_relation_update_activity(): """ Creates an instance of the :class:`Activity` class as aContactRelationUpdateActivity object. :returns: The new contact relation update activity. """ return Activity(type=ActivityTypes.contact_relation_update)
[ "def", "create_contact_relation_update_activity", "(", ")", ":", "return", "Activity", "(", "type", "=", "ActivityTypes", ".", "contact_relation_update", ")" ]
https://github.com/microsoft/botbuilder-python/blob/3d410365461dc434df59bdfeaa2f16d28d9df868/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py#L557-L563
PaddlePaddle/PaddleFL
583691acd5db0a7ca331cc9a72415017b18669b8
python/paddle_fl/feature_engineering/core/federated_feature_engineering_server.py
python
FederatedFeatureEngineeringServer.serve
(self, server)
server init with grpc server
server init with grpc server
[ "server", "init", "with", "grpc", "server" ]
def serve(self, server): """ server init with grpc server """ self._server = server
[ "def", "serve", "(", "self", ",", "server", ")", ":", "self", ".", "_server", "=", "server" ]
https://github.com/PaddlePaddle/PaddleFL/blob/583691acd5db0a7ca331cc9a72415017b18669b8/python/paddle_fl/feature_engineering/core/federated_feature_engineering_server.py#L26-L30
otuncelli/turkish-stemmer-python
0c22380bf84a5ab1f219f4a905274c78afa04ed1
TurkishStemmer/__init__.py
python
HasRoundness
(vowel, candidate)
return ((vowel in UNROUNDED_VOWELS and candidate in UNROUNDED_VOWELS) or (vowel in ROUNDED_VOWELS and candidate in FOLLOWING_ROUNDED_VOWELS))
Checks the roundness harmony of two characters. Args: vowel (str): the first character candidate (str): candidate the second character Returns: bool: whether the two characters have roundness harmony or not.
Checks the roundness harmony of two characters.
[ "Checks", "the", "roundness", "harmony", "of", "two", "characters", "." ]
def HasRoundness(vowel, candidate): """ Checks the roundness harmony of two characters. Args: vowel (str): the first character candidate (str): candidate the second character Returns: bool: whether the two characters have roundness harmony or not. """ return ((vowel in UNROUNDED_VOWELS and candidate in UNROUNDED_VOWELS) or (vowel in ROUNDED_VOWELS and candidate in FOLLOWING_ROUNDED_VOWELS))
[ "def", "HasRoundness", "(", "vowel", ",", "candidate", ")", ":", "return", "(", "(", "vowel", "in", "UNROUNDED_VOWELS", "and", "candidate", "in", "UNROUNDED_VOWELS", ")", "or", "(", "vowel", "in", "ROUNDED_VOWELS", "and", "candidate", "in", "FOLLOWING_ROUNDED_VO...
https://github.com/otuncelli/turkish-stemmer-python/blob/0c22380bf84a5ab1f219f4a905274c78afa04ed1/TurkishStemmer/__init__.py#L339-L351
OpenNMT/OpenNMT-tf
59a4dfdb911d0570ba1096b7a0a7b9fc5c7844bf
opennmt/data/vocab.py
python
Vocab.load
(self, path, file_format="default")
Loads a serialized vocabulary. Args: path: The path to the vocabulary to load. file_format: Define the format of the vocabulary file. Can be: default, sentencepiece. "default" is simply one token per line. Raises: ValueError: if :obj:`file_format` is invalid.
Loads a serialized vocabulary.
[ "Loads", "a", "serialized", "vocabulary", "." ]
def load(self, path, file_format="default"): """Loads a serialized vocabulary. Args: path: The path to the vocabulary to load. file_format: Define the format of the vocabulary file. Can be: default, sentencepiece. "default" is simply one token per line. Raises: ValueError: if :obj:`file_format` is invalid. """ if file_format not in ("default", "sentencepiece"): raise ValueError("Invalid vocabulary format: %s" % file_format) with tf.io.gfile.GFile(path) as vocab: for i, line in enumerate(vocab): token = line.rstrip("\r\n") if file_format == "sentencepiece": token, _ = token.split("\t") # Ignore SentencePiece special tokens. if token in ("<unk>", "<s>", "</s>"): continue if token in self._token_to_id: tf.get_logger().warning( "Duplicate token '%s' in vocabulary %s at line %d", token, path, i + 1, ) continue self._token_to_id[token] = len(self._id_to_token) self._id_to_token.append(token) self._frequency.append(1)
[ "def", "load", "(", "self", ",", "path", ",", "file_format", "=", "\"default\"", ")", ":", "if", "file_format", "not", "in", "(", "\"default\"", ",", "\"sentencepiece\"", ")", ":", "raise", "ValueError", "(", "\"Invalid vocabulary format: %s\"", "%", "file_forma...
https://github.com/OpenNMT/OpenNMT-tf/blob/59a4dfdb911d0570ba1096b7a0a7b9fc5c7844bf/opennmt/data/vocab.py#L107-L140
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/quantum_info/operators/symplectic/pauli_list.py
python
PauliList.transpose
(self)
return PauliList(super().transpose())
Return the transpose of each Pauli in the list.
Return the transpose of each Pauli in the list.
[ "Return", "the", "transpose", "of", "each", "Pauli", "in", "the", "list", "." ]
def transpose(self): """Return the transpose of each Pauli in the list.""" return PauliList(super().transpose())
[ "def", "transpose", "(", "self", ")", ":", "return", "PauliList", "(", "super", "(", ")", ".", "transpose", "(", ")", ")" ]
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/quantum_info/operators/symplectic/pauli_list.py#L772-L774
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/ext/mapreduce/shuffler.py
python
_sort_records_map
(records)
Map function sorting records. Converts records to KeyValue protos, sorts them by key and writes them into new GCS file. Creates _OutputFile entity to record resulting file name. Args: records: list of records which are serialized KeyValue protos.
Map function sorting records.
[ "Map", "function", "sorting", "records", "." ]
def _sort_records_map(records): """Map function sorting records. Converts records to KeyValue protos, sorts them by key and writes them into new GCS file. Creates _OutputFile entity to record resulting file name. Args: records: list of records which are serialized KeyValue protos. """ ctx = context.get() l = len(records) key_records = [None] * l logging.debug("Parsing") for i in range(l): proto = kv_pb.KeyValue() proto.ParseFromString(records[i]) key_records[i] = (proto.key(), records[i]) logging.debug("Sorting") key_records.sort(cmp=_compare_keys) logging.debug("Writing") mapper_spec = ctx.mapreduce_spec.mapper params = input_readers._get_params(mapper_spec) bucket_name = params.get("bucket_name") filename = (ctx.mapreduce_spec.name + "/" + ctx.mapreduce_id + "/output-" + ctx.shard_id + "-" + str(int(time.time()))) full_filename = "/%s/%s" % (bucket_name, filename) filehandle = cloudstorage.open(full_filename, mode="w") with output_writers.GCSRecordsPool(filehandle, ctx=ctx) as pool: for key_record in key_records: pool.append(key_record[1]) logging.debug("Finalizing") filehandle.close() entity = _OutputFile(key_name=full_filename, parent=_OutputFile.get_root_key(ctx.mapreduce_id)) entity.put()
[ "def", "_sort_records_map", "(", "records", ")", ":", "ctx", "=", "context", ".", "get", "(", ")", "l", "=", "len", "(", "records", ")", "key_records", "=", "[", "None", "]", "*", "l", "logging", ".", "debug", "(", "\"Parsing\"", ")", "for", "i", "...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/mapreduce/shuffler.py#L140-L180
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/aifc.py
python
_read_long
(file)
[]
def _read_long(file): try: return struct.unpack('>l', file.read(4))[0] except struct.error: raise EOFError from None
[ "def", "_read_long", "(", "file", ")", ":", "try", ":", "return", "struct", ".", "unpack", "(", "'>l'", ",", "file", ".", "read", "(", "4", ")", ")", "[", "0", "]", "except", "struct", ".", "error", ":", "raise", "EOFError", "from", "None" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/aifc.py#L148-L152
wrye-bash/wrye-bash
d495c47cfdb44475befa523438a40c4419cb386f
Mopy/bash/bolt.py
python
popen_common
(popen_cmd, **kwargs)
return subprocess.Popen(popen_cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo, **kwargs)
Wrapper around subprocess.Popen with commonly needed parameters.
Wrapper around subprocess.Popen with commonly needed parameters.
[ "Wrapper", "around", "subprocess", ".", "Popen", "with", "commonly", "needed", "parameters", "." ]
def popen_common(popen_cmd, **kwargs): """Wrapper around subprocess.Popen with commonly needed parameters.""" return subprocess.Popen(popen_cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo, **kwargs)
[ "def", "popen_common", "(", "popen_cmd", ",", "*", "*", "kwargs", ")", ":", "return", "subprocess", ".", "Popen", "(", "popen_cmd", ",", "stdin", "=", "subprocess", ".", "DEVNULL", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subpr...
https://github.com/wrye-bash/wrye-bash/blob/d495c47cfdb44475befa523438a40c4419cb386f/Mopy/bash/bolt.py#L976-L980
RDFLib/sparqlwrapper
3fdb48d52bf97c789d121b9650591deba16bcaa6
SPARQLWrapper/Wrapper.py
python
SPARQLWrapper._getRequestEncodedParameters
(self, query=None)
return "&".join(pairs)
Internal method for getting the request encoded parameters. :param query: a tuple of two items. The first item can be the string \ ``query`` (for :data:`SELECT`, :data:`DESCRIBE`, :data:`ASK`, :data:`CONSTRUCT` query) or the string ``update`` (for SPARQL Update queries, like :data:`DELETE` or :data:`INSERT`). The second item of the tuple is the query string itself. :type query: tuple :return: the request encoded parameters. :rtype: string
Internal method for getting the request encoded parameters.
[ "Internal", "method", "for", "getting", "the", "request", "encoded", "parameters", "." ]
def _getRequestEncodedParameters(self, query=None): """ Internal method for getting the request encoded parameters. :param query: a tuple of two items. The first item can be the string \ ``query`` (for :data:`SELECT`, :data:`DESCRIBE`, :data:`ASK`, :data:`CONSTRUCT` query) or the string ``update`` (for SPARQL Update queries, like :data:`DELETE` or :data:`INSERT`). The second item of the tuple is the query string itself. :type query: tuple :return: the request encoded parameters. :rtype: string """ query_parameters = self.parameters.copy() # in case of query = tuple("query"/"update", queryString) if query and (isinstance(query, tuple)) and len(query) == 2: query_parameters[query[0]] = [query[1]] if not self.isSparqlUpdateRequest(): # This is very ugly. The fact is that the key for the choice of the output format is not defined. # Virtuoso uses 'format',sparqler uses 'output' # However, these processors are (hopefully) oblivious to the parameters they do not understand. # So: just repeat all possibilities in the final URI. UGLY!!!!!!! if not self.onlyConneg: for f in _returnFormatSetting: query_parameters[f] = [self.returnFormat] # Virtuoso is not supporting a correct Accept header and an unexpected "output"/"format" parameter # value. It returns a 406. # "tsv", "rdf+xml" and "json-ld" are not supported as a correct "output"/"format" parameter value # but "text/tab-separated-values" or "application/rdf+xml" are a valid values, # and there is no problem to send both (4store does not support unexpected values). if self.returnFormat in [TSV, JSONLD, RDFXML]: acceptHeader = ( self._getAcceptHeader() ) # to obtain the mime-type "text/tab-separated-values" or "application/rdf+xml" if "*/*" in acceptHeader: acceptHeader = "" # clear the value in case of "*/*" query_parameters[f] += [acceptHeader] pairs = ( "%s=%s" % ( urllib.parse.quote_plus(param.encode("UTF-8"), safe="/"), urllib.parse.quote_plus(value.encode("UTF-8"), safe="/"), ) for param, values in query_parameters.items() for value in values ) return "&".join(pairs)
[ "def", "_getRequestEncodedParameters", "(", "self", ",", "query", "=", "None", ")", ":", "query_parameters", "=", "self", ".", "parameters", ".", "copy", "(", ")", "# in case of query = tuple(\"query\"/\"update\", queryString)", "if", "query", "and", "(", "isinstance"...
https://github.com/RDFLib/sparqlwrapper/blob/3fdb48d52bf97c789d121b9650591deba16bcaa6/SPARQLWrapper/Wrapper.py#L691-L738
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/req/req_file.py
python
join_lines
(lines_enum)
Joins a line ending in '\' with the previous line (except when following comments). The joined line takes on the index of the first line.
Joins a line ending in '\' with the previous line (except when following comments). The joined line takes on the index of the first line.
[ "Joins", "a", "line", "ending", "in", "\\", "with", "the", "previous", "line", "(", "except", "when", "following", "comments", ")", ".", "The", "joined", "line", "takes", "on", "the", "index", "of", "the", "first", "line", "." ]
def join_lines(lines_enum): # type: (ReqFileLines) -> ReqFileLines """Joins a line ending in '\' with the previous line (except when following comments). The joined line takes on the index of the first line. """ primary_line_number = None new_line = [] # type: List[Text] for line_number, line in lines_enum: if not line.endswith('\\') or COMMENT_RE.match(line): if COMMENT_RE.match(line): # this ensures comments are always matched later line = ' ' + line if new_line: new_line.append(line) yield primary_line_number, ''.join(new_line) new_line = [] else: yield line_number, line else: if not new_line: primary_line_number = line_number new_line.append(line.strip('\\')) # last line contains \ if new_line: yield primary_line_number, ''.join(new_line)
[ "def", "join_lines", "(", "lines_enum", ")", ":", "# type: (ReqFileLines) -> ReqFileLines", "primary_line_number", "=", "None", "new_line", "=", "[", "]", "# type: List[Text]", "for", "line_number", ",", "line", "in", "lines_enum", ":", "if", "not", "line", ".", "...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/req/req_file.py#L301-L326
zhaoolee/StarsAndClown
b2d4039cad2f9232b691e5976f787b49a0a2c113
node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py
python
_LookupTargets
(names, mapping)
return [mapping[name] for name in names if name in mapping]
Returns a list of the mapping[name] for each value in |names| that is in |mapping|.
Returns a list of the mapping[name] for each value in |names| that is in |mapping|.
[ "Returns", "a", "list", "of", "the", "mapping", "[", "name", "]", "for", "each", "value", "in", "|names|", "that", "is", "in", "|mapping|", "." ]
def _LookupTargets(names, mapping): """Returns a list of the mapping[name] for each value in |names| that is in |mapping|.""" return [mapping[name] for name in names if name in mapping]
[ "def", "_LookupTargets", "(", "names", ",", "mapping", ")", ":", "return", "[", "mapping", "[", "name", "]", "for", "name", "in", "names", "if", "name", "in", "mapping", "]" ]
https://github.com/zhaoolee/StarsAndClown/blob/b2d4039cad2f9232b691e5976f787b49a0a2c113/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py#L569-L572
timonwong/OmniMarkupPreviewer
21921ac7a99d2b5924a2219b33679a5b53621392
OmniMarkupLib/libs/bottle.py
python
BaseResponse.set_header
(self, name, value)
Create a new response header, replacing any previously defined headers with the same name.
Create a new response header, replacing any previously defined headers with the same name.
[ "Create", "a", "new", "response", "header", "replacing", "any", "previously", "defined", "headers", "with", "the", "same", "name", "." ]
def set_header(self, name, value): ''' Create a new response header, replacing any previously defined headers with the same name. ''' self._headers[_hkey(name)] = [str(value)]
[ "def", "set_header", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "_headers", "[", "_hkey", "(", "name", ")", "]", "=", "[", "str", "(", "value", ")", "]" ]
https://github.com/timonwong/OmniMarkupPreviewer/blob/21921ac7a99d2b5924a2219b33679a5b53621392/OmniMarkupLib/libs/bottle.py#L1361-L1364
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_scatter3d.py
python
Scatter3d.surfacecolor
(self)
return self["surfacecolor"]
Sets the surface fill color. The 'surfacecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str
Sets the surface fill color. The 'surfacecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen
[ "Sets", "the", "surface", "fill", "color", ".", "The", "surfacecolor", "property", "is", "a", "color", "and", "may", "be", "specified", "as", ":", "-", "A", "hex", "string", "(", "e", ".", "g", ".", "#ff0000", ")", "-", "An", "rgb", "/", "rgba", "s...
def surfacecolor(self): """ Sets the surface fill color. The 'surfacecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["surfacecolor"]
[ "def", "surfacecolor", "(", "self", ")", ":", "return", "self", "[", "\"surfacecolor\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_scatter3d.py#L1228-L1278
jwyang/fpn.pytorch
23bd1d2fa09fbb9453f11625d758a61b9d600942
lib/model/fpn/resnet.py
python
resnet50
(pretrained=False)
return model
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "Constructs", "a", "ResNet", "-", "50", "model", ".", "Args", ":", "pretrained", "(", "bool", ")", ":", "If", "True", "returns", "a", "model", "pre", "-", "trained", "on", "ImageNet" ]
def resnet50(pretrained=False): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
[ "def", "resnet50", "(", "pretrained", "=", "False", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url...
https://github.com/jwyang/fpn.pytorch/blob/23bd1d2fa09fbb9453f11625d758a61b9d600942/lib/model/fpn/resnet.py#L186-L194
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/qtconsole-4.1.0-py3.3.egg/qtconsole/completion_html.py
python
SlidingInterval.stop
(self)
return self._stop
end of interval to show
end of interval to show
[ "end", "of", "interval", "to", "show" ]
def stop(self): """end of interval to show""" return self._stop
[ "def", "stop", "(", "self", ")", ":", "return", "self", ".", "_stop" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/qtconsole-4.1.0-py3.3.egg/qtconsole/completion_html.py#L98-L100
4shadoww/hakkuframework
409a11fc3819d251f86faa3473439f8c19066a21
lib/requests/cookies.py
python
extract_cookies_to_jar
(jar, request, response)
Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object
Extract the cookies from the response into a CookieJar.
[ "Extract", "the", "cookies", "from", "the", "response", "into", "a", "CookieJar", "." ]
def extract_cookies_to_jar(jar, request, response): """Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object """ if not (hasattr(response, '_original_response') and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req)
[ "def", "extract_cookies_to_jar", "(", "jar", ",", "request", ",", "response", ")", ":", "if", "not", "(", "hasattr", "(", "response", ",", "'_original_response'", ")", "and", "response", ".", "_original_response", ")", ":", "return", "# the _original_response fiel...
https://github.com/4shadoww/hakkuframework/blob/409a11fc3819d251f86faa3473439f8c19066a21/lib/requests/cookies.py#L118-L132
statsmodels/statsmodels
debbe7ea6ba28fe5bdb78f09f8cac694bef98722
statsmodels/multivariate/factor_rotation/_gpa_rotation.py
python
vgQ_partial_target
(H, W=None, L=None, A=None, T=None)
return q, Gq
r""" Subroutine for the value of vgQ using orthogonal rotation towards a partial target matrix, i.e., we minimize: .. math:: \phi(L) =\frac{1}{2}\|W\circ(L-H)\|^2, where :math:`\circ` is the element-wise product or Hadamard product and :math:`W` is a matrix whose entries can only be one or zero. The gradient is given by .. math:: d\phi(L)=W\circ(L-H). Either :math:`L` should be provided or :math:`A` and :math:`T` should be provided. For orthogonal rotations :math:`L` satisfies .. math:: L = AT, where :math:`T` is an orthogonal matrix. Parameters ---------- H : numpy matrix target matrix W : numpy matrix (default matrix with equal weight one for all entries) matrix with weights, entries can either be one or zero L : numpy matrix (default None) rotated factors, i.e., :math:`L=A(T^*)^{-1}=AT` A : numpy matrix (default None) non rotated factors T : numpy matrix (default None) rotation matrix
r""" Subroutine for the value of vgQ using orthogonal rotation towards a partial target matrix, i.e., we minimize:
[ "r", "Subroutine", "for", "the", "value", "of", "vgQ", "using", "orthogonal", "rotation", "towards", "a", "partial", "target", "matrix", "i", ".", "e", ".", "we", "minimize", ":" ]
def vgQ_partial_target(H, W=None, L=None, A=None, T=None): r""" Subroutine for the value of vgQ using orthogonal rotation towards a partial target matrix, i.e., we minimize: .. math:: \phi(L) =\frac{1}{2}\|W\circ(L-H)\|^2, where :math:`\circ` is the element-wise product or Hadamard product and :math:`W` is a matrix whose entries can only be one or zero. The gradient is given by .. math:: d\phi(L)=W\circ(L-H). Either :math:`L` should be provided or :math:`A` and :math:`T` should be provided. For orthogonal rotations :math:`L` satisfies .. math:: L = AT, where :math:`T` is an orthogonal matrix. Parameters ---------- H : numpy matrix target matrix W : numpy matrix (default matrix with equal weight one for all entries) matrix with weights, entries can either be one or zero L : numpy matrix (default None) rotated factors, i.e., :math:`L=A(T^*)^{-1}=AT` A : numpy matrix (default None) non rotated factors T : numpy matrix (default None) rotation matrix """ if W is None: return vgQ_target(H, L=L, A=A, T=T) if L is None: assert(A is not None and T is not None) L = rotateA(A, T, rotation_method='orthogonal') q = np.linalg.norm(W*(L-H), 'fro')**2 Gq = 2*W*(L-H) return q, Gq
[ "def", "vgQ_partial_target", "(", "H", ",", "W", "=", "None", ",", "L", "=", "None", ",", "A", "=", "None", ",", "T", "=", "None", ")", ":", "if", "W", "is", "None", ":", "return", "vgQ_target", "(", "H", ",", "L", "=", "L", ",", "A", "=", ...
https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/multivariate/factor_rotation/_gpa_rotation.py#L507-L552
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/smtplib.py
python
SMTP.helo
(self, name='')
return (code, msg)
SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host.
SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host.
[ "SMTP", "helo", "command", ".", "Hostname", "to", "send", "for", "this", "command", "defaults", "to", "the", "FQDN", "of", "the", "local", "host", "." ]
def helo(self, name=''): """SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host. """ self.putcmd("helo", name or self.local_hostname) (code, msg) = self.getreply() self.helo_resp = msg return (code, msg)
[ "def", "helo", "(", "self", ",", "name", "=", "''", ")", ":", "self", ".", "putcmd", "(", "\"helo\"", ",", "name", "or", "self", ".", "local_hostname", ")", "(", "code", ",", "msg", ")", "=", "self", ".", "getreply", "(", ")", "self", ".", "helo_...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/smtplib.py#L397-L405
oddt/oddt
8cf555820d97a692ade81c101ebe10e28bcb3722
oddt/toolkits/ob.py
python
Molecule.make2D
(self)
Generate 2D coordinates for molecule
Generate 2D coordinates for molecule
[ "Generate", "2D", "coordinates", "for", "molecule" ]
def make2D(self): """Generate 2D coordinates for molecule""" pybel._operations['gen2D'].Do(self.OBMol) self._clear_cache()
[ "def", "make2D", "(", "self", ")", ":", "pybel", ".", "_operations", "[", "'gen2D'", "]", ".", "Do", "(", "self", ".", "OBMol", ")", "self", ".", "_clear_cache", "(", ")" ]
https://github.com/oddt/oddt/blob/8cf555820d97a692ade81c101ebe10e28bcb3722/oddt/toolkits/ob.py#L260-L263
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/flatmenu.py
python
FlatMenuButton.SetSize
(self, input1, input2=None)
Sets the size for :class:`FlatMenuButton`. :param `input1`: if it is an instance of :class:`wx.Size`, it represents the :class:`FlatMenuButton` size and the `input2` parameter is not used. Otherwise it is an integer representing the button width; :param `input2`: if not ``None``, it is an integer representing the button height.
Sets the size for :class:`FlatMenuButton`.
[ "Sets", "the", "size", "for", ":", "class", ":", "FlatMenuButton", "." ]
def SetSize(self, input1, input2=None): """ Sets the size for :class:`FlatMenuButton`. :param `input1`: if it is an instance of :class:`wx.Size`, it represents the :class:`FlatMenuButton` size and the `input2` parameter is not used. Otherwise it is an integer representing the button width; :param `input2`: if not ``None``, it is an integer representing the button height. """ if type(input) == type(1): self._size = wx.Size(input1, input2) else: self._size = input1
[ "def", "SetSize", "(", "self", ",", "input1", ",", "input2", "=", "None", ")", ":", "if", "type", "(", "input", ")", "==", "type", "(", "1", ")", ":", "self", ".", "_size", "=", "wx", ".", "Size", "(", "input1", ",", "input2", ")", "else", ":",...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/flatmenu.py#L4105-L4118