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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/reminders/views.py | python | KeywordsListView.total | (self) | return Keyword.get_by_domain(self.domain).count() | [] | def total(self):
return Keyword.get_by_domain(self.domain).count() | [
"def",
"total",
"(",
"self",
")",
":",
"return",
"Keyword",
".",
"get_by_domain",
"(",
"self",
".",
"domain",
")",
".",
"count",
"(",
")"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/reminders/views.py#L272-L273 | |||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/extensions/interface.py | python | ExtensionPoint.extend | (self, impl=None, *, domains=None) | return _extend if impl is None else _extend(impl) | [] | def extend(self, impl=None, *, domains=None):
def _extend(impl):
if self.manager.locked:
raise ExtensionError(
"Late extension definition. Extensions must be defined before setup is complete"
)
if not callable(impl):
raise ExtensionError(f"Extension point implementation must be callable: {impl!r}")
extension = Extension(self.name, impl, domains)
extension.validate(self.providing_args)
self.extensions.append(extension)
return impl
if domains is not None and not isinstance(domains, list):
raise ExtensionError("domains must be a list")
if domains is not None and "domain" not in self.providing_args:
raise ExtensionError("domain filtering not supported for this extension point")
return _extend if impl is None else _extend(impl) | [
"def",
"extend",
"(",
"self",
",",
"impl",
"=",
"None",
",",
"*",
",",
"domains",
"=",
"None",
")",
":",
"def",
"_extend",
"(",
"impl",
")",
":",
"if",
"self",
".",
"manager",
".",
"locked",
":",
"raise",
"ExtensionError",
"(",
"\"Late extension defini... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/extensions/interface.py#L72-L90 | |||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/ota/admin.py | python | MobileRecoveryMeasureAdmin.save_model | (self, request, obj, form, change) | [] | def save_model(self, request, obj, form, change):
obj.username = request.user.username
super(MobileRecoveryMeasureAdmin, self).save_model(request, obj, form, change)
get_recovery_measures_cached.clear(obj.domain, obj.app_id) | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"obj",
".",
"username",
"=",
"request",
".",
"user",
".",
"username",
"super",
"(",
"MobileRecoveryMeasureAdmin",
",",
"self",
")",
".",
"save_model",
"("... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/ota/admin.py#L61-L64 | ||||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/symtable.py | python | Symbol.is_free | (self) | return bool(self.__scope == FREE) | Return *True* if a referenced symbol is
not assigned to. | Return *True* if a referenced symbol is
not assigned to. | [
"Return",
"*",
"True",
"*",
"if",
"a",
"referenced",
"symbol",
"is",
"not",
"assigned",
"to",
"."
] | def is_free(self):
"""Return *True* if a referenced symbol is
not assigned to.
"""
return bool(self.__scope == FREE) | [
"def",
"is_free",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"__scope",
"==",
"FREE",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/symtable.py#L273-L277 | |
Autodesk/molecular-design-toolkit | 5f45a47fea21d3603899a6366cb163024f0e2ec4 | moldesign/interfaces/openmm.py | python | topology_to_mol | (topo, name=None, positions=None, velocities=None, assign_bond_orders=True) | return newmol | Convert an OpenMM topology object into an MDT molecule.
Args:
topo (simtk.openmm.app.topology.Topology): topology to convert
name (str): name to assign to molecule
positions (list): simtk list of atomic positions
velocities (list): simtk list of atomic velocities
assign_bond_orders (bool): assign bond orders from templates (simtk topologies
do not store bond orders) | Convert an OpenMM topology object into an MDT molecule. | [
"Convert",
"an",
"OpenMM",
"topology",
"object",
"into",
"an",
"MDT",
"molecule",
"."
] | def topology_to_mol(topo, name=None, positions=None, velocities=None, assign_bond_orders=True):
""" Convert an OpenMM topology object into an MDT molecule.
Args:
topo (simtk.openmm.app.topology.Topology): topology to convert
name (str): name to assign to molecule
positions (list): simtk list of atomic positions
velocities (list): simtk list of atomic velocities
assign_bond_orders (bool): assign bond orders from templates (simtk topologies
do not store bond orders)
"""
from simtk import unit as stku
# Atoms
atommap = {}
newatoms = []
masses = u.amu*[atom.element.mass.value_in_unit(stku.amu) for atom in topo.atoms()]
for atom,mass in zip(topo.atoms(), masses):
newatom = mdt.Atom(atnum=atom.element.atomic_number,
name=atom.name,
mass=mass)
atommap[atom] = newatom
newatoms.append(newatom)
# Coordinates
if positions is not None:
poslist = np.array([p.value_in_unit(stku.nanometer) for p in positions]) * u.nm
poslist.ito(u.default.length)
for newatom, position in zip(newatoms, poslist):
newatom.position = position
if velocities is not None:
velolist = np.array([v.value_in_unit(stku.nanometer/stku.femtosecond) for v in velocities]) * u.nm/u.fs
velolist = u.default.convert(velolist)
for newatom, velocity in zip(newatoms, velolist):
newatom.momentum = newatom.mass * simtk2pint(velocity)
# Biounits
chains = {}
for chain in topo.chains():
if chain.id not in chains:
chains[chain.id] = mdt.Chain(name=chain.id, index=chain.index)
newchain = chains[chain.id]
for residue in chain.residues():
newresidue = mdt.Residue(name='%s%d' % (residue.name,
residue.index),
chain=newchain,
pdbindex=int(residue.id),
pdbname=residue.name)
newchain.add(newresidue)
for atom in residue.atoms():
newatom = atommap[atom]
newatom.residue = newresidue
newresidue.add(newatom)
# Bonds
bonds = {}
for bond in topo.bonds():
a1, a2 = bond
na1, na2 = atommap[a1], atommap[a2]
if na1 not in bonds:
bonds[na1] = {}
if na2 not in bonds:
bonds[na2] = {}
b = mdt.Bond(na1, na2)
b.order = 1
if name is None:
name = 'Unnamed molecule from OpenMM'
newmol = mdt.Molecule(newatoms, name=name)
if assign_bond_orders:
for residue in newmol.residues:
try:
residue.assign_template_bonds()
except (KeyError, ValueError):
pass
return newmol | [
"def",
"topology_to_mol",
"(",
"topo",
",",
"name",
"=",
"None",
",",
"positions",
"=",
"None",
",",
"velocities",
"=",
"None",
",",
"assign_bond_orders",
"=",
"True",
")",
":",
"from",
"simtk",
"import",
"unit",
"as",
"stku",
"# Atoms",
"atommap",
"=",
... | https://github.com/Autodesk/molecular-design-toolkit/blob/5f45a47fea21d3603899a6366cb163024f0e2ec4/moldesign/interfaces/openmm.py#L223-L302 | |
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/mlab.py | python | ispower2 | (n) | Returns the log base 2 of *n* if *n* is a power of 2, zero otherwise.
Note the potential ambiguity if *n* == 1: 2**0 == 1, interpret accordingly. | Returns the log base 2 of *n* if *n* is a power of 2, zero otherwise. | [
"Returns",
"the",
"log",
"base",
"2",
"of",
"*",
"n",
"*",
"if",
"*",
"n",
"*",
"is",
"a",
"power",
"of",
"2",
"zero",
"otherwise",
"."
] | def ispower2(n):
"""
Returns the log base 2 of *n* if *n* is a power of 2, zero otherwise.
Note the potential ambiguity if *n* == 1: 2**0 == 1, interpret accordingly.
"""
bin_n = binary_repr(n)[1:]
if '1' in bin_n:
return 0
else:
return len(bin_n) | [
"def",
"ispower2",
"(",
"n",
")",
":",
"bin_n",
"=",
"binary_repr",
"(",
"n",
")",
"[",
"1",
":",
"]",
"if",
"'1'",
"in",
"bin_n",
":",
"return",
"0",
"else",
":",
"return",
"len",
"(",
"bin_n",
")"
] | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/mlab.py#L2263-L2274 | ||
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/kubernetes/client/models/v1_replication_controller.py | python | V1ReplicationController.kind | (self, kind) | Sets the kind of this V1ReplicationController.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
:param kind: The kind of this V1ReplicationController.
:type: str | Sets the kind of this V1ReplicationController.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds | [
"Sets",
"the",
"kind",
"of",
"this",
"V1ReplicationController",
".",
"Kind",
"is",
"a",
"string",
"value",
"representing",
"the",
"REST",
"resource",
"this",
"object",
"represents",
".",
"Servers",
"may",
"infer",
"this",
"from",
"the",
"endpoint",
"the",
"cli... | def kind(self, kind):
"""
Sets the kind of this V1ReplicationController.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
:param kind: The kind of this V1ReplicationController.
:type: str
"""
self._kind = kind | [
"def",
"kind",
"(",
"self",
",",
"kind",
")",
":",
"self",
".",
"_kind",
"=",
"kind"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_replication_controller.py#L90-L99 | ||
earthgecko/skyline | 12754424de72593e29eb21009fb1ae3f07f3abff | skyline/analyzer_dev/analyzer_dev.py | python | AnalyzerDev.spawn_alerter_process | (self, alert, metric, context) | Spawn a process to trigger an alert.
This is used by smtp alerters so that matplotlib objects are cleared
down and the alerter cannot create a memory leak in this manner and
plt.savefig keeps the object in memory until the process terminates.
Seeing as data is being surfaced and processed in the alert_smtp
context, multiprocessing the alert creation and handling prevents any
memory leaks in the parent.
Added 20160814 relating to:
* Bug #1558: Memory leak in Analyzer
* Issue #21 Memory leak in Analyzer see https://github.com/earthgecko/skyline/issues/21
Parameters as per :py:func:`skyline.analyzer.alerters.trigger_alert
<analyzer.alerters.trigger_alert>` | Spawn a process to trigger an alert. | [
"Spawn",
"a",
"process",
"to",
"trigger",
"an",
"alert",
"."
] | def spawn_alerter_process(self, alert, metric, context):
"""
Spawn a process to trigger an alert.
This is used by smtp alerters so that matplotlib objects are cleared
down and the alerter cannot create a memory leak in this manner and
plt.savefig keeps the object in memory until the process terminates.
Seeing as data is being surfaced and processed in the alert_smtp
context, multiprocessing the alert creation and handling prevents any
memory leaks in the parent.
Added 20160814 relating to:
* Bug #1558: Memory leak in Analyzer
* Issue #21 Memory leak in Analyzer see https://github.com/earthgecko/skyline/issues/21
Parameters as per :py:func:`skyline.analyzer.alerters.trigger_alert
<analyzer.alerters.trigger_alert>`
"""
trigger_alert(alert, metric, context) | [
"def",
"spawn_alerter_process",
"(",
"self",
",",
"alert",
",",
"metric",
",",
"context",
")",
":",
"trigger_alert",
"(",
"alert",
",",
"metric",
",",
"context",
")"
] | https://github.com/earthgecko/skyline/blob/12754424de72593e29eb21009fb1ae3f07f3abff/skyline/analyzer_dev/analyzer_dev.py#L138-L159 | ||
vmware-archive/vsphere-storage-for-docker | 96d2ce72457047af4ef05cb0a8794cf623803865 | esx_service/utils/threadutils.py | python | get_local_storage | () | return threading.local() | Return a thread local storage object | Return a thread local storage object | [
"Return",
"a",
"thread",
"local",
"storage",
"object"
] | def get_local_storage():
"""Return a thread local storage object"""
return threading.local() | [
"def",
"get_local_storage",
"(",
")",
":",
"return",
"threading",
".",
"local",
"(",
")"
] | https://github.com/vmware-archive/vsphere-storage-for-docker/blob/96d2ce72457047af4ef05cb0a8794cf623803865/esx_service/utils/threadutils.py#L111-L113 | |
unknown-horizons/unknown-horizons | 7397fb333006d26c3d9fe796c7bd9cb8c3b43a49 | horizons/network/networkinterface.py | python | NetworkInterface.network_data_changed | (self) | Call in case constants like client address or client port changed.
@throws RuntimeError in case of invalid data or an NetworkException forwarded from connect | Call in case constants like client address or client port changed. | [
"Call",
"in",
"case",
"constants",
"like",
"client",
"address",
"or",
"client",
"port",
"changed",
"."
] | def network_data_changed(self):
"""Call in case constants like client address or client port changed.
@throws RuntimeError in case of invalid data or an NetworkException forwarded from connect
"""
if self.is_connected:
self.disconnect()
self._setup_client() | [
"def",
"network_data_changed",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_connected",
":",
"self",
".",
"disconnect",
"(",
")",
"self",
".",
"_setup_client",
"(",
")"
] | https://github.com/unknown-horizons/unknown-horizons/blob/7397fb333006d26c3d9fe796c7bd9cb8c3b43a49/horizons/network/networkinterface.py#L154-L161 | ||
angr/angr | 4b04d56ace135018083d36d9083805be8146688b | angr/storage/memory_mixins/paged_memory/pages/cooperation.py | python | CooperationBase._zero_objects | (cls, addr, size, **kwargs) | Like decompose objects, but with a size to zero-fill instead of explicit data | Like decompose objects, but with a size to zero-fill instead of explicit data | [
"Like",
"decompose",
"objects",
"but",
"with",
"a",
"size",
"to",
"zero",
"-",
"fill",
"instead",
"of",
"explicit",
"data"
] | def _zero_objects(cls, addr, size, **kwargs):
"""
Like decompose objects, but with a size to zero-fill instead of explicit data
"""
pass | [
"def",
"_zero_objects",
"(",
"cls",
",",
"addr",
",",
"size",
",",
"*",
"*",
"kwargs",
")",
":",
"pass"
] | https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/storage/memory_mixins/paged_memory/pages/cooperation.py#L29-L33 | ||
codeforamerica/glossary-bot | 98bfac31e6878e6ac9293682c79f6dddc301472c | migrations/env.py | python | run_migrations_online | () | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | Run migrations in 'online' mode. | [
"Run",
"migrations",
"in",
"online",
"mode",
"."
] | def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
connection = engine.connect()
context.configure(
connection=connection,
target_metadata=target_metadata
)
try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close() | [
"def",
"run_migrations_online",
"(",
")",
":",
"engine",
"=",
"engine_from_config",
"(",
"config",
".",
"get_section",
"(",
"config",
".",
"config_ini_section",
")",
",",
"prefix",
"=",
"'sqlalchemy.'",
",",
"poolclass",
"=",
"pool",
".",
"NullPool",
")",
"con... | https://github.com/codeforamerica/glossary-bot/blob/98bfac31e6878e6ac9293682c79f6dddc301472c/migrations/env.py#L45-L67 | ||
Emptyset110/dHydra | 8ec44994ff4dda8bf1ec40e38dd068b757945933 | dHydra/Worker/Web/Web.py | python | Web.__init__ | (self, port=5000, **kwargs) | [] | def __init__(self, port=5000, **kwargs):
super().__init__(**kwargs) # You ae not supposed to change THIS
self.port = port | [
"def",
"__init__",
"(",
"self",
",",
"port",
"=",
"5000",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"*",
"*",
"kwargs",
")",
"# You ae not supposed to change THIS",
"self",
".",
"port",
"=",
"port"
] | https://github.com/Emptyset110/dHydra/blob/8ec44994ff4dda8bf1ec40e38dd068b757945933/dHydra/Worker/Web/Web.py#L6-L8 | ||||
smart-mobile-software/gitstack | d9fee8f414f202143eb6e620529e8e5539a2af56 | python/Lib/site-packages/django/core/files/uploadhandler.py | python | TemporaryFileUploadHandler.new_file | (self, file_name, *args, **kwargs) | Create the file object to append to as data is coming in. | Create the file object to append to as data is coming in. | [
"Create",
"the",
"file",
"object",
"to",
"append",
"to",
"as",
"data",
"is",
"coming",
"in",
"."
] | def new_file(self, file_name, *args, **kwargs):
"""
Create the file object to append to as data is coming in.
"""
super(TemporaryFileUploadHandler, self).new_file(file_name, *args, **kwargs)
self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset) | [
"def",
"new_file",
"(",
"self",
",",
"file_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"TemporaryFileUploadHandler",
",",
"self",
")",
".",
"new_file",
"(",
"file_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"s... | https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/core/files/uploadhandler.py#L130-L135 | ||
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/pkg_resources/__init__.py | python | MarkerEvaluation.evaluate_marker | (cls, text, extra=None) | return cls.interpret(parser.expr(text).totuple(1)[1]) | Evaluate a PEP 426 environment marker on CPython 2.4+.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the 'parser' module, which is not implemented
on
Jython and has been superseded by the 'ast' module in Python 2.6 and
later. | Evaluate a PEP 426 environment marker on CPython 2.4+.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid. | [
"Evaluate",
"a",
"PEP",
"426",
"environment",
"marker",
"on",
"CPython",
"2",
".",
"4",
"+",
".",
"Return",
"a",
"boolean",
"indicating",
"the",
"marker",
"result",
"in",
"this",
"environment",
".",
"Raise",
"SyntaxError",
"if",
"marker",
"is",
"invalid",
... | def evaluate_marker(cls, text, extra=None):
"""
Evaluate a PEP 426 environment marker on CPython 2.4+.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the 'parser' module, which is not implemented
on
Jython and has been superseded by the 'ast' module in Python 2.6 and
later.
"""
return cls.interpret(parser.expr(text).totuple(1)[1]) | [
"def",
"evaluate_marker",
"(",
"cls",
",",
"text",
",",
"extra",
"=",
"None",
")",
":",
"return",
"cls",
".",
"interpret",
"(",
"parser",
".",
"expr",
"(",
"text",
")",
".",
"totuple",
"(",
"1",
")",
"[",
"1",
"]",
")"
] | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/pkg_resources/__init__.py#L1500-L1511 | |
naftaliharris/tauthon | 5587ceec329b75f7caf6d65a036db61ac1bae214 | Lib/mailbox.py | python | _singlefileMailbox.flush | (self) | Write any pending changes to disk. | Write any pending changes to disk. | [
"Write",
"any",
"pending",
"changes",
"to",
"disk",
"."
] | def flush(self):
"""Write any pending changes to disk."""
if not self._pending:
if self._pending_sync:
# Messages have only been added, so syncing the file
# is enough.
_sync_flush(self._file)
self._pending_sync = False
return
# In order to be writing anything out at all, self._toc must
# already have been generated (and presumably has been modified
# by adding or deleting an item).
assert self._toc is not None
# Check length of self._file; if it's changed, some other process
# has modified the mailbox since we scanned it.
self._file.seek(0, 2)
cur_len = self._file.tell()
if cur_len != self._file_length:
raise ExternalClashError('Size of mailbox file changed '
'(expected %i, found %i)' %
(self._file_length, cur_len))
new_file = _create_temporary(self._path)
try:
new_toc = {}
self._pre_mailbox_hook(new_file)
for key in sorted(self._toc.keys()):
start, stop = self._toc[key]
self._file.seek(start)
self._pre_message_hook(new_file)
new_start = new_file.tell()
while True:
buffer = self._file.read(min(4096,
stop - self._file.tell()))
if buffer == '':
break
new_file.write(buffer)
new_toc[key] = (new_start, new_file.tell())
self._post_message_hook(new_file)
self._file_length = new_file.tell()
except:
new_file.close()
os.remove(new_file.name)
raise
_sync_close(new_file)
# self._file is about to get replaced, so no need to sync.
self._file.close()
# Make sure the new file's mode is the same as the old file's
mode = os.stat(self._path).st_mode
os.chmod(new_file.name, mode)
try:
os.rename(new_file.name, self._path)
except OSError, e:
if e.errno == errno.EEXIST or \
(os.name == 'os2' and e.errno == errno.EACCES):
os.remove(self._path)
os.rename(new_file.name, self._path)
else:
raise
self._file = open(self._path, 'rb+')
self._toc = new_toc
self._pending = False
self._pending_sync = False
if self._locked:
_lock_file(self._file, dotlock=False) | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pending",
":",
"if",
"self",
".",
"_pending_sync",
":",
"# Messages have only been added, so syncing the file",
"# is enough.",
"_sync_flush",
"(",
"self",
".",
"_file",
")",
"self",
".",
"_pendi... | https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/mailbox.py#L640-L706 | ||
cortex-lab/phy | 9a330b9437a3d0b40a37a201d147224e6e7fb462 | phy/plot/gloo/texture.py | python | TextureCube._deactivate | (self) | Deactivate texture on GPU | Deactivate texture on GPU | [
"Deactivate",
"texture",
"on",
"GPU"
] | def _deactivate(self):
""" Deactivate texture on GPU """
log.log(5, "GPU: Deactivate texture cube")
gl.glBindTexture(self._target, 0)
gl.glDisable(gl.GL_TEXTURE_CUBE_MAP) | [
"def",
"_deactivate",
"(",
"self",
")",
":",
"log",
".",
"log",
"(",
"5",
",",
"\"GPU: Deactivate texture cube\"",
")",
"gl",
".",
"glBindTexture",
"(",
"self",
".",
"_target",
",",
"0",
")",
"gl",
".",
"glDisable",
"(",
"gl",
".",
"GL_TEXTURE_CUBE_MAP",
... | https://github.com/cortex-lab/phy/blob/9a330b9437a3d0b40a37a201d147224e6e7fb462/phy/plot/gloo/texture.py#L463-L468 | ||
gaasedelen/lighthouse | 7245a2d2c4e84351cd259ed81dafa4263167909a | plugins/lighthouse/painting/painter.py | python | DatabasePainter._rebase_database | (self) | return True | Rebase the active database paint.
TODO/XXX: there may be some edgecases where painting can be wrong if
a rebase occurs while the painter is running. | Rebase the active database paint. | [
"Rebase",
"the",
"active",
"database",
"paint",
"."
] | def _rebase_database(self):
"""
Rebase the active database paint.
TODO/XXX: there may be some edgecases where painting can be wrong if
a rebase occurs while the painter is running.
"""
db_metadata = self.director.metadata
instructions = db_metadata.instructions
nodes = viewvalues(db_metadata.nodes)
# a rebase has not occurred
if not db_metadata.cached or (db_metadata.imagebase == self._imagebase):
return False
# compute the offset of the rebase
rebase_offset = db_metadata.imagebase - self._imagebase
# rebase the cached addresses of what we have painted
self._painted_nodes = set([address+rebase_offset for address in self._painted_nodes])
self._painted_instructions = set([address+rebase_offset for address in self._painted_instructions])
self._imagebase = db_metadata.imagebase
# a rebase has been observed
return True | [
"def",
"_rebase_database",
"(",
"self",
")",
":",
"db_metadata",
"=",
"self",
".",
"director",
".",
"metadata",
"instructions",
"=",
"db_metadata",
".",
"instructions",
"nodes",
"=",
"viewvalues",
"(",
"db_metadata",
".",
"nodes",
")",
"# a rebase has not occurred... | https://github.com/gaasedelen/lighthouse/blob/7245a2d2c4e84351cd259ed81dafa4263167909a/plugins/lighthouse/painting/painter.py#L532-L556 | |
openstack/python-glanceclient | b4c3be8aac5a09a6d47b0168ddbd33a2a4298294 | glanceclient/v2/images.py | python | Controller.data | (self, image_id, do_checksum=True, allow_md5_fallback=False) | return utils.IterableWithLength(body, content_length), resp | Retrieve data of an image.
When do_checksum is enabled, validation proceeds as follows:
1. if the image has a 'os_hash_value' property, the algorithm
specified in the image's 'os_hash_algo' property will be used
to validate against the 'os_hash_value' value. If the
specified hash algorithm is not available AND allow_md5_fallback
is True, then continue to step #2
2. else if the image has a checksum property, MD5 is used to
validate against the 'checksum' value. (If MD5 is not available
to the client, the download fails.)
3. else if the download response has a 'content-md5' header, MD5
is used to validate against the header value. (If MD5 is not
available to the client, the download fails.)
4. if none of 1-3 obtain, the data is **not validated** (this is
compatible with legacy behavior)
:param image_id: ID of the image to download
:param do_checksum: Enable/disable checksum validation
:param allow_md5_fallback:
Use the MD5 checksum for validation if the algorithm specified by
the image's 'os_hash_algo' property is not available
:returns: An iterable body or ``None`` | Retrieve data of an image. | [
"Retrieve",
"data",
"of",
"an",
"image",
"."
] | def data(self, image_id, do_checksum=True, allow_md5_fallback=False):
"""Retrieve data of an image.
When do_checksum is enabled, validation proceeds as follows:
1. if the image has a 'os_hash_value' property, the algorithm
specified in the image's 'os_hash_algo' property will be used
to validate against the 'os_hash_value' value. If the
specified hash algorithm is not available AND allow_md5_fallback
is True, then continue to step #2
2. else if the image has a checksum property, MD5 is used to
validate against the 'checksum' value. (If MD5 is not available
to the client, the download fails.)
3. else if the download response has a 'content-md5' header, MD5
is used to validate against the header value. (If MD5 is not
available to the client, the download fails.)
4. if none of 1-3 obtain, the data is **not validated** (this is
compatible with legacy behavior)
:param image_id: ID of the image to download
:param do_checksum: Enable/disable checksum validation
:param allow_md5_fallback:
Use the MD5 checksum for validation if the algorithm specified by
the image's 'os_hash_algo' property is not available
:returns: An iterable body or ``None``
"""
if do_checksum:
# doing this first to prevent race condition if image record
# is deleted during the image download
url = '/v2/images/%s' % image_id
resp, image_meta = self.http_client.get(url)
meta_checksum = image_meta.get('checksum', None)
meta_hash_value = image_meta.get('os_hash_value', None)
meta_hash_algo = image_meta.get('os_hash_algo', None)
url = '/v2/images/%s/file' % image_id
resp, body = self.http_client.get(url)
if resp.status_code == codes.no_content:
return None, resp
checksum = resp.headers.get('content-md5', None)
content_length = int(resp.headers.get('content-length', 0))
check_md5sum = do_checksum
if do_checksum and meta_hash_value is not None:
try:
hasher = hashlib.new(str(meta_hash_algo))
body = utils.serious_integrity_iter(body,
hasher,
meta_hash_value)
check_md5sum = False
except ValueError as ve:
if (str(ve).startswith('unsupported hash type') and
allow_md5_fallback):
check_md5sum = True
else:
raise
if do_checksum and check_md5sum:
if meta_checksum is not None:
body = utils.integrity_iter(body, meta_checksum)
elif checksum is not None:
body = utils.integrity_iter(body, checksum)
else:
# NOTE(rosmaita): this preserves legacy behavior to return the
# image data when checksumming is requested but there's no
# 'content-md5' header in the response. Just want to make it
# clear that we're doing this on purpose.
pass
return utils.IterableWithLength(body, content_length), resp | [
"def",
"data",
"(",
"self",
",",
"image_id",
",",
"do_checksum",
"=",
"True",
",",
"allow_md5_fallback",
"=",
"False",
")",
":",
"if",
"do_checksum",
":",
"# doing this first to prevent race condition if image record",
"# is deleted during the image download",
"url",
"=",... | https://github.com/openstack/python-glanceclient/blob/b4c3be8aac5a09a6d47b0168ddbd33a2a4298294/glanceclient/v2/images.py#L219-L289 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/celery/beat.py | python | Scheduler.__init__ | (self, app, schedule=None, max_interval=None,
Producer=None, lazy=False, sync_every_tasks=None, **kwargs) | [] | def __init__(self, app, schedule=None, max_interval=None,
Producer=None, lazy=False, sync_every_tasks=None, **kwargs):
self.app = app
self.data = maybe_evaluate({} if schedule is None else schedule)
self.max_interval = (max_interval or
app.conf.beat_max_loop_interval or
self.max_interval)
self.Producer = Producer or app.amqp.Producer
self._heap = None
self.sync_every_tasks = (
app.conf.beat_sync_every if sync_every_tasks is None
else sync_every_tasks)
if not lazy:
self.setup_schedule() | [
"def",
"__init__",
"(",
"self",
",",
"app",
",",
"schedule",
"=",
"None",
",",
"max_interval",
"=",
"None",
",",
"Producer",
"=",
"None",
",",
"lazy",
"=",
"False",
",",
"sync_every_tasks",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/beat.py#L191-L204 | ||||
dmlc/dgl | 8d14a739bc9e446d6c92ef83eafe5782398118de | python/dgl/_deprecate/frame.py | python | FrameRef.__contains__ | (self, name) | return name in self._frame | Return whether the column name exists. | Return whether the column name exists. | [
"Return",
"whether",
"the",
"column",
"name",
"exists",
"."
] | def __contains__(self, name):
"""Return whether the column name exists."""
return name in self._frame | [
"def",
"__contains__",
"(",
"self",
",",
"name",
")",
":",
"return",
"name",
"in",
"self",
".",
"_frame"
] | https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/_deprecate/frame.py#L630-L632 | |
smart-mobile-software/gitstack | d9fee8f414f202143eb6e620529e8e5539a2af56 | python/Lib/site-packages/django/contrib/sessions/backends/signed_cookies.py | python | SessionStore.delete | (self, session_key=None) | To delete, we clear the session key and the underlying data structure
and set the modified flag so that the cookie is set on the client for
the current request. | To delete, we clear the session key and the underlying data structure
and set the modified flag so that the cookie is set on the client for
the current request. | [
"To",
"delete",
"we",
"clear",
"the",
"session",
"key",
"and",
"the",
"underlying",
"data",
"structure",
"and",
"set",
"the",
"modified",
"flag",
"so",
"that",
"the",
"cookie",
"is",
"set",
"on",
"the",
"client",
"for",
"the",
"current",
"request",
"."
] | def delete(self, session_key=None):
"""
To delete, we clear the session key and the underlying data structure
and set the modified flag so that the cookie is set on the client for
the current request.
"""
self._session_key = ''
self._session_cache = {}
self.modified = True | [
"def",
"delete",
"(",
"self",
",",
"session_key",
"=",
"None",
")",
":",
"self",
".",
"_session_key",
"=",
"''",
"self",
".",
"_session_cache",
"=",
"{",
"}",
"self",
".",
"modified",
"=",
"True"
] | https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/contrib/sessions/backends/signed_cookies.py#L65-L73 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/tornado-6.0.1-py3.7-macosx-12.1-iPad6,7.egg/tornado/options.py | python | OptionParser.items | (self) | return [(opt.name, opt.value()) for name, opt in self._options.items()] | An iterable of (name, value) pairs.
.. versionadded:: 3.1 | An iterable of (name, value) pairs. | [
"An",
"iterable",
"of",
"(",
"name",
"value",
")",
"pairs",
"."
] | def items(self) -> Iterable[Tuple[str, Any]]:
"""An iterable of (name, value) pairs.
.. versionadded:: 3.1
"""
return [(opt.name, opt.value()) for name, opt in self._options.items()] | [
"def",
"items",
"(",
"self",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"[",
"(",
"opt",
".",
"name",
",",
"opt",
".",
"value",
"(",
")",
")",
"for",
"name",
",",
"opt",
"in",
"self",
".",
"_options",
... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/tornado-6.0.1-py3.7-macosx-12.1-iPad6,7.egg/tornado/options.py#L166-L171 | |
gwpy/gwpy | 82becd78d166a32985cb657a54d0d39f6a207739 | gwpy/utils/sphinx/ex2rst.py | python | create_parser | () | return parser | [] | def create_parser():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"infile",
type=Path,
metavar="example.py",
help="python file to convert",
)
parser.add_argument(
"outfile",
type=Path,
metavar="example.rst",
nargs="?",
help="rst file to write, default: print to screen",
)
return parser | [
"def",
"create_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"infile\"",
",",
"type",
"=",
"Path",
",",
"metavar",
"=",
"\"example.py\"",
",",
"help",
... | https://github.com/gwpy/gwpy/blob/82becd78d166a32985cb657a54d0d39f6a207739/gwpy/utils/sphinx/ex2rst.py#L143-L158 | |||
projectatomic/atomicapp | fba5cbb0a42b79418ac85ab93036a4404b92a431 | atomicapp/utils.py | python | Utils.getUserHome | () | return home | Finds the home directory of the user running the application.
If runnning within a container, the root dir must be passed as
a volume.
Ex. docker run -v /:/host -e SUDO_USER -e USER foobar | Finds the home directory of the user running the application.
If runnning within a container, the root dir must be passed as
a volume.
Ex. docker run -v /:/host -e SUDO_USER -e USER foobar | [
"Finds",
"the",
"home",
"directory",
"of",
"the",
"user",
"running",
"the",
"application",
".",
"If",
"runnning",
"within",
"a",
"container",
"the",
"root",
"dir",
"must",
"be",
"passed",
"as",
"a",
"volume",
".",
"Ex",
".",
"docker",
"run",
"-",
"v",
... | def getUserHome():
"""
Finds the home directory of the user running the application.
If runnning within a container, the root dir must be passed as
a volume.
Ex. docker run -v /:/host -e SUDO_USER -e USER foobar
"""
logger.debug("Finding the users home directory")
user = Utils.getUserName()
incontainer = Utils.inContainer()
# Check to see if we are running in a container. If we are we
# will chroot into the /host path before calling os.path.expanduser
if incontainer:
os.chroot(HOST_DIR)
# Call os.path.expanduser to determine the user's home dir.
# See https://docs.python.org/2/library/os.path.html#os.path.expanduser
# Warn if none is detected, don't error as not having a home
# dir doesn't mean we fail.
home = os.path.expanduser("~%s" % user)
if home == ("~%s" % user):
logger.error("No home directory exists for user %s" % user)
# Back out of chroot if necessary
if incontainer:
os.chroot("../..")
logger.debug("Running as user %s. Using home directory %s for configuration data"
% (user, home))
return home | [
"def",
"getUserHome",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"Finding the users home directory\"",
")",
"user",
"=",
"Utils",
".",
"getUserName",
"(",
")",
"incontainer",
"=",
"Utils",
".",
"inContainer",
"(",
")",
"# Check to see if we are running in a conta... | https://github.com/projectatomic/atomicapp/blob/fba5cbb0a42b79418ac85ab93036a4404b92a431/atomicapp/utils.py#L458-L488 | |
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/compat/_inspect.py | python | getargs | (co) | return args, varargs, varkw | Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None. | Get information about the arguments accepted by a code object. | [
"Get",
"information",
"about",
"the",
"arguments",
"accepted",
"by",
"a",
"code",
"object",
"."
] | def getargs(co):
"""Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None.
"""
if not iscode(co):
raise TypeError('arg is not a code object')
nargs = co.co_argcount
names = co.co_varnames
args = list(names[:nargs])
# The following acrobatics are for anonymous (tuple) arguments.
# Which we do not need to support, so remove to avoid importing
# the dis module.
for i in range(nargs):
if args[i][:1] in ['', '.']:
raise TypeError("tuple function arguments are not supported")
varargs = None
if co.co_flags & CO_VARARGS:
varargs = co.co_varnames[nargs]
nargs = nargs + 1
varkw = None
if co.co_flags & CO_VARKEYWORDS:
varkw = co.co_varnames[nargs]
return args, varargs, varkw | [
"def",
"getargs",
"(",
"co",
")",
":",
"if",
"not",
"iscode",
"(",
"co",
")",
":",
"raise",
"TypeError",
"(",
"'arg is not a code object'",
")",
"nargs",
"=",
"co",
".",
"co_argcount",
"names",
"=",
"co",
".",
"co_varnames",
"args",
"=",
"list",
"(",
"... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/compat/_inspect.py#L67-L96 | |
nosmokingbandit/Watcher3 | 0217e75158b563bdefc8e01c3be7620008cf3977 | core/searchresults.py | python | import_quality | () | return profile | Creates quality profile for imported releases
Creates import profile that mimics the base profile, but it incapable
of removing releases.
Returns dict | Creates quality profile for imported releases | [
"Creates",
"quality",
"profile",
"for",
"imported",
"releases"
] | def import_quality():
''' Creates quality profile for imported releases
Creates import profile that mimics the base profile, but it incapable
of removing releases.
Returns dict
'''
profile = core.config.base_profile
profile['ignoredwords'] = ''
profile['requiredwords'] = ''
for i in profile['Sources']:
profile['Sources'][i][0] = True
return profile | [
"def",
"import_quality",
"(",
")",
":",
"profile",
"=",
"core",
".",
"config",
".",
"base_profile",
"profile",
"[",
"'ignoredwords'",
"]",
"=",
"''",
"profile",
"[",
"'requiredwords'",
"]",
"=",
"''",
"for",
"i",
"in",
"profile",
"[",
"'Sources'",
"]",
"... | https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/core/searchresults.py#L419-L435 | |
Blueqat/Blueqat | b676f30489b71767419fd20503403d290d4950b5 | blueqat/circuit.py | python | _GateWrapper.__str__ | (self) | return self.op_type.lowername + args_str | [] | def __str__(self) -> str:
if self.params:
args_str = str(self.params)
else:
args_str = ""
if self.options:
args_str += str(self.options)
return self.op_type.lowername + args_str | [
"def",
"__str__",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"params",
":",
"args_str",
"=",
"str",
"(",
"self",
".",
"params",
")",
"else",
":",
"args_str",
"=",
"\"\"",
"if",
"self",
".",
"options",
":",
"args_str",
"+=",
"str",
"(",
... | https://github.com/Blueqat/Blueqat/blob/b676f30489b71767419fd20503403d290d4950b5/blueqat/circuit.py#L261-L268 | |||
xingyizhou/CenterNet | 2b7692c377c6686fb35e473dac2de6105eed62c6 | src/tools/voc_eval_lib/datasets/pascal_voc.py | python | pascal_voc.gt_roidb | (self) | return gt_roidb | Return the database of ground-truth regions of interest.
This function loads/saves from/to a cache file to speed up future calls. | Return the database of ground-truth regions of interest. | [
"Return",
"the",
"database",
"of",
"ground",
"-",
"truth",
"regions",
"of",
"interest",
"."
] | def gt_roidb(self):
"""
Return the database of ground-truth regions of interest.
This function loads/saves from/to a cache file to speed up future calls.
"""
cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl')
if os.path.exists(cache_file):
with open(cache_file, 'rb') as fid:
try:
roidb = pickle.load(fid)
except:
roidb = pickle.load(fid, encoding='bytes')
print('{} gt roidb loaded from {}'.format(self.name, cache_file))
return roidb
gt_roidb = [self._load_pascal_annotation(index)
for index in self.image_index]
with open(cache_file, 'wb') as fid:
pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL)
print('wrote gt roidb to {}'.format(cache_file))
return gt_roidb | [
"def",
"gt_roidb",
"(",
"self",
")",
":",
"cache_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_path",
",",
"self",
".",
"name",
"+",
"'_gt_roidb.pkl'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"cache_file",
")",
":",
... | https://github.com/xingyizhou/CenterNet/blob/2b7692c377c6686fb35e473dac2de6105eed62c6/src/tools/voc_eval_lib/datasets/pascal_voc.py#L98-L120 | |
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | redisdb/datadog_checks/redisdb/config_models/defaults.py | python | instance_min_collection_interval | (field, value) | return 15 | [] | def instance_min_collection_interval(field, value):
return 15 | [
"def",
"instance_min_collection_interval",
"(",
"field",
",",
"value",
")",
":",
"return",
"15"
] | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/redisdb/datadog_checks/redisdb/config_models/defaults.py#L45-L46 | |||
yaksok/yaksok | 73f14863d04f054eef2926f25a091f72f60352a5 | yaksok/yacc.py | python | p_logic_or_expr | (t) | logic_or_expr : logic_or_expr OR logic_and_expr
| logic_and_expr | logic_or_expr : logic_or_expr OR logic_and_expr
| logic_and_expr | [
"logic_or_expr",
":",
"logic_or_expr",
"OR",
"logic_and_expr",
"|",
"logic_and_expr"
] | def p_logic_or_expr(t):
'''logic_or_expr : logic_or_expr OR logic_and_expr
| logic_and_expr'''
if len(t) == 4:
if isinstance(t[1], ast.BoolOp) and isinstance(t[1].op, ast.Or):
t[0] = t[1]
t[0].values.append(t[3])
else:
or_ast = ast.Or()
or_ast.lineno = t.lineno(2)
or_ast.col_offset = -1 # XXX
t[0] = ast.BoolOp(or_ast, [t[1], t[3]])
t[0].lineno = t.lineno(2)
t[0].col_offset = -1 # XXX
else:
t[0] = t[1] | [
"def",
"p_logic_or_expr",
"(",
"t",
")",
":",
"if",
"len",
"(",
"t",
")",
"==",
"4",
":",
"if",
"isinstance",
"(",
"t",
"[",
"1",
"]",
",",
"ast",
".",
"BoolOp",
")",
"and",
"isinstance",
"(",
"t",
"[",
"1",
"]",
".",
"op",
",",
"ast",
".",
... | https://github.com/yaksok/yaksok/blob/73f14863d04f054eef2926f25a091f72f60352a5/yaksok/yacc.py#L475-L490 | ||
robhagemans/pcbasic | c3a043b46af66623a801e18a38175be077251ada | pcbasic/basic/machine.py | python | Memory.def_usr_ | (self, args) | DEF USR: Define machine language function. | DEF USR: Define machine language function. | [
"DEF",
"USR",
":",
"Define",
"machine",
"language",
"function",
"."
] | def def_usr_(self, args):
"""DEF USR: Define machine language function."""
usr, addr = args
addr = values.to_integer(addr, unsigned=True)
logging.warning('DEF USR statement not implemented') | [
"def",
"def_usr_",
"(",
"self",
",",
"args",
")",
":",
"usr",
",",
"addr",
"=",
"args",
"addr",
"=",
"values",
".",
"to_integer",
"(",
"addr",
",",
"unsigned",
"=",
"True",
")",
"logging",
".",
"warning",
"(",
"'DEF USR statement not implemented'",
")"
] | https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/basic/machine.py#L394-L398 | ||
tav/pylibs | 3c16b843681f54130ee6a022275289cadb2f2a69 | docutils/parsers/rst/directives/__init__.py | python | choice | (argument, values) | Directive option utility function, supplied to enable options whose
argument must be a member of a finite set of possible values (must be
lower case). A custom conversion function must be written to use it. For
example::
from docutils.parsers.rst import directives
def yesno(argument):
return directives.choice(argument, ('yes', 'no'))
Raise ``ValueError`` if no argument is found or if the argument's value is
not valid (not an entry in the supplied list). | Directive option utility function, supplied to enable options whose
argument must be a member of a finite set of possible values (must be
lower case). A custom conversion function must be written to use it. For
example:: | [
"Directive",
"option",
"utility",
"function",
"supplied",
"to",
"enable",
"options",
"whose",
"argument",
"must",
"be",
"a",
"member",
"of",
"a",
"finite",
"set",
"of",
"possible",
"values",
"(",
"must",
"be",
"lower",
"case",
")",
".",
"A",
"custom",
"con... | def choice(argument, values):
"""
Directive option utility function, supplied to enable options whose
argument must be a member of a finite set of possible values (must be
lower case). A custom conversion function must be written to use it. For
example::
from docutils.parsers.rst import directives
def yesno(argument):
return directives.choice(argument, ('yes', 'no'))
Raise ``ValueError`` if no argument is found or if the argument's value is
not valid (not an entry in the supplied list).
"""
try:
value = argument.lower().strip()
except AttributeError:
raise ValueError('must supply an argument; choose from %s'
% format_values(values))
if value in values:
return value
else:
raise ValueError('"%s" unknown; choose from %s'
% (argument, format_values(values))) | [
"def",
"choice",
"(",
"argument",
",",
"values",
")",
":",
"try",
":",
"value",
"=",
"argument",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"'must supply an argument; choose from %s'",
"%",
"f... | https://github.com/tav/pylibs/blob/3c16b843681f54130ee6a022275289cadb2f2a69/docutils/parsers/rst/directives/__init__.py#L367-L391 | ||
sdaps/sdaps | 51d1072185223f5e48512661e2c1e8399d63e876 | sdaps/gui/widget_buddies.py | python | QObject.make_heading | (self, title) | return vbox | [] | def make_heading(self, title):
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
vbox.set_margin_top(12)
hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
label = Gtk.Label()
label.set_markup('<b>%s %s</b>' % (self.obj.id_str(), markup_escape_text(title)))
label.set_halign(Gtk.Align.START)
label.show()
hbox.add(label)
image = Gtk.Image()
image.set_from_icon_name('document-edit-symbolic', Gtk.IconSize.BUTTON)
toggle = Gtk.ToggleButton(image=image)
toggle.set_halign(Gtk.Align.END)
toggle.set_margin_start(12)
hbox.add(toggle)
image.connect("button-press-event", lambda *args: print(pressed))
vbox.add(hbox)
self.review_frame = Gtk.Frame()
self.review_frame.set_margin_start(12)
self.review_textbox = Gtk.TextView()
self.review_textbox.show()
self.review_textbox.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
self.review_buffer = self.review_textbox.get_buffer()
self.review_buffer.connect('changed', self.review_buffer_changed_cb)
self.review_frame.add(self.review_textbox)
self.review_frame.hide()
self.review_frame.set_no_show_all(True)
vbox.add(self.review_frame)
toggle.bind_property("active",
self.review_frame, "visible",
GObject.BindingFlags.SYNC_CREATE | GObject.BindingFlags.BIDIRECTIONAL)
return vbox | [
"def",
"make_heading",
"(",
"self",
",",
"title",
")",
":",
"vbox",
"=",
"Gtk",
".",
"Box",
"(",
"orientation",
"=",
"Gtk",
".",
"Orientation",
".",
"VERTICAL",
")",
"vbox",
".",
"set_margin_top",
"(",
"12",
")",
"hbox",
"=",
"Gtk",
".",
"Box",
"(",
... | https://github.com/sdaps/sdaps/blob/51d1072185223f5e48512661e2c1e8399d63e876/sdaps/gui/widget_buddies.py#L163-L198 | |||
albertz/music-player | d23586f5bf657cbaea8147223be7814d117ae73d | src/Song.py | python | Song.userLongDescription | (self) | [] | def userLongDescription(self):
data = dict(self.metadata)
mainKeys = ["artist","title"]
for key in mainKeys:
data[key] = data.get(key, "").strip()
# TODO ...
data = sorted() | [
"def",
"userLongDescription",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
"self",
".",
"metadata",
")",
"mainKeys",
"=",
"[",
"\"artist\"",
",",
"\"title\"",
"]",
"for",
"key",
"in",
"mainKeys",
":",
"data",
"[",
"key",
"]",
"=",
"data",
".",
"g... | https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/src/Song.py#L253-L259 | ||||
Epistimio/orion | 732e739d99561020dbe620760acf062ade746006 | src/orion/storage/base.py | python | BaseStorageProtocol.retrieve_result | (self, trial, *args, **kwargs) | Fetch the result from a given medium (file, db, socket, etc..) for a given trial and
insert it into the trial object | Fetch the result from a given medium (file, db, socket, etc..) for a given trial and
insert it into the trial object | [
"Fetch",
"the",
"result",
"from",
"a",
"given",
"medium",
"(",
"file",
"db",
"socket",
"etc",
"..",
")",
"for",
"a",
"given",
"trial",
"and",
"insert",
"it",
"into",
"the",
"trial",
"object"
] | def retrieve_result(self, trial, *args, **kwargs):
"""Fetch the result from a given medium (file, db, socket, etc..) for a given trial and
insert it into the trial object
"""
raise NotImplementedError() | [
"def",
"retrieve_result",
"(",
"self",
",",
"trial",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/storage/base.py#L317-L321 | ||
aiidateam/aiida-core | c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2 | aiida/orm/nodes/node.py | python | Node.store | (self, with_transaction: bool = True) | return self | Store the node in the database while saving its attributes and repository directory.
After being called attributes cannot be changed anymore! Instead, extras can be changed only AFTER calling
this store() function.
:note: After successful storage, those links that are in the cache, and for which also the parent node is
already stored, will be automatically stored. The others will remain unstored.
:parameter with_transaction: if False, do not use a transaction because the caller will already have opened one. | Store the node in the database while saving its attributes and repository directory. | [
"Store",
"the",
"node",
"in",
"the",
"database",
"while",
"saving",
"its",
"attributes",
"and",
"repository",
"directory",
"."
] | def store(self, with_transaction: bool = True) -> 'Node': # pylint: disable=arguments-differ
"""Store the node in the database while saving its attributes and repository directory.
After being called attributes cannot be changed anymore! Instead, extras can be changed only AFTER calling
this store() function.
:note: After successful storage, those links that are in the cache, and for which also the parent node is
already stored, will be automatically stored. The others will remain unstored.
:parameter with_transaction: if False, do not use a transaction because the caller will already have opened one.
"""
from aiida.manage.caching import get_use_cache
if not self.is_stored:
# Call `validate_storability` directly and not in `_validate` in case sub class forgets to call the super.
self.validate_storability()
self._validate()
# Verify that parents are already stored. Raises if this is not the case.
self.verify_are_parents_stored()
# Determine whether the cache should be used for the process type of this node.
use_cache = get_use_cache(identifier=self.process_type)
# Clean the values on the backend node *before* computing the hash in `_get_same_node`. This will allow
# us to set `clean=False` if we are storing normally, since the values will already have been cleaned
self._backend_entity.clean_values()
# Retrieve the cached node.
same_node = self._get_same_node() if use_cache else None
if same_node is not None:
self._store_from_cache(same_node, with_transaction=with_transaction)
else:
self._store(with_transaction=with_transaction, clean=True)
# Set up autogrouping used by verdi run
if autogroup.CURRENT_AUTOGROUP is not None and autogroup.CURRENT_AUTOGROUP.is_to_be_grouped(self):
group = autogroup.CURRENT_AUTOGROUP.get_or_create_group()
group.add_nodes(self)
return self | [
"def",
"store",
"(",
"self",
",",
"with_transaction",
":",
"bool",
"=",
"True",
")",
"->",
"'Node'",
":",
"# pylint: disable=arguments-differ",
"from",
"aiida",
".",
"manage",
".",
"caching",
"import",
"get_use_cache",
"if",
"not",
"self",
".",
"is_stored",
":... | https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/nodes/node.py#L682-L724 | |
maoschanz/drawing | d4a69258570c7a120817484eaadac1145dedb62d | src/optionsbars/classic/optionsbar_color_popover.py | python | OptionsBarClassicColorPopover._update_nav_box | (self, *args) | Update the visibility of navigation controls ('back to the palette'
and 'always use this editor'). | Update the visibility of navigation controls ('back to the palette'
and 'always use this editor'). | [
"Update",
"the",
"visibility",
"of",
"navigation",
"controls",
"(",
"back",
"to",
"the",
"palette",
"and",
"always",
"use",
"this",
"editor",
")",
"."
] | def _update_nav_box(self, *args):
"""Update the visibility of navigation controls ('back to the palette'
and 'always use this editor')."""
self.editor_box.set_visible(self.color_widget.props.show_editor) | [
"def",
"_update_nav_box",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"editor_box",
".",
"set_visible",
"(",
"self",
".",
"color_widget",
".",
"props",
".",
"show_editor",
")"
] | https://github.com/maoschanz/drawing/blob/d4a69258570c7a120817484eaadac1145dedb62d/src/optionsbars/classic/optionsbar_color_popover.py#L255-L258 | ||
F8LEFT/DecLLVM | d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c | python/idaapi.py | python | write_tinfo_bitfield_value | (*args) | return _idaapi.write_tinfo_bitfield_value(*args) | write_tinfo_bitfield_value(typid, dst, v, bitoff) -> uint64 | write_tinfo_bitfield_value(typid, dst, v, bitoff) -> uint64 | [
"write_tinfo_bitfield_value",
"(",
"typid",
"dst",
"v",
"bitoff",
")",
"-",
">",
"uint64"
] | def write_tinfo_bitfield_value(*args):
"""
write_tinfo_bitfield_value(typid, dst, v, bitoff) -> uint64
"""
return _idaapi.write_tinfo_bitfield_value(*args) | [
"def",
"write_tinfo_bitfield_value",
"(",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"write_tinfo_bitfield_value",
"(",
"*",
"args",
")"
] | https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L29991-L29995 | |
tdryer/hangups | f0b37be1d46e71b30337227d7c46192cc726dcb4 | hangups/client.py | python | Client.remove_user | (self, remove_user_request) | return response | Remove a participant from a group conversation. | Remove a participant from a group conversation. | [
"Remove",
"a",
"participant",
"from",
"a",
"group",
"conversation",
"."
] | async def remove_user(self, remove_user_request):
"""Remove a participant from a group conversation."""
response = hangouts_pb2.RemoveUserResponse()
await self._pb_request('conversations/removeuser',
remove_user_request, response)
return response | [
"async",
"def",
"remove_user",
"(",
"self",
",",
"remove_user_request",
")",
":",
"response",
"=",
"hangouts_pb2",
".",
"RemoveUserResponse",
"(",
")",
"await",
"self",
".",
"_pb_request",
"(",
"'conversations/removeuser'",
",",
"remove_user_request",
",",
"response... | https://github.com/tdryer/hangups/blob/f0b37be1d46e71b30337227d7c46192cc726dcb4/hangups/client.py#L563-L568 | |
uqfoundation/multiprocess | 028cc73f02655e6451d92e5147d19d8c10aebe50 | py3.2/multiprocess/sharedctypes.py | python | Value | (typecode_or_type, *args, lock=None) | return synchronized(obj, lock) | Return a synchronization wrapper for a Value | Return a synchronization wrapper for a Value | [
"Return",
"a",
"synchronization",
"wrapper",
"for",
"a",
"Value"
] | def Value(typecode_or_type, *args, lock=None):
'''
Return a synchronization wrapper for a Value
'''
obj = RawValue(typecode_or_type, *args)
if lock is False:
return obj
if lock in (True, None):
lock = RLock()
if not hasattr(lock, 'acquire'):
raise AttributeError("'%r' has no method 'acquire'" % lock)
return synchronized(obj, lock) | [
"def",
"Value",
"(",
"typecode_or_type",
",",
"*",
"args",
",",
"lock",
"=",
"None",
")",
":",
"obj",
"=",
"RawValue",
"(",
"typecode_or_type",
",",
"*",
"args",
")",
"if",
"lock",
"is",
"False",
":",
"return",
"obj",
"if",
"lock",
"in",
"(",
"True",... | https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py3.2/multiprocess/sharedctypes.py#L92-L103 | |
click-contrib/click-completion | 5d665333536cf9f4ae1146729142aba53be9817d | click_completion/lib.py | python | double_quote | (s) | return '"' + s.replace('"', '"\'"\'"') + '"' | Escape a string with double quotes in order to be parsed as a single element by shlex
Parameters
----------
s : str
The string to quote
Returns
-------
str
The quoted string | Escape a string with double quotes in order to be parsed as a single element by shlex | [
"Escape",
"a",
"string",
"with",
"double",
"quotes",
"in",
"order",
"to",
"be",
"parsed",
"as",
"a",
"single",
"element",
"by",
"shlex"
] | def double_quote(s):
"""Escape a string with double quotes in order to be parsed as a single element by shlex
Parameters
----------
s : str
The string to quote
Returns
-------
str
The quoted string
"""
if not s:
return '""'
if find_unsafe(s) is None:
return s
# use double quotes, and put double quotes into single quotes
# the string $"b is then quoted as "$"'"'"b"
return '"' + s.replace('"', '"\'"\'"') + '"' | [
"def",
"double_quote",
"(",
"s",
")",
":",
"if",
"not",
"s",
":",
"return",
"'\"\"'",
"if",
"find_unsafe",
"(",
"s",
")",
"is",
"None",
":",
"return",
"s",
"# use double quotes, and put double quotes into single quotes",
"# the string $\"b is then quoted as \"$\"'\"'\"b... | https://github.com/click-contrib/click-completion/blob/5d665333536cf9f4ae1146729142aba53be9817d/click_completion/lib.py#L39-L59 | |
Perlence/PyGuitarPro | e599b1c1c483e16eb158affd3c7097c514e5642b | guitarpro/gp3.py | python | GP3File.toStrokeValue | (self, value) | Unpack stroke value.
Stroke value maps to:
- *1*: hundred twenty-eighth
- *2*: sixty-fourth
- *3*: thirty-second
- *4*: sixteenth
- *5*: eighth
- *6*: quarter | Unpack stroke value. | [
"Unpack",
"stroke",
"value",
"."
] | def toStrokeValue(self, value):
"""Unpack stroke value.
Stroke value maps to:
- *1*: hundred twenty-eighth
- *2*: sixty-fourth
- *3*: thirty-second
- *4*: sixteenth
- *5*: eighth
- *6*: quarter
"""
if value == 1:
return gp.Duration.hundredTwentyEighth
elif value == 2:
return gp.Duration.sixtyFourth
elif value == 3:
return gp.Duration.thirtySecond
elif value == 4:
return gp.Duration.sixteenth
elif value == 5:
return gp.Duration.eighth
elif value == 6:
return gp.Duration.quarter
else:
return gp.Duration.sixtyFourth | [
"def",
"toStrokeValue",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"1",
":",
"return",
"gp",
".",
"Duration",
".",
"hundredTwentyEighth",
"elif",
"value",
"==",
"2",
":",
"return",
"gp",
".",
"Duration",
".",
"sixtyFourth",
"elif",
"value"... | https://github.com/Perlence/PyGuitarPro/blob/e599b1c1c483e16eb158affd3c7097c514e5642b/guitarpro/gp3.py#L736-L761 | ||
karanchahal/distiller | a17ec06cbeafcdd2aea19d7c7663033c951392f5 | models/cifar10/vgg.py | python | VGG._make_layers | (self, cfg) | return nn.Sequential(*layers) | [] | def _make_layers(self, cfg):
layers = []
in_channels = 3
for x in cfg:
if x == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),
nn.BatchNorm2d(x),
nn.ReLU(inplace=True)]
in_channels = x
layers += [nn.AvgPool2d(kernel_size=1, stride=1)]
return nn.Sequential(*layers) | [
"def",
"_make_layers",
"(",
"self",
",",
"cfg",
")",
":",
"layers",
"=",
"[",
"]",
"in_channels",
"=",
"3",
"for",
"x",
"in",
"cfg",
":",
"if",
"x",
"==",
"'M'",
":",
"layers",
"+=",
"[",
"nn",
".",
"MaxPool2d",
"(",
"kernel_size",
"=",
"2",
",",... | https://github.com/karanchahal/distiller/blob/a17ec06cbeafcdd2aea19d7c7663033c951392f5/models/cifar10/vgg.py#L26-L38 | |||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/algebras/quatalg/quaternion_algebra.py | python | QuaternionFractionalIdeal_rational.multiply_by_conjugate | (self, J) | return R.ideal(basis, check=False) | Return product of self and the conjugate Jbar of `J`.
INPUT:
- ``J`` -- a quaternion ideal.
OUTPUT: a quaternionic fractional ideal.
EXAMPLES::
sage: R = BrandtModule(3,5).right_ideals()
sage: R[0].multiply_by_conjugate(R[1])
Fractional ideal (8 + 8*j + 112*k, 8*i + 16*j + 136*k, 32*j + 128*k, 160*k)
sage: R[0]*R[1].conjugate()
Fractional ideal (8 + 8*j + 112*k, 8*i + 16*j + 136*k, 32*j + 128*k, 160*k) | Return product of self and the conjugate Jbar of `J`. | [
"Return",
"product",
"of",
"self",
"and",
"the",
"conjugate",
"Jbar",
"of",
"J",
"."
] | def multiply_by_conjugate(self, J):
"""
Return product of self and the conjugate Jbar of `J`.
INPUT:
- ``J`` -- a quaternion ideal.
OUTPUT: a quaternionic fractional ideal.
EXAMPLES::
sage: R = BrandtModule(3,5).right_ideals()
sage: R[0].multiply_by_conjugate(R[1])
Fractional ideal (8 + 8*j + 112*k, 8*i + 16*j + 136*k, 32*j + 128*k, 160*k)
sage: R[0]*R[1].conjugate()
Fractional ideal (8 + 8*j + 112*k, 8*i + 16*j + 136*k, 32*j + 128*k, 160*k)
"""
Jbar = [b.conjugate() for b in J.basis()]
gens = [a * b for a in self.basis() for b in Jbar]
basis = tuple(basis_for_quaternion_lattice(gens))
R = self.quaternion_algebra()
return R.ideal(basis, check=False) | [
"def",
"multiply_by_conjugate",
"(",
"self",
",",
"J",
")",
":",
"Jbar",
"=",
"[",
"b",
".",
"conjugate",
"(",
")",
"for",
"b",
"in",
"J",
".",
"basis",
"(",
")",
"]",
"gens",
"=",
"[",
"a",
"*",
"b",
"for",
"a",
"in",
"self",
".",
"basis",
"... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/algebras/quatalg/quaternion_algebra.py#L2535-L2557 | |
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/future/backports/email/message.py | python | Message.__getitem__ | (self, name) | return self.get(name) | Get a header value.
Return None if the header is missing instead of raising an exception.
Note that if the header appeared multiple times, exactly which
occurrence gets returned is undefined. Use get_all() to get all
the values matching a header field name. | Get a header value. | [
"Get",
"a",
"header",
"value",
"."
] | def __getitem__(self, name):
"""Get a header value.
Return None if the header is missing instead of raising an exception.
Note that if the header appeared multiple times, exactly which
occurrence gets returned is undefined. Use get_all() to get all
the values matching a header field name.
"""
return self.get(name) | [
"def",
"__getitem__",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"get",
"(",
"name",
")"
] | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/future/backports/email/message.py#L337-L346 | |
IBM/lale | b4d6829c143a4735b06083a0e6c70d2cca244162 | lale/expressions.py | python | Expr.__ne__ | (self, other) | [] | def __ne__(self, other):
if isinstance(other, Expr):
comp = ast.Compare(
left=self._expr, ops=[ast.NotEq()], comparators=[other._expr]
)
return Expr(comp, istrue=self is other)
elif other is not None:
comp = ast.Compare(
left=self._expr,
ops=[ast.NotEq()],
comparators=[ast.Constant(value=other)],
)
return Expr(comp, istrue=False)
else:
return False | [
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Expr",
")",
":",
"comp",
"=",
"ast",
".",
"Compare",
"(",
"left",
"=",
"self",
".",
"_expr",
",",
"ops",
"=",
"[",
"ast",
".",
"NotEq",
"(",
")",
"]",... | https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/expressions.py#L189-L203 | ||||
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | pypy/module/__pypy__/interp_magic.py | python | newlist_hint | (space, sizehint) | return space.newlist_hint(sizehint) | Create a new empty list that has an underlying storage of length sizehint | Create a new empty list that has an underlying storage of length sizehint | [
"Create",
"a",
"new",
"empty",
"list",
"that",
"has",
"an",
"underlying",
"storage",
"of",
"length",
"sizehint"
] | def newlist_hint(space, sizehint):
""" Create a new empty list that has an underlying storage of length sizehint """
return space.newlist_hint(sizehint) | [
"def",
"newlist_hint",
"(",
"space",
",",
"sizehint",
")",
":",
"return",
"space",
".",
"newlist_hint",
"(",
"sizehint",
")"
] | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/module/__pypy__/interp_magic.py#L125-L127 | |
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/mutagen/asf/_objects.py | python | BaseObject.__init__ | (self) | [] | def __init__(self):
self.objects = []
self.data = b"" | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"objects",
"=",
"[",
"]",
"self",
".",
"data",
"=",
"b\"\""
] | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/mutagen/asf/_objects.py#L26-L28 | ||||
google/caliban | 56f96e7e05b1d33ebdebc01620dc867f7ec54df3 | caliban/config/experiment.py | python | _tupleize_compound_item | (k: Union[Tuple, str], v: Any) | converts a JSON-input compound key/value pair into a dictionary of tuples | converts a JSON-input compound key/value pair into a dictionary of tuples | [
"converts",
"a",
"JSON",
"-",
"input",
"compound",
"key",
"/",
"value",
"pair",
"into",
"a",
"dictionary",
"of",
"tuples"
] | def _tupleize_compound_item(k: Union[Tuple, str], v: Any) -> Dict:
""" converts a JSON-input compound key/value pair into a dictionary of tuples """
if _is_compound_key(k):
return {_tupleize_compound_key(k): _tupleize_compound_value(v)}
else:
return {k: v} | [
"def",
"_tupleize_compound_item",
"(",
"k",
":",
"Union",
"[",
"Tuple",
",",
"str",
"]",
",",
"v",
":",
"Any",
")",
"->",
"Dict",
":",
"if",
"_is_compound_key",
"(",
"k",
")",
":",
"return",
"{",
"_tupleize_compound_key",
"(",
"k",
")",
":",
"_tupleize... | https://github.com/google/caliban/blob/56f96e7e05b1d33ebdebc01620dc867f7ec54df3/caliban/config/experiment.py#L90-L95 | ||
nmcspadden/ProfileSigner | b591c51c1a5a8e47da322b0f1f1fa6fb1c8692db | profile_signer.py | python | writePlist | (dataObject, filepath) | Write 'rootObject' as a plist to filepath. | Write 'rootObject' as a plist to filepath. | [
"Write",
"rootObject",
"as",
"a",
"plist",
"to",
"filepath",
"."
] | def writePlist(dataObject, filepath):
'''
Write 'rootObject' as a plist to filepath.
'''
plistData, error = (
NSPropertyListSerialization.
dataFromPropertyList_format_errorDescription_(
dataObject, NSPropertyListXMLFormat_v1_0, None))
if plistData is None:
if error:
error = error.encode('ascii', 'ignore')
else:
error = "Unknown error"
raise NSPropertyListSerializationException(error)
else:
if plistData.writeToFile_atomically_(filepath, True):
return
else:
raise NSPropertyListWriteException(
"Failed to write plist data to %s" % filepath) | [
"def",
"writePlist",
"(",
"dataObject",
",",
"filepath",
")",
":",
"plistData",
",",
"error",
"=",
"(",
"NSPropertyListSerialization",
".",
"dataFromPropertyList_format_errorDescription_",
"(",
"dataObject",
",",
"NSPropertyListXMLFormat_v1_0",
",",
"None",
")",
")",
... | https://github.com/nmcspadden/ProfileSigner/blob/b591c51c1a5a8e47da322b0f1f1fa6fb1c8692db/profile_signer.py#L64-L83 | ||
ahmetcemturan/SFACT | 7576e29ba72b33e5058049b77b7b558875542747 | skeinforge_application/skeinforge_plugins/craft_plugins/hop.py | python | HopSkein.__init__ | (self) | Initialize | Initialize | [
"Initialize"
] | def __init__(self):
'Initialize'
self.distanceFeedRate = gcodec.DistanceFeedRate()
self.extruderActive = False
self.feedRateMinute = 961.0
self.hopHeight = 0.4
self.hopDistance = self.hopHeight
self.justDeactivated = False
self.layerCount = settings.LayerCount()
self.lineIndex = 0
self.lines = None
self.oldLocation = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"distanceFeedRate",
"=",
"gcodec",
".",
"DistanceFeedRate",
"(",
")",
"self",
".",
"extruderActive",
"=",
"False",
"self",
".",
"feedRateMinute",
"=",
"961.0",
"self",
".",
"hopHeight",
"=",
"0.4",
"se... | https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/skeinforge_application/skeinforge_plugins/craft_plugins/hop.py#L110-L121 | ||
crits/crits_services | c7abf91f1865d913cffad4b966599da204f8ae43 | pdf2txt_service/__init__.py | python | pdf2txtService.get_config_details | (config) | return {'pdf2txt_path': config['pdf2txt_path'],
'antiword_path': config['antiword_path']} | [] | def get_config_details(config):
return {'pdf2txt_path': config['pdf2txt_path'],
'antiword_path': config['antiword_path']} | [
"def",
"get_config_details",
"(",
"config",
")",
":",
"return",
"{",
"'pdf2txt_path'",
":",
"config",
"[",
"'pdf2txt_path'",
"]",
",",
"'antiword_path'",
":",
"config",
"[",
"'antiword_path'",
"]",
"}"
] | https://github.com/crits/crits_services/blob/c7abf91f1865d913cffad4b966599da204f8ae43/pdf2txt_service/__init__.py#L85-L87 | |||
hzlzh/AlfredWorkflow.com | 7055f14f6922c80ea5943839eb0caff11ae57255 | Sources/Workflows/SearchKippt/alp/request/requests/utils.py | python | to_key_val_list | (value) | return list(value) | Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
ValueError: cannot encode objects that are not 2-tuples. | Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g., | [
"Take",
"an",
"object",
"and",
"test",
"to",
"see",
"if",
"it",
"can",
"be",
"represented",
"as",
"a",
"dictionary",
".",
"If",
"it",
"can",
"be",
"return",
"a",
"list",
"of",
"tuples",
"e",
".",
"g",
"."
] | def to_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
ValueError: cannot encode objects that are not 2-tuples.
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
if isinstance(value, dict):
value = value.items()
return list(value) | [
"def",
"to_key_val_list",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"bytes",
",",
"bool",
",",
"int",
")",
")",
":",
"raise",
"ValueError",
"(",
"'cannot encode o... | https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/SearchKippt/alp/request/requests/utils.py#L118-L140 | |
rspivak/lsbasi | 07e1a14516156a21ebe2d82e0bae4bba5ad73dd6 | part17/spi.py | python | Lexer.advance | (self) | Advance the `pos` pointer and set the `current_char` variable. | Advance the `pos` pointer and set the `current_char` variable. | [
"Advance",
"the",
"pos",
"pointer",
"and",
"set",
"the",
"current_char",
"variable",
"."
] | def advance(self):
"""Advance the `pos` pointer and set the `current_char` variable."""
if self.current_char == '\n':
self.lineno += 1
self.column = 0
self.pos += 1
if self.pos > len(self.text) - 1:
self.current_char = None # Indicates end of input
else:
self.current_char = self.text[self.pos]
self.column += 1 | [
"def",
"advance",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_char",
"==",
"'\\n'",
":",
"self",
".",
"lineno",
"+=",
"1",
"self",
".",
"column",
"=",
"0",
"self",
".",
"pos",
"+=",
"1",
"if",
"self",
".",
"pos",
">",
"len",
"(",
"self",
... | https://github.com/rspivak/lsbasi/blob/07e1a14516156a21ebe2d82e0bae4bba5ad73dd6/part17/spi.py#L149-L160 | ||
veusz/veusz | 5a1e2af5f24df0eb2a2842be51f2997c4999c7fb | veusz/widgets/axis.py | python | AutoRange.adjustPlottedRange | (self, plottedrange, adjustmin, adjustmax, log, doc) | Adjust plotted range list given settings.
plottedrange: [minval, maxval]
adjustmin/adjustmax: bool whether to adjust
log: is log axis
doc: Document object | Adjust plotted range list given settings.
plottedrange: [minval, maxval]
adjustmin/adjustmax: bool whether to adjust
log: is log axis
doc: Document object | [
"Adjust",
"plotted",
"range",
"list",
"given",
"settings",
".",
"plottedrange",
":",
"[",
"minval",
"maxval",
"]",
"adjustmin",
"/",
"adjustmax",
":",
"bool",
"whether",
"to",
"adjust",
"log",
":",
"is",
"log",
"axis",
"doc",
":",
"Document",
"object"
] | def adjustPlottedRange(self, plottedrange, adjustmin, adjustmax, log, doc):
"""Adjust plotted range list given settings.
plottedrange: [minval, maxval]
adjustmin/adjustmax: bool whether to adjust
log: is log axis
doc: Document object
"""
rng = self.val
if rng == 'exact':
pass
elif rng == 'next-tick':
pass
else:
# get fractions to expand range by
expandfrac1, expandfrac2 = self.autoRangeToFracs(
rng, doc)
origrange = list(plottedrange)
if log:
# logarithmic
logrng = abs(
N.log(plottedrange[1]) - N.log(plottedrange[0]) )
if adjustmin:
plottedrange[0] /= N.exp(logrng * expandfrac1)
if adjustmax:
plottedrange[1] *= N.exp(logrng * expandfrac2)
else:
# linear
rng = plottedrange[1] - plottedrange[0]
if adjustmin:
plottedrange[0] -= rng*expandfrac1
if adjustmax:
plottedrange[1] += rng*expandfrac2
# if order is wrong, then give error!
if plottedrange[1] <= plottedrange[0]:
doc.log(_("Invalid axis range '%s'") % rng)
plottedrange[:] = origrange | [
"def",
"adjustPlottedRange",
"(",
"self",
",",
"plottedrange",
",",
"adjustmin",
",",
"adjustmax",
",",
"log",
",",
"doc",
")",
":",
"rng",
"=",
"self",
".",
"val",
"if",
"rng",
"==",
"'exact'",
":",
"pass",
"elif",
"rng",
"==",
"'next-tick'",
":",
"pa... | https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/widgets/axis.py#L288-L324 | ||
matplotlib/matplotlib | 8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322 | lib/mpl_toolkits/axes_grid1/axes_rgb.py | python | make_rgb_axes | (ax, pad=0.01, axes_class=None, **kwargs) | return ax_rgb | Parameters
----------
pad : float
Fraction of the axes height. | Parameters
----------
pad : float
Fraction of the axes height. | [
"Parameters",
"----------",
"pad",
":",
"float",
"Fraction",
"of",
"the",
"axes",
"height",
"."
] | def make_rgb_axes(ax, pad=0.01, axes_class=None, **kwargs):
"""
Parameters
----------
pad : float
Fraction of the axes height.
"""
divider = make_axes_locatable(ax)
pad_size = pad * Size.AxesY(ax)
xsize = ((1-2*pad)/3) * Size.AxesX(ax)
ysize = ((1-2*pad)/3) * Size.AxesY(ax)
divider.set_horizontal([Size.AxesX(ax), pad_size, xsize])
divider.set_vertical([ysize, pad_size, ysize, pad_size, ysize])
ax.set_axes_locator(divider.new_locator(0, 0, ny1=-1))
ax_rgb = []
if axes_class is None:
try:
axes_class = ax._axes_class
except AttributeError:
axes_class = type(ax)
for ny in [4, 2, 0]:
ax1 = axes_class(ax.get_figure(), ax.get_position(original=True),
sharex=ax, sharey=ax, **kwargs)
locator = divider.new_locator(nx=2, ny=ny)
ax1.set_axes_locator(locator)
for t in ax1.yaxis.get_ticklabels() + ax1.xaxis.get_ticklabels():
t.set_visible(False)
try:
for axis in ax1.axis.values():
axis.major_ticklabels.set_visible(False)
except AttributeError:
pass
ax_rgb.append(ax1)
fig = ax.get_figure()
for ax1 in ax_rgb:
fig.add_axes(ax1)
return ax_rgb | [
"def",
"make_rgb_axes",
"(",
"ax",
",",
"pad",
"=",
"0.01",
",",
"axes_class",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"divider",
"=",
"make_axes_locatable",
"(",
"ax",
")",
"pad_size",
"=",
"pad",
"*",
"Size",
".",
"AxesY",
"(",
"ax",
")",
... | https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/mpl_toolkits/axes_grid1/axes_rgb.py#L7-L53 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/ipykernel/datapub.py | python | publish_data | (data) | publish a data_message on the IOPub channel
Parameters
----------
data : dict
The data to be published. Think of it as a namespace. | publish a data_message on the IOPub channel | [
"publish",
"a",
"data_message",
"on",
"the",
"IOPub",
"channel"
] | def publish_data(data):
"""publish a data_message on the IOPub channel
Parameters
----------
data : dict
The data to be published. Think of it as a namespace.
"""
warnings.warn("ipykernel.datapub is deprecated. It has moved to ipyparallel.datapub", DeprecationWarning)
from ipykernel.zmqshell import ZMQInteractiveShell
ZMQInteractiveShell.instance().data_pub.publish_data(data) | [
"def",
"publish_data",
"(",
"data",
")",
":",
"warnings",
".",
"warn",
"(",
"\"ipykernel.datapub is deprecated. It has moved to ipyparallel.datapub\"",
",",
"DeprecationWarning",
")",
"from",
"ipykernel",
".",
"zmqshell",
"import",
"ZMQInteractiveShell",
"ZMQInteractiveShell"... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/ipykernel/datapub.py#L50-L62 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/physics/quantum/density.py | python | Density.doit | (self, **hints) | return Add(*terms) | Expand the density operator into an outer product format.
Examples
=========
>>> from sympy.physics.quantum.state import Ket
>>> from sympy.physics.quantum.density import Density
>>> from sympy.physics.quantum.operator import Operator
>>> A = Operator('A')
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
>>> d.doit()
0.5*|0><0| + 0.5*|1><1| | Expand the density operator into an outer product format. | [
"Expand",
"the",
"density",
"operator",
"into",
"an",
"outer",
"product",
"format",
"."
] | def doit(self, **hints):
"""Expand the density operator into an outer product format.
Examples
=========
>>> from sympy.physics.quantum.state import Ket
>>> from sympy.physics.quantum.density import Density
>>> from sympy.physics.quantum.operator import Operator
>>> A = Operator('A')
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
>>> d.doit()
0.5*|0><0| + 0.5*|1><1|
"""
terms = []
for (state, prob) in self.args:
state = state.expand() # needed to break up (a+b)*c
if (isinstance(state, Add)):
for arg in product(state.args, repeat=2):
terms.append(prob *
self._generate_outer_prod(arg[0], arg[1]))
else:
terms.append(prob *
self._generate_outer_prod(state, state))
return Add(*terms) | [
"def",
"doit",
"(",
"self",
",",
"*",
"*",
"hints",
")",
":",
"terms",
"=",
"[",
"]",
"for",
"(",
"state",
",",
"prob",
")",
"in",
"self",
".",
"args",
":",
"state",
"=",
"state",
".",
"expand",
"(",
")",
"# needed to break up (a+b)*c",
"if",
"(",
... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/physics/quantum/density.py#L149-L176 | |
bayespy/bayespy | 0e6e6130c888a4295cc9421d61d4ad27b2960ebb | bayespy/inference/vmp/vmp.py | python | VB.optimize | (self, *nodes, maxiter=10, verbose=True, method='fletcher-reeves',
riemannian=True, collapsed=None, tol=None) | Optimize nodes using Riemannian conjugate gradient | Optimize nodes using Riemannian conjugate gradient | [
"Optimize",
"nodes",
"using",
"Riemannian",
"conjugate",
"gradient"
] | def optimize(self, *nodes, maxiter=10, verbose=True, method='fletcher-reeves',
riemannian=True, collapsed=None, tol=None):
"""
Optimize nodes using Riemannian conjugate gradient
"""
method = method.lower()
if collapsed is None:
collapsed = []
scale = 1.0
p = self.get_parameters(*nodes)
dd_prev = 0
for i in range(maxiter):
t = time.time()
# Get gradients
if riemannian and method == 'gradient':
rg = self.get_gradients(*nodes, euclidian=False)
g1 = rg
g2 = rg
else:
(rg, g) = self.get_gradients(*nodes, euclidian=True)
if riemannian:
g1 = g
g2 = rg
else:
g1 = g
g2 = g
if method == 'gradient':
b = 0
elif method == 'fletcher-reeves':
dd_curr = self.dot(g1, g2)
if dd_prev == 0:
b = 0
else:
b = dd_curr / dd_prev
dd_prev = dd_curr
else:
raise Exception("Unknown optimization method: %s" % (method))
if b:
s = self.add(g2, s, scale=b)
else:
s = g2
success = False
while not success:
p_new = self.add(p, s, scale=scale)
try:
self.set_parameters(p_new, *nodes)
except:
if verbose:
self.print("CG update was unsuccessful, using gradient and resetting CG")
if s is g2:
scale = scale / 2
dd_prev = 0
s = g2
continue
# Update collapsed variables
collapsed_params = self.get_parameters(*collapsed)
try:
for node in collapsed:
self[node].update()
except:
self.set_parameters(collapsed_params, *collapsed)
if verbose:
self.print("Collapsed node update node failed, reset CG")
if s is g2:
scale = scale / 2
dd_prev = 0
s = g2
continue
L = self.compute_lowerbound()
bound_decreased = (
self.iter > 0 and
L < self.L[self.iter-1] and
not np.allclose(L, self.L[self.iter-1], rtol=1e-8)
)
if np.isnan(L) or bound_decreased:
# Restore the state of the collapsed nodes to what it was
# before updating them
self.set_parameters(collapsed_params, *collapsed)
if s is g2:
scale = scale / 2
if verbose:
self.print(
"Gradient ascent decreased lower bound from {0} to {1}, halfing step length"
.format(
self.L[self.iter-1],
L,
)
)
else:
if scale < 2 ** (-10):
if verbose:
self.print(
"CG decreased lower bound from {0} to {1}, reset CG."
.format(
self.L[self.iter-1],
L,
)
)
dd_prev = 0
s = g2
else:
scale = scale / 2
if verbose:
self.print(
"CG decreased lower bound from {0} to {1}, halfing step length"
.format(
self.L[self.iter-1],
L,
)
)
continue
success = True
scale = scale * np.sqrt(2)
p = p_new
cputime = time.time() - t
if self._end_iteration_step('OPT', cputime, tol=tol, verbose=verbose):
break | [
"def",
"optimize",
"(",
"self",
",",
"*",
"nodes",
",",
"maxiter",
"=",
"10",
",",
"verbose",
"=",
"True",
",",
"method",
"=",
"'fletcher-reeves'",
",",
"riemannian",
"=",
"True",
",",
"collapsed",
"=",
"None",
",",
"tol",
"=",
"None",
")",
":",
"met... | https://github.com/bayespy/bayespy/blob/0e6e6130c888a4295cc9421d61d4ad27b2960ebb/bayespy/inference/vmp/vmp.py#L477-L612 | ||
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/win32comext/axdebug/gateways.py | python | RemoteDebugApplicationEvents.OnLeaveBreakPoint | (self, rdat) | rdat -- PyIRemoteDebugApplicationThread | rdat -- PyIRemoteDebugApplicationThread | [
"rdat",
"--",
"PyIRemoteDebugApplicationThread"
] | def OnLeaveBreakPoint(self, rdat):
"""rdat -- PyIRemoteDebugApplicationThread
"""
RaiseNotImpl("OnLeaveBreakPoint") | [
"def",
"OnLeaveBreakPoint",
"(",
"self",
",",
"rdat",
")",
":",
"RaiseNotImpl",
"(",
"\"OnLeaveBreakPoint\"",
")"
] | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/win32comext/axdebug/gateways.py#L385-L388 | ||
alteryx/featuretools | d59e11082962f163540fd6e185901f65c506326a | docs/notebook_cleaner.py | python | _check_python_version | (notebook, default_version) | return True | [] | def _check_python_version(notebook, default_version):
with open(notebook, "r") as f:
source = json.load(f)
if source["metadata"]["language_info"]["version"] != default_version:
return False
return True | [
"def",
"_check_python_version",
"(",
"notebook",
",",
"default_version",
")",
":",
"with",
"open",
"(",
"notebook",
",",
"\"r\"",
")",
"as",
"f",
":",
"source",
"=",
"json",
".",
"load",
"(",
"f",
")",
"if",
"source",
"[",
"\"metadata\"",
"]",
"[",
"\"... | https://github.com/alteryx/featuretools/blob/d59e11082962f163540fd6e185901f65c506326a/docs/notebook_cleaner.py#L47-L52 | |||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/IPython/core/ultratb.py | python | getargs | (co) | return inspect.Arguments(args, varargs, varkw) | Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None. | Get information about the arguments accepted by a code object. | [
"Get",
"information",
"about",
"the",
"arguments",
"accepted",
"by",
"a",
"code",
"object",
"."
] | def getargs(co):
"""Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None."""
if not iscode(co):
raise TypeError('{!r} is not a code object'.format(co))
nargs = co.co_argcount
names = co.co_varnames
args = list(names[:nargs])
step = 0
# The following acrobatics are for anonymous (tuple) arguments.
for i in range(nargs):
if args[i][:1] in ('', '.'):
stack, remain, count = [], [], []
while step < len(co.co_code):
op = ord(co.co_code[step])
step = step + 1
if op >= dis.HAVE_ARGUMENT:
opname = dis.opname[op]
value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
step = step + 2
if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
remain.append(value)
count.append(value)
elif opname in ('STORE_FAST', 'STORE_DEREF'):
if op in dis.haslocal:
stack.append(co.co_varnames[value])
elif op in dis.hasfree:
stack.append((co.co_cellvars + co.co_freevars)[value])
# Special case for sublists of length 1: def foo((bar))
# doesn't generate the UNPACK_TUPLE bytecode, so if
# `remain` is empty here, we have such a sublist.
if not remain:
stack[0] = [stack[0]]
break
else:
remain[-1] = remain[-1] - 1
while remain[-1] == 0:
remain.pop()
size = count.pop()
stack[-size:] = [stack[-size:]]
if not remain:
break
remain[-1] = remain[-1] - 1
if not remain:
break
args[i] = stack[0]
varargs = None
if co.co_flags & inspect.CO_VARARGS:
varargs = co.co_varnames[nargs]
nargs = nargs + 1
varkw = None
if co.co_flags & inspect.CO_VARKEYWORDS:
varkw = co.co_varnames[nargs]
return inspect.Arguments(args, varargs, varkw) | [
"def",
"getargs",
"(",
"co",
")",
":",
"if",
"not",
"iscode",
"(",
"co",
")",
":",
"raise",
"TypeError",
"(",
"'{!r} is not a code object'",
".",
"format",
"(",
"co",
")",
")",
"nargs",
"=",
"co",
".",
"co_argcount",
"names",
"=",
"co",
".",
"co_varnam... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/IPython/core/ultratb.py#L238-L297 | |
randy3k/SendCode | 6775b40613bb4911ba0499ff8a600c41f48a62c2 | code_sender/winauto.py | python | enum_child_windows | (hwnd, callback) | [] | def enum_child_windows(hwnd, callback):
proc = EnumChildWindowsProc(callback)
EnumChildWindows(hwnd, proc, 0) | [
"def",
"enum_child_windows",
"(",
"hwnd",
",",
"callback",
")",
":",
"proc",
"=",
"EnumChildWindowsProc",
"(",
"callback",
")",
"EnumChildWindows",
"(",
"hwnd",
",",
"proc",
",",
"0",
")"
] | https://github.com/randy3k/SendCode/blob/6775b40613bb4911ba0499ff8a600c41f48a62c2/code_sender/winauto.py#L94-L96 | ||||
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | lib/cherrypy/__init__.py | python | _ThreadLocalProxy.__nonzero__ | (self) | return bool(child) | [] | def __nonzero__(self):
child = getattr(serving, self.__attrname__)
return bool(child) | [
"def",
"__nonzero__",
"(",
"self",
")",
":",
"child",
"=",
"getattr",
"(",
"serving",
",",
"self",
".",
"__attrname__",
")",
"return",
"bool",
"(",
"child",
")"
] | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/cherrypy/__init__.py#L264-L266 | |||
profusion/sgqlc | 465a5e800f8b408ceafe25cde45ee0bde4912482 | sgqlc/codegen/operation.py | python | Variable.__repr__ | (self) | return 'sgqlc.types.Variable(%r)' % (self.name,) | [] | def __repr__(self):
return 'sgqlc.types.Variable(%r)' % (self.name,) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'sgqlc.types.Variable(%r)'",
"%",
"(",
"self",
".",
"name",
",",
")"
] | https://github.com/profusion/sgqlc/blob/465a5e800f8b408ceafe25cde45ee0bde4912482/sgqlc/codegen/operation.py#L47-L48 | |||
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py | python | IPv6Address.is_link_local | (self) | return self in self._constants._linklocal_network | Test if the address is reserved for link-local.
Returns:
A boolean, True if the address is reserved per RFC 4291. | Test if the address is reserved for link-local. | [
"Test",
"if",
"the",
"address",
"is",
"reserved",
"for",
"link",
"-",
"local",
"."
] | def is_link_local(self):
"""Test if the address is reserved for link-local.
Returns:
A boolean, True if the address is reserved per RFC 4291.
"""
return self in self._constants._linklocal_network | [
"def",
"is_link_local",
"(",
"self",
")",
":",
"return",
"self",
"in",
"self",
".",
"_constants",
".",
"_linklocal_network"
] | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py#L2074-L2081 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | apps/beeswax/gen-py/hive_metastore/ThriftHiveMetastore.py | python | Iface.get_delegation_token | (self, token_owner, renewer_kerberos_principal_name) | Parameters:
- token_owner
- renewer_kerberos_principal_name | Parameters:
- token_owner
- renewer_kerberos_principal_name | [
"Parameters",
":",
"-",
"token_owner",
"-",
"renewer_kerberos_principal_name"
] | def get_delegation_token(self, token_owner, renewer_kerberos_principal_name):
"""
Parameters:
- token_owner
- renewer_kerberos_principal_name
"""
pass | [
"def",
"get_delegation_token",
"(",
"self",
",",
"token_owner",
",",
"renewer_kerberos_principal_name",
")",
":",
"pass"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/apps/beeswax/gen-py/hive_metastore/ThriftHiveMetastore.py#L1091-L1098 | ||
adamcaudill/EquationGroupLeak | 52fa871c89008566c27159bd48f2a8641260c984 | windows/fuzzbunch/pyreadline/modes/basemode.py | python | BaseMode.backward_delete_word | (self, e) | Delete the character behind the cursor. A numeric argument means
to kill the characters instead of deleting them. | Delete the character behind the cursor. A numeric argument means
to kill the characters instead of deleting them. | [
"Delete",
"the",
"character",
"behind",
"the",
"cursor",
".",
"A",
"numeric",
"argument",
"means",
"to",
"kill",
"the",
"characters",
"instead",
"of",
"deleting",
"them",
"."
] | def backward_delete_word(self, e): # (Control-Rubout)
'''Delete the character behind the cursor. A numeric argument means
to kill the characters instead of deleting them.'''
self.l_buffer.backward_delete_word(self.argument_reset) | [
"def",
"backward_delete_word",
"(",
"self",
",",
"e",
")",
":",
"# (Control-Rubout)",
"self",
".",
"l_buffer",
".",
"backward_delete_word",
"(",
"self",
".",
"argument_reset",
")"
] | https://github.com/adamcaudill/EquationGroupLeak/blob/52fa871c89008566c27159bd48f2a8641260c984/windows/fuzzbunch/pyreadline/modes/basemode.py#L358-L361 | ||
realpython/book2-exercises | cde325eac8e6d8cff2316601c2e5b36bb46af7d0 | web2py-rest/gluon/compileapp.py | python | LOAD | (c=None, f='index', args=None, vars=None,
extension=None, target=None, ajax=False, ajax_trap=False,
url=None, user_signature=False, timeout=None, times=1,
content='loading...', post_vars=Storage(), **attr) | LOADs a component into the action's document
Args:
c(str): controller
f(str): function
args(tuple or list): arguments
vars(dict): vars
extension(str): extension
target(str): id of the target
ajax(bool): True to enable AJAX bahaviour
ajax_trap(bool): True if `ajax` is set to `True`, traps
both links and forms "inside" the target
url(str): overrides `c`,`f`,`args` and `vars`
user_signature(bool): adds hmac signature to all links
with a key that is different for every user
timeout(int): in milliseconds, specifies the time to wait before
starting the request or the frequency if times is greater than
1 or "infinity"
times(integer or str): how many times the component will be requested
"infinity" or "continuous" are accepted to reload indefinitely the
component | LOADs a component into the action's document | [
"LOADs",
"a",
"component",
"into",
"the",
"action",
"s",
"document"
] | def LOAD(c=None, f='index', args=None, vars=None,
extension=None, target=None, ajax=False, ajax_trap=False,
url=None, user_signature=False, timeout=None, times=1,
content='loading...', post_vars=Storage(), **attr):
""" LOADs a component into the action's document
Args:
c(str): controller
f(str): function
args(tuple or list): arguments
vars(dict): vars
extension(str): extension
target(str): id of the target
ajax(bool): True to enable AJAX bahaviour
ajax_trap(bool): True if `ajax` is set to `True`, traps
both links and forms "inside" the target
url(str): overrides `c`,`f`,`args` and `vars`
user_signature(bool): adds hmac signature to all links
with a key that is different for every user
timeout(int): in milliseconds, specifies the time to wait before
starting the request or the frequency if times is greater than
1 or "infinity"
times(integer or str): how many times the component will be requested
"infinity" or "continuous" are accepted to reload indefinitely the
component
"""
from html import TAG, DIV, URL, SCRIPT, XML
if args is None:
args = []
vars = Storage(vars or {})
target = target or 'c' + str(random.random())[2:]
attr['_id'] = target
request = current.request
if '.' in f:
f, extension = f.rsplit('.', 1)
if url or ajax:
url = url or URL(request.application, c, f, r=request,
args=args, vars=vars, extension=extension,
user_signature=user_signature)
# timing options
if isinstance(times, basestring):
if times.upper() in ("INFINITY", "CONTINUOUS"):
times = "Infinity"
else:
raise TypeError("Unsupported times argument %s" % times)
elif isinstance(times, int):
if times <= 0:
raise ValueError("Times argument must be greater than zero, 'Infinity' or None")
else:
raise TypeError("Unsupported times argument type %s" % type(times))
if timeout is not None:
if not isinstance(timeout, (int, long)):
raise ValueError("Timeout argument must be an integer or None")
elif timeout <= 0:
raise ValueError(
"Timeout argument must be greater than zero or None")
statement = "$.web2py.component('%s','%s', %s, %s);" \
% (url, target, timeout, times)
attr['_data-w2p_timeout'] = timeout
attr['_data-w2p_times'] = times
else:
statement = "$.web2py.component('%s','%s');" % (url, target)
attr['_data-w2p_remote'] = url
if not target is None:
return DIV(content, **attr)
else:
if not isinstance(args, (list, tuple)):
args = [args]
c = c or request.controller
other_request = Storage(request)
other_request['env'] = Storage(request.env)
other_request.controller = c
other_request.function = f
other_request.extension = extension or request.extension
other_request.args = List(args)
other_request.vars = vars
other_request.get_vars = vars
other_request.post_vars = post_vars
other_response = Response()
other_request.env.path_info = '/' + \
'/'.join([request.application, c, f] +
map(str, other_request.args))
other_request.env.query_string = \
vars and URL(vars=vars).split('?')[1] or ''
other_request.env.http_web2py_component_location = \
request.env.path_info
other_request.cid = target
other_request.env.http_web2py_component_element = target
other_request.restful = types.MethodType(request.restful.im_func, other_request) # A bit nasty but needed to use LOAD on action decorates with @request.restful()
other_response.view = '%s/%s.%s' % (c, f, other_request.extension)
other_environment = copy.copy(current.globalenv) # NASTY
other_response._view_environment = other_environment
other_response.generic_patterns = \
copy.copy(current.response.generic_patterns)
other_environment['request'] = other_request
other_environment['response'] = other_response
## some magic here because current are thread-locals
original_request, current.request = current.request, other_request
original_response, current.response = current.response, other_response
page = run_controller_in(c, f, other_environment)
if isinstance(page, dict):
other_response._vars = page
other_response._view_environment.update(page)
run_view_in(other_response._view_environment)
page = other_response.body.getvalue()
current.request, current.response = original_request, original_response
js = None
if ajax_trap:
link = URL(request.application, c, f, r=request,
args=args, vars=vars, extension=extension,
user_signature=user_signature)
js = "$.web2py.trap_form('%s','%s');" % (link, target)
script = js and SCRIPT(js, _type="text/javascript") or ''
return TAG[''](DIV(XML(page), **attr), script) | [
"def",
"LOAD",
"(",
"c",
"=",
"None",
",",
"f",
"=",
"'index'",
",",
"args",
"=",
"None",
",",
"vars",
"=",
"None",
",",
"extension",
"=",
"None",
",",
"target",
"=",
"None",
",",
"ajax",
"=",
"False",
",",
"ajax_trap",
"=",
"False",
",",
"url",
... | https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py-rest/gluon/compileapp.py#L127-L245 | ||
ioflo/ioflo | 177ac656d7c4ff801aebb0d8b401db365a5248ce | ioflo/base/registering.py | python | Registrar.Retrieve | (cls, name = '') | return cls.Names.get(name, None) | Retrieves object in registry with name
return object with name or False if no object by name | Retrieves object in registry with name | [
"Retrieves",
"object",
"in",
"registry",
"with",
"name"
] | def Retrieve(cls, name = ''):
"""Retrieves object in registry with name
return object with name or False if no object by name
"""
return cls.Names.get(name, None) | [
"def",
"Retrieve",
"(",
"cls",
",",
"name",
"=",
"''",
")",
":",
"return",
"cls",
".",
"Names",
".",
"get",
"(",
"name",
",",
"None",
")"
] | https://github.com/ioflo/ioflo/blob/177ac656d7c4ff801aebb0d8b401db365a5248ce/ioflo/base/registering.py#L114-L119 | |
kellyjonbrazil/jc | e6900e2000bf265dfcfc09ffbfda39e9238661af | jc/parsers/tracepath.py | python | _process | (proc_data) | return proc_data | Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary) raw structured data to process
Returns:
Dictionary. Structured data to conform to the schema. | Final processing to conform to the schema. | [
"Final",
"processing",
"to",
"conform",
"to",
"the",
"schema",
"."
] | def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary) raw structured data to process
Returns:
Dictionary. Structured data to conform to the schema.
"""
# convert ints and floats
int_list = ['pmtu', 'forward_hops', 'return_hops', 'ttl', 'asymmetric_difference']
float_list = ['reply_ms']
for key in proc_data:
if key in int_list:
proc_data[key] = jc.utils.convert_to_int(proc_data[key])
if key in float_list:
proc_data[key] = jc.utils.convert_to_float(proc_data[key])
if 'hops' in proc_data:
for entry in proc_data['hops']:
for key in entry:
if key in int_list:
entry[key] = jc.utils.convert_to_int(entry[key])
if key in float_list:
entry[key] = jc.utils.convert_to_float(entry[key])
return proc_data | [
"def",
"_process",
"(",
"proc_data",
")",
":",
"# convert ints and floats",
"int_list",
"=",
"[",
"'pmtu'",
",",
"'forward_hops'",
",",
"'return_hops'",
",",
"'ttl'",
",",
"'asymmetric_difference'",
"]",
"float_list",
"=",
"[",
"'reply_ms'",
"]",
"for",
"key",
"... | https://github.com/kellyjonbrazil/jc/blob/e6900e2000bf265dfcfc09ffbfda39e9238661af/jc/parsers/tracepath.py#L148-L178 | |
psychopy/psychopy | 01b674094f38d0e0bd51c45a6f66f671d7041696 | psychopy/projects/pavlovia.py | python | PavloviaProject.commit | (self, message) | Commits the staged changes | Commits the staged changes | [
"Commits",
"the",
"staged",
"changes"
] | def commit(self, message):
"""Commits the staged changes"""
self.repo.git.commit('-m', message)
time.sleep(0.1)
# then get a new copy of the repo
self.repo = git.Repo(self.localRoot) | [
"def",
"commit",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"repo",
".",
"git",
".",
"commit",
"(",
"'-m'",
",",
"message",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"# then get a new copy of the repo",
"self",
".",
"repo",
"=",
"git",
".",
... | https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/projects/pavlovia.py#L968-L973 | ||
nicolargo/glances | 00c65933ae1d0ebd3e72dc30fc3c215a83dfaae2 | glances/plugins/glances_wifi.py | python | Plugin.update_views | (self) | Update stats views. | Update stats views. | [
"Update",
"stats",
"views",
"."
] | def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics information
# Alert on signal thresholds
for i in self.stats:
self.views[i[self.get_key()]]['signal']['decoration'] = self.get_alert(i['signal'])
self.views[i[self.get_key()]]['quality']['decoration'] = self.views[i[self.get_key()]]['signal'][
'decoration'
] | [
"def",
"update_views",
"(",
"self",
")",
":",
"# Call the father's method",
"super",
"(",
"Plugin",
",",
"self",
")",
".",
"update_views",
"(",
")",
"# Add specifics information",
"# Alert on signal thresholds",
"for",
"i",
"in",
"self",
".",
"stats",
":",
"self",... | https://github.com/nicolargo/glances/blob/00c65933ae1d0ebd3e72dc30fc3c215a83dfaae2/glances/plugins/glances_wifi.py#L153-L164 | ||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/mailbox.py | python | Mailbox.lock | (self) | Lock the mailbox. | Lock the mailbox. | [
"Lock",
"the",
"mailbox",
"."
] | def lock(self):
"""Lock the mailbox."""
raise NotImplementedError('Method must be implemented by subclass') | [
"def",
"lock",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Method must be implemented by subclass'",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/mailbox.py#L185-L187 | ||
eg4000/SKU110K_CVPR19 | 1fb83d6d0e5fd0fef8d53d25940ebd6f8d027020 | object_detector_retinanet/keras_retinanet/backend/tensorflow_backend.py | python | top_k | (*args, **kwargs) | return tensorflow.nn.top_k(*args, **kwargs) | See https://www.tensorflow.org/versions/master/api_docs/python/tf/nn/top_k . | See https://www.tensorflow.org/versions/master/api_docs/python/tf/nn/top_k . | [
"See",
"https",
":",
"//",
"www",
".",
"tensorflow",
".",
"org",
"/",
"versions",
"/",
"master",
"/",
"api_docs",
"/",
"python",
"/",
"tf",
"/",
"nn",
"/",
"top_k",
"."
] | def top_k(*args, **kwargs):
""" See https://www.tensorflow.org/versions/master/api_docs/python/tf/nn/top_k .
"""
return tensorflow.nn.top_k(*args, **kwargs) | [
"def",
"top_k",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"tensorflow",
".",
"nn",
".",
"top_k",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/eg4000/SKU110K_CVPR19/blob/1fb83d6d0e5fd0fef8d53d25940ebd6f8d027020/object_detector_retinanet/keras_retinanet/backend/tensorflow_backend.py#L32-L35 | |
airbnb/streamalert | 26cf1d08432ca285fd4f7410511a6198ca104bbb | streamalert/scheduled_queries/container/container.py | python | ServiceContainer.get_parameter | (self, parameter_name) | return self._parameters[parameter_name] | Returns a parameter registered in the service container | Returns a parameter registered in the service container | [
"Returns",
"a",
"parameter",
"registered",
"in",
"the",
"service",
"container"
] | def get_parameter(self, parameter_name):
"""Returns a parameter registered in the service container"""
if parameter_name not in self._parameters:
raise ValueError('ServiceContainer no such parameter: "{}"'.format(parameter_name))
return self._parameters[parameter_name] | [
"def",
"get_parameter",
"(",
"self",
",",
"parameter_name",
")",
":",
"if",
"parameter_name",
"not",
"in",
"self",
".",
"_parameters",
":",
"raise",
"ValueError",
"(",
"'ServiceContainer no such parameter: \"{}\"'",
".",
"format",
"(",
"parameter_name",
")",
")",
... | https://github.com/airbnb/streamalert/blob/26cf1d08432ca285fd4f7410511a6198ca104bbb/streamalert/scheduled_queries/container/container.py#L41-L46 | |
scipy/scipy | e0a749f01e79046642ccfdc419edbf9e7ca141ad | scipy/optimize/_optimize.py | python | golden | (func, args=(), brack=None, tol=_epsilon,
full_output=0, maxiter=5000) | Return the minimum of a function of one variable using golden section
method.
Given a function of one variable and a possible bracketing interval,
return the minimum of the function isolated to a fractional precision of
tol.
Parameters
----------
func : callable func(x,*args)
Objective function to minimize.
args : tuple, optional
Additional arguments (if present), passed to func.
brack : tuple, optional
Triple (a,b,c), where (a<b<c) and func(b) <
func(a),func(c). If bracket consists of two numbers (a,
c), then they are assumed to be a starting interval for a
downhill bracket search (see `bracket`); it doesn't always
mean that obtained solution will satisfy a<=x<=c.
tol : float, optional
x tolerance stop criterion
full_output : bool, optional
If True, return optional outputs.
maxiter : int
Maximum number of iterations to perform.
See also
--------
minimize_scalar: Interface to minimization algorithms for scalar
univariate functions. See the 'Golden' `method` in particular.
Notes
-----
Uses analog of bisection method to decrease the bracketed
interval.
Examples
--------
We illustrate the behaviour of the function when `brack` is of
size 2 and 3, respectively. In the case where `brack` is of the
form (xa,xb), we can see for the given values, the output need
not necessarily lie in the range ``(xa, xb)``.
>>> def f(x):
... return x**2
>>> from scipy import optimize
>>> minimum = optimize.golden(f, brack=(1, 2))
>>> minimum
1.5717277788484873e-162
>>> minimum = optimize.golden(f, brack=(-1, 0.5, 2))
>>> minimum
-1.5717277788484873e-162 | Return the minimum of a function of one variable using golden section
method. | [
"Return",
"the",
"minimum",
"of",
"a",
"function",
"of",
"one",
"variable",
"using",
"golden",
"section",
"method",
"."
] | def golden(func, args=(), brack=None, tol=_epsilon,
full_output=0, maxiter=5000):
"""
Return the minimum of a function of one variable using golden section
method.
Given a function of one variable and a possible bracketing interval,
return the minimum of the function isolated to a fractional precision of
tol.
Parameters
----------
func : callable func(x,*args)
Objective function to minimize.
args : tuple, optional
Additional arguments (if present), passed to func.
brack : tuple, optional
Triple (a,b,c), where (a<b<c) and func(b) <
func(a),func(c). If bracket consists of two numbers (a,
c), then they are assumed to be a starting interval for a
downhill bracket search (see `bracket`); it doesn't always
mean that obtained solution will satisfy a<=x<=c.
tol : float, optional
x tolerance stop criterion
full_output : bool, optional
If True, return optional outputs.
maxiter : int
Maximum number of iterations to perform.
See also
--------
minimize_scalar: Interface to minimization algorithms for scalar
univariate functions. See the 'Golden' `method` in particular.
Notes
-----
Uses analog of bisection method to decrease the bracketed
interval.
Examples
--------
We illustrate the behaviour of the function when `brack` is of
size 2 and 3, respectively. In the case where `brack` is of the
form (xa,xb), we can see for the given values, the output need
not necessarily lie in the range ``(xa, xb)``.
>>> def f(x):
... return x**2
>>> from scipy import optimize
>>> minimum = optimize.golden(f, brack=(1, 2))
>>> minimum
1.5717277788484873e-162
>>> minimum = optimize.golden(f, brack=(-1, 0.5, 2))
>>> minimum
-1.5717277788484873e-162
"""
options = {'xtol': tol, 'maxiter': maxiter}
res = _minimize_scalar_golden(func, brack, args, **options)
if full_output:
return res['x'], res['fun'], res['nfev']
else:
return res['x'] | [
"def",
"golden",
"(",
"func",
",",
"args",
"=",
"(",
")",
",",
"brack",
"=",
"None",
",",
"tol",
"=",
"_epsilon",
",",
"full_output",
"=",
"0",
",",
"maxiter",
"=",
"5000",
")",
":",
"options",
"=",
"{",
"'xtol'",
":",
"tol",
",",
"'maxiter'",
":... | https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/optimize/_optimize.py#L2533-L2597 | ||
Nuitka/Nuitka | 39262276993757fa4e299f497654065600453fc9 | nuitka/build/inline_copy/lib/scons-3.1.2/SCons/Tool/applelink.py | python | _applelib_versioned_lib_soname | (env, libnode, version, prefix, suffix, name_func) | return soname | For libnode='/optional/dir/libfoo.X.Y.Z.dylib' it returns 'libfoo.X.dylib | For libnode='/optional/dir/libfoo.X.Y.Z.dylib' it returns 'libfoo.X.dylib | [
"For",
"libnode",
"=",
"/",
"optional",
"/",
"dir",
"/",
"libfoo",
".",
"X",
".",
"Y",
".",
"Z",
".",
"dylib",
"it",
"returns",
"libfoo",
".",
"X",
".",
"dylib"
] | def _applelib_versioned_lib_soname(env, libnode, version, prefix, suffix, name_func):
"""For libnode='/optional/dir/libfoo.X.Y.Z.dylib' it returns 'libfoo.X.dylib'"""
Verbose = False
if Verbose:
print("_applelib_versioned_lib_soname: version={!r}".format(version))
name = name_func(env, libnode, version, prefix, suffix)
if Verbose:
print("_applelib_versioned_lib_soname: name={!r}".format(name))
major = version.split('.')[0]
(libname,_suffix) = name.split('.')
soname = '.'.join([libname, major, _suffix])
if Verbose:
print("_applelib_versioned_lib_soname: soname={!r}".format(soname))
return soname | [
"def",
"_applelib_versioned_lib_soname",
"(",
"env",
",",
"libnode",
",",
"version",
",",
"prefix",
",",
"suffix",
",",
"name_func",
")",
":",
"Verbose",
"=",
"False",
"if",
"Verbose",
":",
"print",
"(",
"\"_applelib_versioned_lib_soname: version={!r}\"",
".",
"fo... | https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-3.1.2/SCons/Tool/applelink.py#L63-L76 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/rings/asymptotic/growth_group.py | python | MonomialGrowthElement.__pow__ | (self, exponent) | return self.parent()._create_element_in_extension_(
self.exponent * strip_symbolic(exponent)) | r"""
Calculate the power of this growth element to the given ``exponent``.
INPUT:
- ``exponent`` -- a number. This can be anything that is a
valid right hand side of ``*`` with elements of the
parent's base.
OUTPUT:
The result of this exponentiation, a :class:`MonomialGrowthElement`.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: P = GrowthGroup('x^ZZ')
sage: x = P.gen()
sage: a = x^7; a
x^7
sage: a^(1/2)
x^(7/2)
sage: (a^(1/2)).parent()
Growth Group x^QQ
sage: a^(1/7)
x
sage: (a^(1/7)).parent()
Growth Group x^QQ
sage: P = GrowthGroup('x^QQ')
sage: b = P.gen()^(7/2); b
x^(7/2)
sage: b^12
x^42 | r"""
Calculate the power of this growth element to the given ``exponent``. | [
"r",
"Calculate",
"the",
"power",
"of",
"this",
"growth",
"element",
"to",
"the",
"given",
"exponent",
"."
] | def __pow__(self, exponent):
r"""
Calculate the power of this growth element to the given ``exponent``.
INPUT:
- ``exponent`` -- a number. This can be anything that is a
valid right hand side of ``*`` with elements of the
parent's base.
OUTPUT:
The result of this exponentiation, a :class:`MonomialGrowthElement`.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: P = GrowthGroup('x^ZZ')
sage: x = P.gen()
sage: a = x^7; a
x^7
sage: a^(1/2)
x^(7/2)
sage: (a^(1/2)).parent()
Growth Group x^QQ
sage: a^(1/7)
x
sage: (a^(1/7)).parent()
Growth Group x^QQ
sage: P = GrowthGroup('x^QQ')
sage: b = P.gen()^(7/2); b
x^(7/2)
sage: b^12
x^42
"""
from .misc import strip_symbolic
return self.parent()._create_element_in_extension_(
self.exponent * strip_symbolic(exponent)) | [
"def",
"__pow__",
"(",
"self",
",",
"exponent",
")",
":",
"from",
".",
"misc",
"import",
"strip_symbolic",
"return",
"self",
".",
"parent",
"(",
")",
".",
"_create_element_in_extension_",
"(",
"self",
".",
"exponent",
"*",
"strip_symbolic",
"(",
"exponent",
... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/asymptotic/growth_group.py#L3039-L3076 | |
vaexio/vaex | 6c1571f4f1ac030eb7128c1b35b2ccbb5dd29cac | packages/vaex-core/vaex/column.py | python | ColumnIndexed.index | (column, indices, direct_indices_map=None, masked=False) | Creates a new column indexed by indices which avoids nested indices
:param df: Dataframe where column comes from
:param column: Column object or numpy array
:param name: name of column
:param indices: ndarray with indices which rows to take
:param direct_indices_map: cache of the nested indices (pass a dict for better performance), defaults to None
:return: A column object which avoids two levels of indirection
:rtype: ColumnIndexed | Creates a new column indexed by indices which avoids nested indices | [
"Creates",
"a",
"new",
"column",
"indexed",
"by",
"indices",
"which",
"avoids",
"nested",
"indices"
] | def index(column, indices, direct_indices_map=None, masked=False):
"""Creates a new column indexed by indices which avoids nested indices
:param df: Dataframe where column comes from
:param column: Column object or numpy array
:param name: name of column
:param indices: ndarray with indices which rows to take
:param direct_indices_map: cache of the nested indices (pass a dict for better performance), defaults to None
:return: A column object which avoids two levels of indirection
:rtype: ColumnIndexed
"""
direct_indices_map = direct_indices_map if direct_indices_map is not None else {}
if isinstance(column, ColumnIndexed):
if id(column.indices) not in direct_indices_map:
direct_indices = column.indices[indices]
if masked:
# restored sentinel mask values
direct_indices[indices == -1] = -1
direct_indices_map[id(column.indices)] = direct_indices
else:
direct_indices = direct_indices_map[id(column.indices)]
return ColumnIndexed(column.column, direct_indices, masked=masked or column.masked)
else:
return ColumnIndexed(column, indices, masked=masked) | [
"def",
"index",
"(",
"column",
",",
"indices",
",",
"direct_indices_map",
"=",
"None",
",",
"masked",
"=",
"False",
")",
":",
"direct_indices_map",
"=",
"direct_indices_map",
"if",
"direct_indices_map",
"is",
"not",
"None",
"else",
"{",
"}",
"if",
"isinstance"... | https://github.com/vaexio/vaex/blob/6c1571f4f1ac030eb7128c1b35b2ccbb5dd29cac/packages/vaex-core/vaex/column.py#L302-L325 | ||
nschaetti/EchoTorch | cba209c49e0fda73172d2e853b85c747f9f5117e | echotorch/data/datasets/EchoDataset.py | python | EchoDataset.data | (self) | Get the whole dataset (according to init parameters)
@return: The Torch Tensor | Get the whole dataset (according to init parameters) | [
"Get",
"the",
"whole",
"dataset",
"(",
"according",
"to",
"init",
"parameters",
")"
] | def data(self) -> Union[torch.Tensor, List]:
"""
Get the whole dataset (according to init parameters)
@return: The Torch Tensor
"""
raise Exception("data not implemented") | [
"def",
"data",
"(",
"self",
")",
"->",
"Union",
"[",
"torch",
".",
"Tensor",
",",
"List",
"]",
":",
"raise",
"Exception",
"(",
"\"data not implemented\"",
")"
] | https://github.com/nschaetti/EchoTorch/blob/cba209c49e0fda73172d2e853b85c747f9f5117e/echotorch/data/datasets/EchoDataset.py#L87-L92 | ||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/site-packages/Crypto/Cipher/blockalgo.py | python | BlockAlgo.decrypt | (self, ciphertext) | return self._cipher.decrypt(ciphertext) | Decrypt data with the key and the parameters set at initialization.
The cipher object is stateful; decryption of a long block
of data can be broken up in two or more calls to `decrypt()`.
That is, the statement:
>>> c.decrypt(a) + c.decrypt(b)
is always equivalent to:
>>> c.decrypt(a+b)
That also means that you cannot reuse an object for encrypting
or decrypting other data with the same key.
This function does not perform any padding.
- For `MODE_ECB`, `MODE_CBC`, and `MODE_OFB`, *ciphertext* length
(in bytes) must be a multiple of *block_size*.
- For `MODE_CFB`, *ciphertext* length (in bytes) must be a multiple
of *segment_size*/8.
- For `MODE_CTR`, *ciphertext* can be of any length.
- For `MODE_OPENPGP`, *plaintext* must be a multiple of *block_size*,
unless it is the last chunk of the message.
:Parameters:
ciphertext : byte string
The piece of data to decrypt.
:Return: the decrypted data (byte string, as long as *ciphertext*). | Decrypt data with the key and the parameters set at initialization.
The cipher object is stateful; decryption of a long block
of data can be broken up in two or more calls to `decrypt()`.
That is, the statement:
>>> c.decrypt(a) + c.decrypt(b) | [
"Decrypt",
"data",
"with",
"the",
"key",
"and",
"the",
"parameters",
"set",
"at",
"initialization",
".",
"The",
"cipher",
"object",
"is",
"stateful",
";",
"decryption",
"of",
"a",
"long",
"block",
"of",
"data",
"can",
"be",
"broken",
"up",
"in",
"two",
"... | def decrypt(self, ciphertext):
"""Decrypt data with the key and the parameters set at initialization.
The cipher object is stateful; decryption of a long block
of data can be broken up in two or more calls to `decrypt()`.
That is, the statement:
>>> c.decrypt(a) + c.decrypt(b)
is always equivalent to:
>>> c.decrypt(a+b)
That also means that you cannot reuse an object for encrypting
or decrypting other data with the same key.
This function does not perform any padding.
- For `MODE_ECB`, `MODE_CBC`, and `MODE_OFB`, *ciphertext* length
(in bytes) must be a multiple of *block_size*.
- For `MODE_CFB`, *ciphertext* length (in bytes) must be a multiple
of *segment_size*/8.
- For `MODE_CTR`, *ciphertext* can be of any length.
- For `MODE_OPENPGP`, *plaintext* must be a multiple of *block_size*,
unless it is the last chunk of the message.
:Parameters:
ciphertext : byte string
The piece of data to decrypt.
:Return: the decrypted data (byte string, as long as *ciphertext*).
"""
if self.mode == MODE_OPENPGP:
padding_length = (self.block_size - len(ciphertext) % self.block_size) % self.block_size
if padding_length>0:
# CFB mode requires ciphertext to have length multiple of block size,
# but PGP mode allows the last block to be shorter
if self._done_last_block:
raise ValueError("Only the last chunk is allowed to have length not multiple of %d bytes",
self.block_size)
self._done_last_block = True
padded = ciphertext + b('\x00')*padding_length
res = self._cipher.decrypt(padded)[:len(ciphertext)]
else:
res = self._cipher.decrypt(ciphertext)
return res
return self._cipher.decrypt(ciphertext) | [
"def",
"decrypt",
"(",
"self",
",",
"ciphertext",
")",
":",
"if",
"self",
".",
"mode",
"==",
"MODE_OPENPGP",
":",
"padding_length",
"=",
"(",
"self",
".",
"block_size",
"-",
"len",
"(",
"ciphertext",
")",
"%",
"self",
".",
"block_size",
")",
"%",
"self... | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/site-packages/Crypto/Cipher/blockalgo.py#L246-L295 | |
ym2011/POC-EXP | 206b22d3a6b2a172359678df33bbc5b2ad04b6c3 | Joomla/batch detection/hackUtils-master/bs4/element.py | python | Tag.__setitem__ | (self, key, value) | Setting tag[key] sets the value of the 'key' attribute for the
tag. | Setting tag[key] sets the value of the 'key' attribute for the
tag. | [
"Setting",
"tag",
"[",
"key",
"]",
"sets",
"the",
"value",
"of",
"the",
"key",
"attribute",
"for",
"the",
"tag",
"."
] | def __setitem__(self, key, value):
"""Setting tag[key] sets the value of the 'key' attribute for the
tag."""
self.attrs[key] = value | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"attrs",
"[",
"key",
"]",
"=",
"value"
] | https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/Joomla/batch detection/hackUtils-master/bs4/element.py#L922-L925 | ||
Azure/azure-cli | 6c1b085a0910c6c2139006fcbd8ade44006eb6dd | tools/automation/verify/verify_module_load_times.py | python | mean | (data) | return sum(data)/float(n) | Return the sample arithmetic mean of data. | Return the sample arithmetic mean of data. | [
"Return",
"the",
"sample",
"arithmetic",
"mean",
"of",
"data",
"."
] | def mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('len < 1')
return sum(data)/float(n) | [
"def",
"mean",
"(",
"data",
")",
":",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'len < 1'",
")",
"return",
"sum",
"(",
"data",
")",
"/",
"float",
"(",
"n",
")"
] | https://github.com/Azure/azure-cli/blob/6c1b085a0910c6c2139006fcbd8ade44006eb6dd/tools/automation/verify/verify_module_load_times.py#L30-L35 | |
i3visio/osrframework | e02a6e9b1346ab5a01244c0d19bcec8232bf1a37 | osrframework/thirdparties/pipl_com/checkInfo.py | python | checkInfo | (email=None, username=None, api_key=None) | return results | Method that checks if the given hash is stored in the pipl.com website.
:param email: queries to be launched.
:param api_key: api_key to be used in pipl.com. If not provided, the API key will be searched in the config_api_keys.py file.
:return: Python structure for the Json received. It has the following structure: | Method that checks if the given hash is stored in the pipl.com website. | [
"Method",
"that",
"checks",
"if",
"the",
"given",
"hash",
"is",
"stored",
"in",
"the",
"pipl",
".",
"com",
"website",
"."
] | def checkInfo(email=None, username=None, api_key=None):
'''
Method that checks if the given hash is stored in the pipl.com website.
:param email: queries to be launched.
:param api_key: api_key to be used in pipl.com. If not provided, the API key will be searched in the config_api_keys.py file.
:return: Python structure for the Json received. It has the following structure:
'''
# This is for i3visio
if api_key is None:
#api_key = raw_input("Insert the API KEY here:\t")
allKeys = config_api_keys.returnListOfAPIKeys()
try:
api_key = allKeys["pipl_com"]
except:
# API_Key not found. The samplekey will be used but it has a limit of 10 queries/day.
api_key = "samplekey"
results = {}
results["person"] = []
results["records"] = []
if username != None:
request = SearchAPIRequest( username=username, api_key=api_key)
person, records = launchRequest(request)
# Appending the results
results["person"].append(person)
results["records"].append(records)
if email != None:
request = SearchAPIRequest( email=email, api_key=api_key)
person, records = launchRequest(request)
# Appending the results
results["person"].append(person)
results["records"].append(records)
return results | [
"def",
"checkInfo",
"(",
"email",
"=",
"None",
",",
"username",
"=",
"None",
",",
"api_key",
"=",
"None",
")",
":",
"# This is for i3visio",
"if",
"api_key",
"is",
"None",
":",
"#api_key = raw_input(\"Insert the API KEY here:\\t\")",
"allKeys",
"=",
"config_api_keys... | https://github.com/i3visio/osrframework/blob/e02a6e9b1346ab5a01244c0d19bcec8232bf1a37/osrframework/thirdparties/pipl_com/checkInfo.py#L30-L65 | |
spender-sandbox/cuckoo-modified | eb93ef3d41b8fee51b4330306dcd315d8101e021 | modules/machinery/vsphere.py | python | vSphere._initialize_check | (self) | Runs checks against virtualization software when a machine manager
is initialized.
@raise CuckooCriticalError: if a misconfiguration or unsupported state
is found. | Runs checks against virtualization software when a machine manager
is initialized. | [
"Runs",
"checks",
"against",
"virtualization",
"software",
"when",
"a",
"machine",
"manager",
"is",
"initialized",
"."
] | def _initialize_check(self):
"""Runs checks against virtualization software when a machine manager
is initialized.
@raise CuckooCriticalError: if a misconfiguration or unsupported state
is found.
"""
self.connect_opts = {}
if self.options.vsphere.host:
self.connect_opts["host"] = self.options.vsphere.host
else:
raise CuckooCriticalError("vSphere host address setting not found, "
"please add it to the config file.")
if self.options.vsphere.port:
self.connect_opts["port"] = self.options.vsphere.port
else:
raise CuckooCriticalError("vSphere port setting not found, "
"please add it to the config file.")
if self.options.vsphere.user:
self.connect_opts["user"] = self.options.vsphere.user
else:
raise CuckooCriticalError("vSphere username setting not found, "
"please add it to the config file.")
if self.options.vsphere.pwd:
self.connect_opts["pwd"] = self.options.vsphere.pwd
else:
raise CuckooCriticalError("vSphere password setting not found, "
"please add it to the config file.")
# Workaround for PEP-0476 issues in recent Python versions
if self.options.vsphere.unverified_ssl:
import ssl
sslContext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
sslContext.verify_mode = ssl.CERT_NONE
self.connect_opts["sslContext"] = sslContext
log.warn("Turning off SSL certificate verification!")
# Check that a snapshot is configured for each machine
# and that it was taken in a powered-on state
try:
with SmartConnection(**self.connect_opts) as conn:
for machine in self.machines():
if not machine.snapshot:
raise CuckooCriticalError("Snapshot name not specified "
"for machine {0}, please add "
"it to the config file."
.format(machine.label))
vm = self._get_virtual_machine_by_label(conn, machine.label)
if not vm:
raise CuckooCriticalError("Unable to find machine {0} "
"on vSphere host, please "
"update your configuration."
.format(machine.label))
state = self._get_snapshot_power_state(vm, machine.snapshot)
if not state:
raise CuckooCriticalError("Unable to find snapshot {0} "
"for machine {1}, please "
"update your configuration."
.format(machine.snapshot,
machine.label))
if state != self.RUNNING:
raise CuckooCriticalError("Snapshot for machine {0} not "
"in powered-on state, please "
"create one."
.format(machine.label))
except CuckooCriticalError:
raise
except Exception as e:
raise CuckooCriticalError("Couldn't connect to vSphere host")
super(vSphere, self)._initialize_check() | [
"def",
"_initialize_check",
"(",
"self",
")",
":",
"self",
".",
"connect_opts",
"=",
"{",
"}",
"if",
"self",
".",
"options",
".",
"vsphere",
".",
"host",
":",
"self",
".",
"connect_opts",
"[",
"\"host\"",
"]",
"=",
"self",
".",
"options",
".",
"vsphere... | https://github.com/spender-sandbox/cuckoo-modified/blob/eb93ef3d41b8fee51b4330306dcd315d8101e021/modules/machinery/vsphere.py#L53-L128 | ||
docker-archive/docker-registry | f93b432d3fc7befa508ab27a590e6d0f78c86401 | docker_registry/images.py | python | put_image_json | (image_id) | return toolkit.response() | [] | def put_image_json(image_id):
data = None
try:
# Note(dmp): unicode patch
data = json.loads(flask.request.data.decode('utf8'))
except ValueError:
pass
if not data or not isinstance(data, dict):
return toolkit.api_error('Invalid JSON')
if 'id' not in data:
return toolkit.api_error('Missing key `id\' in JSON')
if image_id != data['id']:
return toolkit.api_error('JSON data contains invalid id')
if check_images_list(image_id) is False:
return toolkit.api_error('This image does not belong to the '
'repository')
parent_id = data.get('parent')
if parent_id and not store.exists(store.image_json_path(data['parent'])):
return toolkit.api_error('Image depends on a non existing parent')
elif parent_id and not toolkit.validate_parent_access(parent_id):
return toolkit.api_error('Image depends on an unauthorized parent')
json_path = store.image_json_path(image_id)
mark_path = store.image_mark_path(image_id)
if store.exists(json_path) and not store.exists(mark_path):
return toolkit.api_error('Image already exists', 409)
sender = flask.current_app._get_current_object()
signal_result = signals.before_put_image_json.send(sender, image_json=data)
for result_pair in signal_result:
if result_pair[1] is not None:
return toolkit.api_error(result_pair[1])
# If we reach that point, it means that this is a new image or a retry
# on a failed push
store.put_content(mark_path, 'true')
# We cleanup any old checksum in case it's a retry after a fail
try:
store.remove(store.image_checksum_path(image_id))
except Exception:
pass
store.put_content(json_path, flask.request.data)
layers.generate_ancestry(image_id, parent_id)
return toolkit.response() | [
"def",
"put_image_json",
"(",
"image_id",
")",
":",
"data",
"=",
"None",
"try",
":",
"# Note(dmp): unicode patch",
"data",
"=",
"json",
".",
"loads",
"(",
"flask",
".",
"request",
".",
"data",
".",
"decode",
"(",
"'utf8'",
")",
")",
"except",
"ValueError",... | https://github.com/docker-archive/docker-registry/blob/f93b432d3fc7befa508ab27a590e6d0f78c86401/docker_registry/images.py#L334-L376 | |||
liuyubobobo/Play-with-Linear-Algebra | e86175adb908b03756618fbeeeadb448a3551321 | 09-Vector-Space-Dimension-and-Four-Subspaces/08-Implement-Rank-of-Matrix/playLA/Vector.py | python | Vector.norm | (self) | return math.sqrt(sum(e**2 for e in self)) | 返回向量的模 | 返回向量的模 | [
"返回向量的模"
] | def norm(self):
"""返回向量的模"""
return math.sqrt(sum(e**2 for e in self)) | [
"def",
"norm",
"(",
"self",
")",
":",
"return",
"math",
".",
"sqrt",
"(",
"sum",
"(",
"e",
"**",
"2",
"for",
"e",
"in",
"self",
")",
")"
] | https://github.com/liuyubobobo/Play-with-Linear-Algebra/blob/e86175adb908b03756618fbeeeadb448a3551321/09-Vector-Space-Dimension-and-Four-Subspaces/08-Implement-Rank-of-Matrix/playLA/Vector.py#L29-L31 | |
suurjaak/Skyperious | 6a4f264dbac8d326c2fa8aeb5483dbca987860bf | skyperious/support.py | python | FeedbackDialog.OnToggleFullScreen | (self, event) | Handler for toggling screenshot size from fullscreen to window. | Handler for toggling screenshot size from fullscreen to window. | [
"Handler",
"for",
"toggling",
"screenshot",
"size",
"from",
"fullscreen",
"to",
"window",
"."
] | def OnToggleFullScreen(self, event):
"""Handler for toggling screenshot size from fullscreen to window."""
self.SetScreenshot(take_screenshot(self.cb_fullscreen.Value)) | [
"def",
"OnToggleFullScreen",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"SetScreenshot",
"(",
"take_screenshot",
"(",
"self",
".",
"cb_fullscreen",
".",
"Value",
")",
")"
] | https://github.com/suurjaak/Skyperious/blob/6a4f264dbac8d326c2fa8aeb5483dbca987860bf/skyperious/support.py#L378-L380 | ||
tBuLi/symfit | 3bcb66fbbe518f65a1339d6c62be715da4d77398 | symfit/core/models.py | python | HessianModel.hessian | (self) | return [[[sympy.diff(partial_dv, param) for param in self.params]
for partial_dv in comp] for comp in self.jacobian] | :return: Hessian filled with the symbolic expressions for all the
second order partial derivatives. Partial derivatives are taken with
respect to the Parameter's, not the independent Variable's. | :return: Hessian filled with the symbolic expressions for all the
second order partial derivatives. Partial derivatives are taken with
respect to the Parameter's, not the independent Variable's. | [
":",
"return",
":",
"Hessian",
"filled",
"with",
"the",
"symbolic",
"expressions",
"for",
"all",
"the",
"second",
"order",
"partial",
"derivatives",
".",
"Partial",
"derivatives",
"are",
"taken",
"with",
"respect",
"to",
"the",
"Parameter",
"s",
"not",
"the",
... | def hessian(self):
"""
:return: Hessian filled with the symbolic expressions for all the
second order partial derivatives. Partial derivatives are taken with
respect to the Parameter's, not the independent Variable's.
"""
return [[[sympy.diff(partial_dv, param) for param in self.params]
for partial_dv in comp] for comp in self.jacobian] | [
"def",
"hessian",
"(",
"self",
")",
":",
"return",
"[",
"[",
"[",
"sympy",
".",
"diff",
"(",
"partial_dv",
",",
"param",
")",
"for",
"param",
"in",
"self",
".",
"params",
"]",
"for",
"partial_dv",
"in",
"comp",
"]",
"for",
"comp",
"in",
"self",
"."... | https://github.com/tBuLi/symfit/blob/3bcb66fbbe518f65a1339d6c62be715da4d77398/symfit/core/models.py#L925-L932 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/napalm_mod.py | python | alive | (**kwargs) | return salt.utils.napalm.call(
napalm_device, "is_alive", **{} # pylint: disable=undefined-variable
) | Returns the alive status of the connection layer.
The output is a dictionary under the usual dictionary
output of the NAPALM modules.
CLI Example:
.. code-block:: bash
salt '*' napalm.alive
Output Example:
.. code-block:: yaml
result: True
out:
is_alive: False
comment: '' | Returns the alive status of the connection layer.
The output is a dictionary under the usual dictionary
output of the NAPALM modules. | [
"Returns",
"the",
"alive",
"status",
"of",
"the",
"connection",
"layer",
".",
"The",
"output",
"is",
"a",
"dictionary",
"under",
"the",
"usual",
"dictionary",
"output",
"of",
"the",
"NAPALM",
"modules",
"."
] | def alive(**kwargs): # pylint: disable=unused-argument
"""
Returns the alive status of the connection layer.
The output is a dictionary under the usual dictionary
output of the NAPALM modules.
CLI Example:
.. code-block:: bash
salt '*' napalm.alive
Output Example:
.. code-block:: yaml
result: True
out:
is_alive: False
comment: ''
"""
return salt.utils.napalm.call(
napalm_device, "is_alive", **{} # pylint: disable=undefined-variable
) | [
"def",
"alive",
"(",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"return",
"salt",
".",
"utils",
".",
"napalm",
".",
"call",
"(",
"napalm_device",
",",
"\"is_alive\"",
",",
"*",
"*",
"{",
"}",
"# pylint: disable=undefined-variable",
")"
] | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/napalm_mod.py#L170-L193 | |
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/bdf/bdf_interface/pybdf.py | python | BDFInputPy._validate_open_file | (self, bdf_filename: Union[str, StringIO],
bdf_filename_inc: str,
check: bool=True) | checks that the file doesn't have obvious errors
- hasn't been used
- not a directory
- is a file
Parameters
----------
bdf_filename : str
the current bdf filename
bdf_filename_inc : str
the next bdf filename
check : bool; default=True
you can disable the checks
Raises
------
RuntimeError : file is active
IOError : Invalid file type | checks that the file doesn't have obvious errors
- hasn't been used
- not a directory
- is a file | [
"checks",
"that",
"the",
"file",
"doesn",
"t",
"have",
"obvious",
"errors",
"-",
"hasn",
"t",
"been",
"used",
"-",
"not",
"a",
"directory",
"-",
"is",
"a",
"file"
] | def _validate_open_file(self, bdf_filename: Union[str, StringIO],
bdf_filename_inc: str,
check: bool=True) -> None:
"""
checks that the file doesn't have obvious errors
- hasn't been used
- not a directory
- is a file
Parameters
----------
bdf_filename : str
the current bdf filename
bdf_filename_inc : str
the next bdf filename
check : bool; default=True
you can disable the checks
Raises
------
RuntimeError : file is active
IOError : Invalid file type
"""
if check:
if not os.path.exists(_filename(bdf_filename_inc)):
msg = 'No such bdf_filename: %r\n' % bdf_filename_inc
msg += 'cwd: %r\n' % os.getcwd()
msg += 'include_dir: %r\n' % self.include_dir
msg += print_bad_path(bdf_filename_inc)
raise IOError(msg)
elif bdf_filename_inc.endswith('.op2'):
raise IOError('Invalid filetype: bdf_filename=%r' % bdf_filename_inc)
bdf_filename = bdf_filename_inc
if bdf_filename in self.active_filenames:
msg = 'bdf_filename=%s is already active.\nactive_filenames=%s' \
% (bdf_filename, self.active_filenames)
raise RuntimeError(msg)
elif os.path.isdir(_filename(bdf_filename)):
current_fname = self.active_filename if len(self.active_filenames) > 0 else 'None'
raise IOError('Found a directory: bdf_filename=%r\ncurrent_file=%s' % (
bdf_filename_inc, current_fname))
elif not os.path.isfile(_filename(bdf_filename)):
raise IOError('Not a file: bdf_filename=%r' % bdf_filename) | [
"def",
"_validate_open_file",
"(",
"self",
",",
"bdf_filename",
":",
"Union",
"[",
"str",
",",
"StringIO",
"]",
",",
"bdf_filename_inc",
":",
"str",
",",
"check",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"check",
":",
"if",
"not",
"os",
... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/bdf_interface/pybdf.py#L677-L721 | ||
geopython/OWSLib | 414375413c9e2bab33a2d09608ab209875ce6daf | owslib/util.py | python | cleanup_namespaces | (element) | Remove unused namespaces from an element | Remove unused namespaces from an element | [
"Remove",
"unused",
"namespaces",
"from",
"an",
"element"
] | def cleanup_namespaces(element):
""" Remove unused namespaces from an element """
if etree.__name__ == 'lxml.etree':
etree.cleanup_namespaces(element)
return element
else:
return etree.fromstring(etree.tostring(element)) | [
"def",
"cleanup_namespaces",
"(",
"element",
")",
":",
"if",
"etree",
".",
"__name__",
"==",
"'lxml.etree'",
":",
"etree",
".",
"cleanup_namespaces",
"(",
"element",
")",
"return",
"element",
"else",
":",
"return",
"etree",
".",
"fromstring",
"(",
"etree",
"... | https://github.com/geopython/OWSLib/blob/414375413c9e2bab33a2d09608ab209875ce6daf/owslib/util.py#L278-L284 | ||
solarwinds/orionsdk-python | 97168451ddbc68db1773717f592a42f78be0eefe | orionsdk/solarwinds.py | python | SolarWinds.does_dependency_exist | (self, dependency_name) | Checks to see if a SolarWinds dependency exists with the given name. Calls the get_dependency_id method of
the class and uses the returned value to determine whether or not the dependency exists.
Args:
dependency_name(string): A dependency name which should equal the name used in SolarWinds for the
dependency object.
Returns:
True: The dependency exists.
False: The dependency does not exist. | Checks to see if a SolarWinds dependency exists with the given name. Calls the get_dependency_id method of
the class and uses the returned value to determine whether or not the dependency exists. | [
"Checks",
"to",
"see",
"if",
"a",
"SolarWinds",
"dependency",
"exists",
"with",
"the",
"given",
"name",
".",
"Calls",
"the",
"get_dependency_id",
"method",
"of",
"the",
"class",
"and",
"uses",
"the",
"returned",
"value",
"to",
"determine",
"whether",
"or",
"... | def does_dependency_exist(self, dependency_name):
""" Checks to see if a SolarWinds dependency exists with the given name. Calls the get_dependency_id method of
the class and uses the returned value to determine whether or not the dependency exists.
Args:
dependency_name(string): A dependency name which should equal the name used in SolarWinds for the
dependency object.
Returns:
True: The dependency exists.
False: The dependency does not exist.
"""
if self.get_dependency_id(dependency_name):
return True
else:
return False | [
"def",
"does_dependency_exist",
"(",
"self",
",",
"dependency_name",
")",
":",
"if",
"self",
".",
"get_dependency_id",
"(",
"dependency_name",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/solarwinds/orionsdk-python/blob/97168451ddbc68db1773717f592a42f78be0eefe/orionsdk/solarwinds.py#L582-L599 | ||
nathanlopez/Stitch | 8e22e91c94237959c02d521aab58dc7e3d994cea | Application/stitch_cmd.py | python | stitch_server.complete_ls | (self, text, line, begidx, endidx) | return find_path(text, line, begidx, endidx, dir_only = True) | [] | def complete_ls(self, text, line, begidx, endidx):
return find_path(text, line, begidx, endidx, dir_only = True) | [
"def",
"complete_ls",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
":",
"return",
"find_path",
"(",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
",",
"dir_only",
"=",
"True",
")"
] | https://github.com/nathanlopez/Stitch/blob/8e22e91c94237959c02d521aab58dc7e3d994cea/Application/stitch_cmd.py#L458-L459 | |||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/celery/worker/control.py | python | control_command | (**kwargs) | return Panel.register(type='control', **kwargs) | [] | def control_command(**kwargs):
return Panel.register(type='control', **kwargs) | [
"def",
"control_command",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"Panel",
".",
"register",
"(",
"type",
"=",
"'control'",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/worker/control.py#L73-L74 | |||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/freezer.py | python | _remove_extra_packages | (frozen_pkgs, ret, **kwargs) | Remove extra packages and update the ret dict | Remove extra packages and update the ret dict | [
"Remove",
"extra",
"packages",
"and",
"update",
"the",
"ret",
"dict"
] | def _remove_extra_packages(frozen_pkgs, ret, **kwargs):
"""Remove extra packages and update the ret dict"""
pkgs = __salt__["pkg.list_pkgs"](**kwargs)
extra_pkgs = set(pkgs) - set(frozen_pkgs)
for pkg in extra_pkgs:
try:
__salt__["pkg.remove"](name=pkg, **kwargs)
ret["pkgs"]["remove"].append(pkg)
log.info("Removed extra package %s", pkg)
except Exception as e: # pylint: disable=broad-except
msg = "Error removing %s package: %s"
log.error(msg, pkg, e)
ret["comment"].append(msg % (pkg, e)) | [
"def",
"_remove_extra_packages",
"(",
"frozen_pkgs",
",",
"ret",
",",
"*",
"*",
"kwargs",
")",
":",
"pkgs",
"=",
"__salt__",
"[",
"\"pkg.list_pkgs\"",
"]",
"(",
"*",
"*",
"kwargs",
")",
"extra_pkgs",
"=",
"set",
"(",
"pkgs",
")",
"-",
"set",
"(",
"froz... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/freezer.py#L204-L216 | ||
stellargraph/stellargraph | 3c2c8c18ab4c5c16660f350d8e23d7dc39e738de | stellargraph/mapper/sequences.py | python | LinkSequence.on_epoch_end | (self) | Shuffle all link IDs at the end of each epoch | Shuffle all link IDs at the end of each epoch | [
"Shuffle",
"all",
"link",
"IDs",
"at",
"the",
"end",
"of",
"each",
"epoch"
] | def on_epoch_end(self):
"""
Shuffle all link IDs at the end of each epoch
"""
self.indices = list(range(self.data_size))
if self.shuffle:
self._rs.shuffle(self.indices) | [
"def",
"on_epoch_end",
"(",
"self",
")",
":",
"self",
".",
"indices",
"=",
"list",
"(",
"range",
"(",
"self",
".",
"data_size",
")",
")",
"if",
"self",
".",
"shuffle",
":",
"self",
".",
"_rs",
".",
"shuffle",
"(",
"self",
".",
"indices",
")"
] | https://github.com/stellargraph/stellargraph/blob/3c2c8c18ab4c5c16660f350d8e23d7dc39e738de/stellargraph/mapper/sequences.py#L245-L251 | ||
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/s3cfg.py | python | S3Config.get_supply_shipping_code | (self) | return self.supply.get("shipping_code") | Custom shipping code generator (REQ, WB, GRN etc)
- function(prefix, site_id, field) | Custom shipping code generator (REQ, WB, GRN etc)
- function(prefix, site_id, field) | [
"Custom",
"shipping",
"code",
"generator",
"(",
"REQ",
"WB",
"GRN",
"etc",
")",
"-",
"function",
"(",
"prefix",
"site_id",
"field",
")"
] | def get_supply_shipping_code(self):
"""
Custom shipping code generator (REQ, WB, GRN etc)
- function(prefix, site_id, field)
"""
return self.supply.get("shipping_code") | [
"def",
"get_supply_shipping_code",
"(",
"self",
")",
":",
"return",
"self",
".",
"supply",
".",
"get",
"(",
"\"shipping_code\"",
")"
] | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3cfg.py#L6171-L6176 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.