repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
Geotab/mygeotab-python | mygeotab/api.py | https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L160-L170 | def set(self, type_name, entity):
"""Sets an entity using the API. Shortcut for using call() with the 'Set' method.
:param type_name: The type of entity.
:type type_name: str
:param entity: The entity to set.
:type entity: dict
:raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
:raise TimeoutException: Raises when the request does not respond after some time.
"""
return self.call('Set', type_name=type_name, entity=entity) | [
"def",
"set",
"(",
"self",
",",
"type_name",
",",
"entity",
")",
":",
"return",
"self",
".",
"call",
"(",
"'Set'",
",",
"type_name",
"=",
"type_name",
",",
"entity",
"=",
"entity",
")"
] | Sets an entity using the API. Shortcut for using call() with the 'Set' method.
:param type_name: The type of entity.
:type type_name: str
:param entity: The entity to set.
:type entity: dict
:raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
:raise TimeoutException: Raises when the request does not respond after some time. | [
"Sets",
"an",
"entity",
"using",
"the",
"API",
".",
"Shortcut",
"for",
"using",
"call",
"()",
"with",
"the",
"Set",
"method",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py#L565-L575 | def threshold_monitor_hidden_threshold_monitor_interface_pause(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_monitor = ET.SubElement(threshold_monitor_hidden, "threshold-monitor")
interface = ET.SubElement(threshold_monitor, "interface")
pause = ET.SubElement(interface, "pause")
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"threshold_monitor_hidden_threshold_monitor_interface_pause",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"threshold_monitor_hidden",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"thres... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Qiskit/qiskit-terra | qiskit/compiler/transpiler.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/compiler/transpiler.py#L19-L147 | def transpile(circuits,
backend=None,
basis_gates=None, coupling_map=None, backend_properties=None,
initial_layout=None, seed_transpiler=None,
optimization_level=None,
pass_manager=None,
seed_mapper=None): # deprecated
"""transpile one or more circuits, according to some desired
transpilation targets.
All arguments may be given as either singleton or list. In case of list,
the length must be equal to the number of circuits being transpiled.
Transpilation is done in parallel using multiprocessing.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]):
Circuit(s) to transpile
backend (BaseBackend):
If set, transpiler options are automatically grabbed from
backend.configuration() and backend.properties().
If any other option is explicitly set (e.g. coupling_map), it
will override the backend's.
Note: the backend arg is purely for convenience. The resulting
circuit may be run on any backend as long as it is compatible.
basis_gates (list[str]):
List of basis gate names to unroll to.
e.g:
['u1', 'u2', 'u3', 'cx']
If None, do not unroll.
coupling_map (CouplingMap or list):
Coupling map (perhaps custom) to target in mapping.
Multiple formats are supported:
a. CouplingMap instance
b. list
Must be given as an adjacency matrix, where each entry
specifies all two-qubit interactions supported by backend
e.g:
[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]
backend_properties (BackendProperties):
properties returned by a backend, including information on gate
errors, readout errors, qubit coherence times, etc. For a backend
that provides this information, it can be obtained with:
``backend.properties()``
initial_layout (Layout or dict or list):
Initial position of virtual qubits on physical qubits.
If this layout makes the circuit compatible with the coupling_map
constraints, it will be used.
The final layout is not guaranteed to be the same, as the transpiler
may permute qubits through swaps or other means.
Multiple formats are supported:
a. Layout instance
b. dict
virtual to physical:
{qr[0]: 0,
qr[1]: 3,
qr[2]: 5}
physical to virtual:
{0: qr[0],
3: qr[1],
5: qr[2]}
c. list
virtual to physical:
[0, 3, 5] # virtual qubits are ordered (in addition to named)
physical to virtual:
[qr[0], None, None, qr[1], None, qr[2]]
seed_transpiler (int):
sets random seed for the stochastic parts of the transpiler
optimization_level (int):
How much optimization to perform on the circuits.
Higher levels generate more optimized circuits,
at the expense of longer transpilation time.
0: no optimization
1: light optimization
2: heavy optimization
pass_manager (PassManager):
The pass manager to use for a custom pipeline of transpiler passes.
If this arg is present, all other args will be ignored and the
pass manager will be used directly (Qiskit will not attempt to
auto-select a pass manager based on transpile options).
seed_mapper (int):
DEPRECATED in 0.8: use ``seed_transpiler`` kwarg instead
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: in case of bad inputs to transpiler or errors in passes
"""
# Deprecation matter
if seed_mapper:
warnings.warn("seed_mapper has been deprecated and will be removed in the "
"0.9 release. Instead use seed_transpiler to set the seed "
"for all stochastic parts of the.", DeprecationWarning)
seed_transpiler = seed_mapper
# transpiling schedules is not supported yet.
if isinstance(circuits, Schedule) or \
(isinstance(circuits, list) and all(isinstance(c, Schedule) for c in circuits)):
return circuits
# Get TranspileConfig(s) to configure the circuit transpilation job(s)
circuits = circuits if isinstance(circuits, list) else [circuits]
transpile_configs = _parse_transpile_args(circuits, backend, basis_gates, coupling_map,
backend_properties, initial_layout,
seed_transpiler, optimization_level,
pass_manager)
# Transpile circuits in parallel
circuits = parallel_map(_transpile_circuit, list(zip(circuits, transpile_configs)))
if len(circuits) == 1:
return circuits[0]
return circuits | [
"def",
"transpile",
"(",
"circuits",
",",
"backend",
"=",
"None",
",",
"basis_gates",
"=",
"None",
",",
"coupling_map",
"=",
"None",
",",
"backend_properties",
"=",
"None",
",",
"initial_layout",
"=",
"None",
",",
"seed_transpiler",
"=",
"None",
",",
"optimi... | transpile one or more circuits, according to some desired
transpilation targets.
All arguments may be given as either singleton or list. In case of list,
the length must be equal to the number of circuits being transpiled.
Transpilation is done in parallel using multiprocessing.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]):
Circuit(s) to transpile
backend (BaseBackend):
If set, transpiler options are automatically grabbed from
backend.configuration() and backend.properties().
If any other option is explicitly set (e.g. coupling_map), it
will override the backend's.
Note: the backend arg is purely for convenience. The resulting
circuit may be run on any backend as long as it is compatible.
basis_gates (list[str]):
List of basis gate names to unroll to.
e.g:
['u1', 'u2', 'u3', 'cx']
If None, do not unroll.
coupling_map (CouplingMap or list):
Coupling map (perhaps custom) to target in mapping.
Multiple formats are supported:
a. CouplingMap instance
b. list
Must be given as an adjacency matrix, where each entry
specifies all two-qubit interactions supported by backend
e.g:
[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]
backend_properties (BackendProperties):
properties returned by a backend, including information on gate
errors, readout errors, qubit coherence times, etc. For a backend
that provides this information, it can be obtained with:
``backend.properties()``
initial_layout (Layout or dict or list):
Initial position of virtual qubits on physical qubits.
If this layout makes the circuit compatible with the coupling_map
constraints, it will be used.
The final layout is not guaranteed to be the same, as the transpiler
may permute qubits through swaps or other means.
Multiple formats are supported:
a. Layout instance
b. dict
virtual to physical:
{qr[0]: 0,
qr[1]: 3,
qr[2]: 5}
physical to virtual:
{0: qr[0],
3: qr[1],
5: qr[2]}
c. list
virtual to physical:
[0, 3, 5] # virtual qubits are ordered (in addition to named)
physical to virtual:
[qr[0], None, None, qr[1], None, qr[2]]
seed_transpiler (int):
sets random seed for the stochastic parts of the transpiler
optimization_level (int):
How much optimization to perform on the circuits.
Higher levels generate more optimized circuits,
at the expense of longer transpilation time.
0: no optimization
1: light optimization
2: heavy optimization
pass_manager (PassManager):
The pass manager to use for a custom pipeline of transpiler passes.
If this arg is present, all other args will be ignored and the
pass manager will be used directly (Qiskit will not attempt to
auto-select a pass manager based on transpile options).
seed_mapper (int):
DEPRECATED in 0.8: use ``seed_transpiler`` kwarg instead
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: in case of bad inputs to transpiler or errors in passes | [
"transpile",
"one",
"or",
"more",
"circuits",
"according",
"to",
"some",
"desired",
"transpilation",
"targets",
"."
] | python | test |
mcrute/pydora | pandora/models/_base.py | https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/models/_base.py#L120-L147 | def populate_fields(api_client, instance, data):
"""Populate all fields of a model with data
Given a model with a PandoraModel superclass will enumerate all
declared fields on that model and populate the values of their Field
and SyntheticField classes. All declared fields will have a value after
this function runs even if they are missing from the incoming JSON.
"""
for key, value in instance.__class__._fields.items():
default = getattr(value, "default", None)
newval = data.get(value.field, default)
if isinstance(value, SyntheticField):
newval = value.formatter(api_client, data, newval)
setattr(instance, key, newval)
continue
model_class = getattr(value, "model", None)
if newval and model_class:
if isinstance(newval, list):
newval = model_class.from_json_list(api_client, newval)
else:
newval = model_class.from_json(api_client, newval)
if newval and value.formatter:
newval = value.formatter(api_client, newval)
setattr(instance, key, newval) | [
"def",
"populate_fields",
"(",
"api_client",
",",
"instance",
",",
"data",
")",
":",
"for",
"key",
",",
"value",
"in",
"instance",
".",
"__class__",
".",
"_fields",
".",
"items",
"(",
")",
":",
"default",
"=",
"getattr",
"(",
"value",
",",
"\"default\"",... | Populate all fields of a model with data
Given a model with a PandoraModel superclass will enumerate all
declared fields on that model and populate the values of their Field
and SyntheticField classes. All declared fields will have a value after
this function runs even if they are missing from the incoming JSON. | [
"Populate",
"all",
"fields",
"of",
"a",
"model",
"with",
"data"
] | python | valid |
tanghaibao/jcvi | jcvi/utils/cbook.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/cbook.py#L308-L326 | def autoscale(bp, optimal=6):
"""
>>> autoscale(150000000)
20000000
>>> autoscale(97352632)
10000000
"""
slen = str(bp)
tlen = slen[0:2] if len(slen) > 1 else slen[0]
precision = len(slen) - 2 # how many zeros we need to pad?
bp_len_scaled = int(tlen) # scale bp_len to range (0, 100)
tick_diffs = [(x, abs(bp_len_scaled / x - optimal)) for x in [1, 2, 5, 10]]
best_stride, best_tick_diff = min(tick_diffs, key=lambda x: x[1])
while precision > 0:
best_stride *= 10
precision -= 1
return best_stride | [
"def",
"autoscale",
"(",
"bp",
",",
"optimal",
"=",
"6",
")",
":",
"slen",
"=",
"str",
"(",
"bp",
")",
"tlen",
"=",
"slen",
"[",
"0",
":",
"2",
"]",
"if",
"len",
"(",
"slen",
")",
">",
"1",
"else",
"slen",
"[",
"0",
"]",
"precision",
"=",
"... | >>> autoscale(150000000)
20000000
>>> autoscale(97352632)
10000000 | [
">>>",
"autoscale",
"(",
"150000000",
")",
"20000000",
">>>",
"autoscale",
"(",
"97352632",
")",
"10000000"
] | python | train |
camptocamp/Studio | studio/lib/archivefile.py | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/archivefile.py#L22-L55 | def extractall(archive, filename, dstdir):
""" extract zip or tar content to dstdir"""
if zipfile.is_zipfile(archive):
z = zipfile.ZipFile(archive)
for name in z.namelist():
targetname = name
# directories ends with '/' (on Windows as well)
if targetname.endswith('/'):
targetname = targetname[:-1]
# don't include leading "/" from file name if present
if targetname.startswith(os.path.sep):
targetname = os.path.join(dstdir, targetname[1:])
else:
targetname = os.path.join(dstdir, targetname)
targetname = os.path.normpath(targetname)
# Create all upper directories if necessary.
upperdirs = os.path.dirname(targetname)
if upperdirs and not os.path.exists(upperdirs):
os.makedirs(upperdirs)
# directories ends with '/' (on Windows as well)
if not name.endswith('/'):
# copy file
file(targetname, 'wb').write(z.read(name))
elif tarfile.is_tarfile(archive):
tar = tarfile.open(archive)
tar.extractall(path=dstdir)
else:
# seems to be a single file, save it
shutil.copyfile(archive, os.path.join(dstdir, filename)) | [
"def",
"extractall",
"(",
"archive",
",",
"filename",
",",
"dstdir",
")",
":",
"if",
"zipfile",
".",
"is_zipfile",
"(",
"archive",
")",
":",
"z",
"=",
"zipfile",
".",
"ZipFile",
"(",
"archive",
")",
"for",
"name",
"in",
"z",
".",
"namelist",
"(",
")"... | extract zip or tar content to dstdir | [
"extract",
"zip",
"or",
"tar",
"content",
"to",
"dstdir"
] | python | train |
jason-weirather/py-seq-tools | seqtools/format/bgzf.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/format/bgzf.py#L138-L154 | def read(self,size):
"""read size bytes and return them"""
done = 0 #number of bytes that have been read so far
v = ''
while True:
if size-done < len(self._buffer['data']) - self._buffer_pos:
v += self._buffer['data'][self._buffer_pos:self._buffer_pos+(size-done)]
self._buffer_pos += (size-done)
#self.pointer += size
return v
else: # we need more buffer
vpart = self._buffer['data'][self._buffer_pos:]
self._buffer = self._load_block()
v += vpart
self._buffer_pos = 0
if len(self._buffer['data'])==0: return v
done += len(vpart) | [
"def",
"read",
"(",
"self",
",",
"size",
")",
":",
"done",
"=",
"0",
"#number of bytes that have been read so far",
"v",
"=",
"''",
"while",
"True",
":",
"if",
"size",
"-",
"done",
"<",
"len",
"(",
"self",
".",
"_buffer",
"[",
"'data'",
"]",
")",
"-",
... | read size bytes and return them | [
"read",
"size",
"bytes",
"and",
"return",
"them"
] | python | train |
testing-cabal/mock | mock/mock.py | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L907-L914 | def assert_called_once(_mock_self):
"""assert that the mock was called only once.
"""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg) | [
"def",
"assert_called_once",
"(",
"_mock_self",
")",
":",
"self",
"=",
"_mock_self",
"if",
"not",
"self",
".",
"call_count",
"==",
"1",
":",
"msg",
"=",
"(",
"\"Expected '%s' to have been called once. Called %s times.\"",
"%",
"(",
"self",
".",
"_mock_name",
"or",... | assert that the mock was called only once. | [
"assert",
"that",
"the",
"mock",
"was",
"called",
"only",
"once",
"."
] | python | train |
bkabrda/anymarkup-core | anymarkup_core/__init__.py | https://github.com/bkabrda/anymarkup-core/blob/299935092fc2650cca4e32ec92441786918f9bab/anymarkup_core/__init__.py#L425-L458 | def _guess_fmt_from_bytes(inp):
"""Try to guess format of given bytestring.
Args:
inp: byte string to guess format of
Returns:
guessed format
"""
stripped = inp.strip()
fmt = None
ini_section_header_re = re.compile(b'^\[([\w-]+)\]')
if len(stripped) == 0:
# this can be anything, so choose yaml, for example
fmt = 'yaml'
else:
if stripped.startswith(b'<'):
fmt = 'xml'
else:
for l in stripped.splitlines():
line = l.strip()
# there are C-style comments in json5, but we don't auto-detect it,
# so it doesn't matter here
if not line.startswith(b'#') and line:
break
# json, ini or yaml => skip comments and then determine type
if ini_section_header_re.match(line):
fmt = 'ini'
else:
# we assume that yaml is superset of json
# TODO: how do we figure out it's not yaml?
fmt = 'yaml'
return fmt | [
"def",
"_guess_fmt_from_bytes",
"(",
"inp",
")",
":",
"stripped",
"=",
"inp",
".",
"strip",
"(",
")",
"fmt",
"=",
"None",
"ini_section_header_re",
"=",
"re",
".",
"compile",
"(",
"b'^\\[([\\w-]+)\\]'",
")",
"if",
"len",
"(",
"stripped",
")",
"==",
"0",
"... | Try to guess format of given bytestring.
Args:
inp: byte string to guess format of
Returns:
guessed format | [
"Try",
"to",
"guess",
"format",
"of",
"given",
"bytestring",
"."
] | python | train |
jtwhite79/pyemu | pyemu/utils/pp_utils.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/pp_utils.py#L252-L277 | def pp_tpl_to_dataframe(tpl_filename):
""" read a pilot points template file to a pandas dataframe
Parameters
----------
tpl_filename : str
pilot points template file
Returns
-------
df : pandas.DataFrame
a dataframe with "parnme" included
"""
inlines = open(tpl_filename, 'r').readlines()
header = inlines.pop(0)
marker = header.strip().split()[1]
assert len(marker) == 1
usecols = [0,1,2,3]
df = pd.read_csv(tpl_filename, delim_whitespace=True,skiprows=1,
header=None, names=PP_NAMES[:-1],usecols=usecols)
df.loc[:,"name"] = df.name.apply(str).apply(str.lower)
df["parnme"] = [i.split(marker)[1].strip() for i in inlines]
return df | [
"def",
"pp_tpl_to_dataframe",
"(",
"tpl_filename",
")",
":",
"inlines",
"=",
"open",
"(",
"tpl_filename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"header",
"=",
"inlines",
".",
"pop",
"(",
"0",
")",
"marker",
"=",
"header",
".",
"strip",
"(",
")",... | read a pilot points template file to a pandas dataframe
Parameters
----------
tpl_filename : str
pilot points template file
Returns
-------
df : pandas.DataFrame
a dataframe with "parnme" included | [
"read",
"a",
"pilot",
"points",
"template",
"file",
"to",
"a",
"pandas",
"dataframe"
] | python | train |
frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/__init__.py | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/__init__.py#L41-L85 | def get_driver(driver='ASCII_RS232', *args, **keywords):
""" Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
which corresponds to ``drivers.ASCII_RS232``.
Parameters
----------
driver : str, optional
The driver to communicate to the particular driver with, which
includes the hardware connection and possibly the communications
protocol. The only driver currently supported is the
``'ASCII_RS232'`` driver which corresponds to
``drivers.ASCII_RS232``.
*args : additional positional arguments
Additional positional arguments to pass onto the constructor for
the driver.
**keywords : additional keyword arguments
Additional keyword arguments to pass onto the constructor for
the driver.
Returns
-------
drivers : drivers
The connected drivers class that is connected to the drive.
Raises
------
NotImplementedError
If the `driver` is not supported.
See Also
--------
drivers
drivers.ASCII_RS232
"""
if driver.upper() == 'ASCII_RS232':
return drivers.ASCII_RS232(*args, **keywords)
else:
raise NotImplementedError('Driver not supported: '
+ str(driver)) | [
"def",
"get_driver",
"(",
"driver",
"=",
"'ASCII_RS232'",
",",
"*",
"args",
",",
"*",
"*",
"keywords",
")",
":",
"if",
"driver",
".",
"upper",
"(",
")",
"==",
"'ASCII_RS232'",
":",
"return",
"drivers",
".",
"ASCII_RS232",
"(",
"*",
"args",
",",
"*",
... | Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
which corresponds to ``drivers.ASCII_RS232``.
Parameters
----------
driver : str, optional
The driver to communicate to the particular driver with, which
includes the hardware connection and possibly the communications
protocol. The only driver currently supported is the
``'ASCII_RS232'`` driver which corresponds to
``drivers.ASCII_RS232``.
*args : additional positional arguments
Additional positional arguments to pass onto the constructor for
the driver.
**keywords : additional keyword arguments
Additional keyword arguments to pass onto the constructor for
the driver.
Returns
-------
drivers : drivers
The connected drivers class that is connected to the drive.
Raises
------
NotImplementedError
If the `driver` is not supported.
See Also
--------
drivers
drivers.ASCII_RS232 | [
"Gets",
"a",
"driver",
"for",
"a",
"Parker",
"Motion",
"Gemini",
"drive",
"."
] | python | train |
riga/tfdeploy | tfdeploy.py | https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L2159-L2164 | def Conv3D(a, f, strides, padding):
"""
3D conv op.
"""
patches = _conv_patches(a, f, strides, padding.decode("ascii"))
return np.sum(patches, axis=tuple(range(-f.ndim, -1))), | [
"def",
"Conv3D",
"(",
"a",
",",
"f",
",",
"strides",
",",
"padding",
")",
":",
"patches",
"=",
"_conv_patches",
"(",
"a",
",",
"f",
",",
"strides",
",",
"padding",
".",
"decode",
"(",
"\"ascii\"",
")",
")",
"return",
"np",
".",
"sum",
"(",
"patches... | 3D conv op. | [
"3D",
"conv",
"op",
"."
] | python | train |
pybel/pybel | src/pybel/manager/cache_manager.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L1045-L1047 | def get_modification_by_hash(self, sha512: str) -> Optional[Modification]:
"""Get a modification by a SHA512 hash."""
return self.session.query(Modification).filter(Modification.sha512 == sha512).one_or_none() | [
"def",
"get_modification_by_hash",
"(",
"self",
",",
"sha512",
":",
"str",
")",
"->",
"Optional",
"[",
"Modification",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Modification",
")",
".",
"filter",
"(",
"Modification",
".",
"sha512",
"=... | Get a modification by a SHA512 hash. | [
"Get",
"a",
"modification",
"by",
"a",
"SHA512",
"hash",
"."
] | python | train |
nats-io/python-nats | nats/io/client.py | https://github.com/nats-io/python-nats/blob/4a409319c409e7e55ce8377b64b406375c5f455b/nats/io/client.py#L1338-L1354 | def _process_err(self, err=None):
"""
Stores the last received error from the server and dispatches the error callback.
"""
self.stats['errors_received'] += 1
if err == "'Authorization Violation'":
self._err = ErrAuthorization
elif err == "'Slow Consumer'":
self._err = ErrSlowConsumer
elif err == "'Stale Connection'":
self._err = ErrStaleConnection
else:
self._err = Exception(err)
if self._error_cb is not None:
self._error_cb(err) | [
"def",
"_process_err",
"(",
"self",
",",
"err",
"=",
"None",
")",
":",
"self",
".",
"stats",
"[",
"'errors_received'",
"]",
"+=",
"1",
"if",
"err",
"==",
"\"'Authorization Violation'\"",
":",
"self",
".",
"_err",
"=",
"ErrAuthorization",
"elif",
"err",
"==... | Stores the last received error from the server and dispatches the error callback. | [
"Stores",
"the",
"last",
"received",
"error",
"from",
"the",
"server",
"and",
"dispatches",
"the",
"error",
"callback",
"."
] | python | train |
insomnia-lab/libreant | users/__init__.py | https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/users/__init__.py#L83-L107 | def populate_with_defaults():
'''Create user admin and grant him all permission
If the admin user already exists the function will simply return
'''
logging.getLogger(__name__).debug("Populating with default users")
if not User.select().where(User.name == 'admin').exists():
admin = User.create(name='admin', password='admin')
admins = Group.create(name='admins')
starCap = Capability.create(domain='.+',
action=(Action.CREATE |
Action.READ |
Action.UPDATE |
Action.DELETE))
admins.capabilities.add(starCap)
admin.groups.add(admins)
admin.save()
if not User.select().where(User.name == 'anonymous').exists():
anon = User.create(name='anonymous', password='')
anons = Group.create(name='anonymous')
readCap = Capability.create(domain=Capability.simToReg('/volumes/*'),
action=Action.READ)
anons.capabilities.add(readCap)
anon.groups.add(anons)
anon.save() | [
"def",
"populate_with_defaults",
"(",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"debug",
"(",
"\"Populating with default users\"",
")",
"if",
"not",
"User",
".",
"select",
"(",
")",
".",
"where",
"(",
"User",
".",
"name",
"==",
"'ad... | Create user admin and grant him all permission
If the admin user already exists the function will simply return | [
"Create",
"user",
"admin",
"and",
"grant",
"him",
"all",
"permission"
] | python | train |
rosenbrockc/fortpy | fortpy/interop/ftypes.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/interop/ftypes.py#L602-L620 | def _py_check_optional(parameter, tab, assign):
"""Returns the code to check for actual values when an out parameter is pure
out/optional and doesn't have anything changed.
:arg assign: the actual variable assignment value if the conditions pass.
"""
if parameter.direction == "(out)":
result = []
checks = ["{0}_{1:d}.value==0".format(parameter.lname, i) for i in range(parameter.D)]
spacing = len(tab) + 2 + 3 + 3 + 2
result.append("{}if not all([{}]):".format(tab, present_params(checks, spacing, linecont=", ")))
for line in assign:
if assign is not None:
result.append("{0}{1}".format(tab, line))
result.append("{}else:".format(tab))
result.append('{0}{0}result.add("{1}", None)'.format(tab, parameter.lname))
return '\n'.join(result)
else:
return '\n'.join(assign) | [
"def",
"_py_check_optional",
"(",
"parameter",
",",
"tab",
",",
"assign",
")",
":",
"if",
"parameter",
".",
"direction",
"==",
"\"(out)\"",
":",
"result",
"=",
"[",
"]",
"checks",
"=",
"[",
"\"{0}_{1:d}.value==0\"",
".",
"format",
"(",
"parameter",
".",
"l... | Returns the code to check for actual values when an out parameter is pure
out/optional and doesn't have anything changed.
:arg assign: the actual variable assignment value if the conditions pass. | [
"Returns",
"the",
"code",
"to",
"check",
"for",
"actual",
"values",
"when",
"an",
"out",
"parameter",
"is",
"pure",
"out",
"/",
"optional",
"and",
"doesn",
"t",
"have",
"anything",
"changed",
"."
] | python | train |
quikmile/trellio | trellio/utils/decorators.py | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/utils/decorators.py#L21-L57 | def retry(exceptions, tries=5, delay=1, backoff=2, logger=None):
"""
Retry calling the decorated function using an exponential backoff.
Args:
exceptions: The exception to check. may be a tuple of
exceptions to check.
tries: Number of times to try (not retry) before giving up.
delay: Initial delay between retries in seconds.
backoff: Backoff multiplier (e.g. value of 2 will double the delay
each retry).
logger: Logger to use. If None, print.
"""
def deco_retry(func):
@wraps(func)
async def f_retry(self, *args, **kwargs):
if not iscoroutine(func):
f = coroutine(func)
else:
f = func
mtries, mdelay = tries, delay
while mtries > 1:
try:
return await f(self, *args, **kwargs)
except exceptions:
if logger:
logger.info('Retrying %s after %s seconds', f.__name__, mdelay)
sleep(mdelay)
mtries -= 1
mdelay *= backoff
return await f(self, *args, **kwargs)
return f_retry
return deco_retry | [
"def",
"retry",
"(",
"exceptions",
",",
"tries",
"=",
"5",
",",
"delay",
"=",
"1",
",",
"backoff",
"=",
"2",
",",
"logger",
"=",
"None",
")",
":",
"def",
"deco_retry",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"async",
"def",
"f_retr... | Retry calling the decorated function using an exponential backoff.
Args:
exceptions: The exception to check. may be a tuple of
exceptions to check.
tries: Number of times to try (not retry) before giving up.
delay: Initial delay between retries in seconds.
backoff: Backoff multiplier (e.g. value of 2 will double the delay
each retry).
logger: Logger to use. If None, print. | [
"Retry",
"calling",
"the",
"decorated",
"function",
"using",
"an",
"exponential",
"backoff",
"."
] | python | train |
PyCQA/prospector | prospector/blender.py | https://github.com/PyCQA/prospector/blob/7cfc6d587049a786f935a722d6851cd3b72d7972/prospector/blender.py#L19-L77 | def blend_line(messages, blend_combos=None):
"""
Given a list of messages on the same line, blend them together so that we
end up with one message per actual problem. Note that we can still return
more than one message here if there are two or more different errors for
the line.
"""
blend_combos = blend_combos or BLEND_COMBOS
blend_lists = [[] for _ in range(len(blend_combos))]
blended = []
# first we split messages into each of the possible blendable categories
# so that we have a list of lists of messages which can be blended together
for message in messages:
key = (message.source, message.code)
found = False
for blend_combo_idx, blend_combo in enumerate(blend_combos):
if key in blend_combo:
found = True
blend_lists[blend_combo_idx].append(message)
# note: we use 'found=True' here rather than a simple break/for-else
# because this allows the same message to be put into more than one
# 'bucket'. This means that the same message from pep8 can 'subsume'
# two from pylint, for example.
if not found:
# if we get here, then this is not a message which can be blended,
# so by definition is already blended
blended.append(message)
# we should now have a list of messages which all represent the same
# problem on the same line, so we will sort them according to the priority
# in BLEND and pick the first one
for blend_combo_idx, blend_list in enumerate(blend_lists):
if len(blend_list) == 0:
continue
blend_list.sort(
key=lambda msg: blend_combos[blend_combo_idx].index(
(msg.source, msg.code),
),
)
if blend_list[0] not in blended:
# We may have already added this message if it represents
# several messages in other tools which are not being run -
# for example, pylint missing-docstring is blended with pep257 D100, D101
# and D102, but should not appear 3 times!
blended.append(blend_list[0])
# Some messages from a tool point out an error that in another tool is handled by two
# different errors or more. For example, pylint emits the same warning (multiple-statements)
# for "two statements on a line" separated by a colon and a semi-colon, while pep8 has E701
# and E702 for those cases respectively. In this case, the pylint error will not be 'blended' as
# it will appear in two blend_lists. Therefore we mark anything not taken from the blend list
# as "consumed" and then filter later, to avoid such cases.
for now_used in blend_list[1:]:
now_used.used = True
return [m for m in blended if not getattr(m, 'used', False)] | [
"def",
"blend_line",
"(",
"messages",
",",
"blend_combos",
"=",
"None",
")",
":",
"blend_combos",
"=",
"blend_combos",
"or",
"BLEND_COMBOS",
"blend_lists",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"blend_combos",
")",
")",
"]",
"bl... | Given a list of messages on the same line, blend them together so that we
end up with one message per actual problem. Note that we can still return
more than one message here if there are two or more different errors for
the line. | [
"Given",
"a",
"list",
"of",
"messages",
"on",
"the",
"same",
"line",
"blend",
"them",
"together",
"so",
"that",
"we",
"end",
"up",
"with",
"one",
"message",
"per",
"actual",
"problem",
".",
"Note",
"that",
"we",
"can",
"still",
"return",
"more",
"than",
... | python | train |
hearsaycorp/normalize | normalize/record/__init__.py | https://github.com/hearsaycorp/normalize/blob/8b36522ddca6d41b434580bd848f3bdaa7a999c8/normalize/record/__init__.py#L170-L176 | def diff(self, other, **kwargs):
"""Compare an object with another and return a :py:class:`DiffInfo`
object. Accepts the same arguments as
:py:meth:`normalize.record.Record.diff_iter`
"""
from normalize.diff import diff
return diff(self, other, **kwargs) | [
"def",
"diff",
"(",
"self",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"normalize",
".",
"diff",
"import",
"diff",
"return",
"diff",
"(",
"self",
",",
"other",
",",
"*",
"*",
"kwargs",
")"
] | Compare an object with another and return a :py:class:`DiffInfo`
object. Accepts the same arguments as
:py:meth:`normalize.record.Record.diff_iter` | [
"Compare",
"an",
"object",
"with",
"another",
"and",
"return",
"a",
":",
"py",
":",
"class",
":",
"DiffInfo",
"object",
".",
"Accepts",
"the",
"same",
"arguments",
"as",
":",
"py",
":",
"meth",
":",
"normalize",
".",
"record",
".",
"Record",
".",
"diff... | python | train |
sorgerlab/indra | indra/sources/hume/processor.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hume/processor.py#L141-L163 | def _make_concept(self, entity):
"""Return Concept from a Hume entity."""
# Use the canonical name as the name of the Concept by default
name = self._sanitize(entity['canonicalName'])
# But if there is a trigger head text, we prefer that since
# it almost always results in a cleaner name
# This is removed for now since the head word seems to be too
# minimal for some concepts, e.g. it gives us only "security"
# for "food security".
"""
trigger = entity.get('trigger')
if trigger is not None:
head_text = trigger.get('head text')
if head_text is not None:
name = head_text
"""
# Save raw text and Hume scored groundings as db_refs
db_refs = _get_grounding(entity)
concept = Concept(name, db_refs=db_refs)
metadata = {arg['type']: arg['value']['@id']
for arg in entity['arguments']}
return concept, metadata | [
"def",
"_make_concept",
"(",
"self",
",",
"entity",
")",
":",
"# Use the canonical name as the name of the Concept by default",
"name",
"=",
"self",
".",
"_sanitize",
"(",
"entity",
"[",
"'canonicalName'",
"]",
")",
"# But if there is a trigger head text, we prefer that since... | Return Concept from a Hume entity. | [
"Return",
"Concept",
"from",
"a",
"Hume",
"entity",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_vcs.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_vcs.py#L716-L730 | def get_last_config_update_time_for_xpaths_output_last_config_update_time_for_xpaths_last_config_update_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_last_config_update_time_for_xpaths = ET.Element("get_last_config_update_time_for_xpaths")
config = get_last_config_update_time_for_xpaths
output = ET.SubElement(get_last_config_update_time_for_xpaths, "output")
last_config_update_time_for_xpaths = ET.SubElement(output, "last-config-update-time-for-xpaths")
xpath_string_key = ET.SubElement(last_config_update_time_for_xpaths, "xpath-string")
xpath_string_key.text = kwargs.pop('xpath_string')
last_config_update_time = ET.SubElement(last_config_update_time_for_xpaths, "last-config-update-time")
last_config_update_time.text = kwargs.pop('last_config_update_time')
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"get_last_config_update_time_for_xpaths_output_last_config_update_time_for_xpaths_last_config_update_time",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_last_config_update_time_for_xpaths",
"=",
"ET",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Akrog/cinderlib | cinderlib/cinderlib.py | https://github.com/Akrog/cinderlib/blob/6481cd9a34744f80bdba130fe9089f1b8b7cb327/cinderlib/cinderlib.py#L202-L215 | def _update_cinder_config(cls):
"""Parse in-memory file to update OSLO configuration used by Cinder."""
cls._config_string_io.seek(0)
cls._parser.write(cls._config_string_io)
# Check if we have any multiopt
cls._config_string_io.seek(0)
current_cfg = cls._config_string_io.read()
if '\n\t' in current_cfg:
cls._config_string_io.seek(0)
cls._config_string_io.write(current_cfg.replace('\n\t', '\n'))
cls._config_string_io.seek(0)
cfg.CONF.reload_config_files() | [
"def",
"_update_cinder_config",
"(",
"cls",
")",
":",
"cls",
".",
"_config_string_io",
".",
"seek",
"(",
"0",
")",
"cls",
".",
"_parser",
".",
"write",
"(",
"cls",
".",
"_config_string_io",
")",
"# Check if we have any multiopt",
"cls",
".",
"_config_string_io",... | Parse in-memory file to update OSLO configuration used by Cinder. | [
"Parse",
"in",
"-",
"memory",
"file",
"to",
"update",
"OSLO",
"configuration",
"used",
"by",
"Cinder",
"."
] | python | train |
ska-sa/katcp-python | katcp/resource_client.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L889-L906 | def reapply_sampling_strategies(self):
"""Reapply all sensor strategies using cached values"""
check_sensor = self._inspecting_client.future_check_sensor
for sensor_name, strategy in list(self._strategy_cache.items()):
try:
sensor_exists = yield check_sensor(sensor_name)
if not sensor_exists:
self._logger.warn('Did not set strategy for non-existing sensor {}'
.format(sensor_name))
continue
result = yield self.set_sampling_strategy(sensor_name, strategy)
except KATCPSensorError as e:
self._logger.error('Error reapplying strategy for sensor {0}: {1!s}'
.format(sensor_name, e))
except Exception:
self._logger.exception('Unhandled exception reapplying strategy for '
'sensor {}'.format(sensor_name), exc_info=True) | [
"def",
"reapply_sampling_strategies",
"(",
"self",
")",
":",
"check_sensor",
"=",
"self",
".",
"_inspecting_client",
".",
"future_check_sensor",
"for",
"sensor_name",
",",
"strategy",
"in",
"list",
"(",
"self",
".",
"_strategy_cache",
".",
"items",
"(",
")",
")"... | Reapply all sensor strategies using cached values | [
"Reapply",
"all",
"sensor",
"strategies",
"using",
"cached",
"values"
] | python | train |
bapakode/OmMongo | ommongo/fields/ref.py | https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/ref.py#L65-L70 | def dereference(self, session, ref, allow_none=False):
""" Dereference an ObjectID to this field's underlying type """
ref = DBRef(id=ref, collection=self.type.type.get_collection_name(),
database=self.db)
ref.type = self.type.type
return session.dereference(ref, allow_none=allow_none) | [
"def",
"dereference",
"(",
"self",
",",
"session",
",",
"ref",
",",
"allow_none",
"=",
"False",
")",
":",
"ref",
"=",
"DBRef",
"(",
"id",
"=",
"ref",
",",
"collection",
"=",
"self",
".",
"type",
".",
"type",
".",
"get_collection_name",
"(",
")",
",",... | Dereference an ObjectID to this field's underlying type | [
"Dereference",
"an",
"ObjectID",
"to",
"this",
"field",
"s",
"underlying",
"type"
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_console.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_console.py#L72-L75 | def unload(self):
'''unload module'''
self.mpstate.console.close()
self.mpstate.console = textconsole.SimpleConsole() | [
"def",
"unload",
"(",
"self",
")",
":",
"self",
".",
"mpstate",
".",
"console",
".",
"close",
"(",
")",
"self",
".",
"mpstate",
".",
"console",
"=",
"textconsole",
".",
"SimpleConsole",
"(",
")"
] | unload module | [
"unload",
"module"
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L12970-L13060 | def attach_device_without_medium(self, name, controller_port, device, type_p):
"""Attaches a device and optionally mounts a medium to the given storage
controller (:py:class:`IStorageController` , identified by @a name),
at the indicated port and device.
This method is intended for managing storage devices in general while a
machine is powered off. It can be used to attach and detach fixed
and removable media. The following kind of media can be attached
to a machine:
For fixed and removable media, you can pass in a medium that was
previously opened using :py:func:`IVirtualBox.open_medium` .
Only for storage devices supporting removable media (such as
DVDs and floppies) with an empty drive or one of the medium objects listed
in the :py:func:`IHost.dvd_drives` and :py:func:`IHost.floppy_drives`
arrays to indicate a host drive.
For removable devices, you can also use :py:func:`IMachine.mount_medium`
to change the media while the machine is running.
In a VM's default configuration of virtual machines, the secondary
master of the IDE controller is used for a CD/DVD drive.
:py:class:`IMediumAttachment` will appear in the machine's list of medium
attachments (see :py:func:`IMachine.medium_attachments` ).
See :py:class:`IMedium` and :py:class:`IMediumAttachment` for more
information about attaching media.
The specified device slot must not have a device attached to it,
or this method will fail.
You cannot attach a device to a newly created machine until
this machine's settings are saved to disk using
:py:func:`save_settings` .
If the medium is being attached indirectly, a new differencing medium
will implicitly be created for it and attached instead. If the
changes made to the machine settings (including this indirect
attachment) are later cancelled using :py:func:`discard_settings` ,
this implicitly created differencing medium will implicitly
be deleted.
in name of type str
Name of the storage controller to attach the device to.
in controller_port of type int
Port to attach the device to. For an IDE controller, 0 specifies
the primary controller and 1 specifies the secondary controller.
For a SCSI controller, this must range from 0 to 15; for a SATA controller,
from 0 to 29; for an SAS controller, from 0 to 7.
in device of type int
Device slot in the given port to attach the device to. This is only
relevant for IDE controllers, for which 0 specifies the master device and
1 specifies the slave device. For all other controller types, this must
be 0.
in type_p of type :class:`DeviceType`
Device type of the attached device. For media opened by
:py:func:`IVirtualBox.open_medium` , this must match the device type
specified there.
raises :class:`OleErrorInvalidarg`
SATA device, SATA port, IDE port or IDE slot out of range, or
file or UUID not found.
raises :class:`VBoxErrorInvalidObjectState`
Machine must be registered before media can be attached.
raises :class:`VBoxErrorInvalidVmState`
Invalid machine state.
raises :class:`VBoxErrorObjectInUse`
A medium is already attached to this or another virtual machine.
"""
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
if not isinstance(controller_port, baseinteger):
raise TypeError("controller_port can only be an instance of type baseinteger")
if not isinstance(device, baseinteger):
raise TypeError("device can only be an instance of type baseinteger")
if not isinstance(type_p, DeviceType):
raise TypeError("type_p can only be an instance of type DeviceType")
self._call("attachDeviceWithoutMedium",
in_p=[name, controller_port, device, type_p]) | [
"def",
"attach_device_without_medium",
"(",
"self",
",",
"name",
",",
"controller_port",
",",
"device",
",",
"type_p",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be an instance of type... | Attaches a device and optionally mounts a medium to the given storage
controller (:py:class:`IStorageController` , identified by @a name),
at the indicated port and device.
This method is intended for managing storage devices in general while a
machine is powered off. It can be used to attach and detach fixed
and removable media. The following kind of media can be attached
to a machine:
For fixed and removable media, you can pass in a medium that was
previously opened using :py:func:`IVirtualBox.open_medium` .
Only for storage devices supporting removable media (such as
DVDs and floppies) with an empty drive or one of the medium objects listed
in the :py:func:`IHost.dvd_drives` and :py:func:`IHost.floppy_drives`
arrays to indicate a host drive.
For removable devices, you can also use :py:func:`IMachine.mount_medium`
to change the media while the machine is running.
In a VM's default configuration of virtual machines, the secondary
master of the IDE controller is used for a CD/DVD drive.
:py:class:`IMediumAttachment` will appear in the machine's list of medium
attachments (see :py:func:`IMachine.medium_attachments` ).
See :py:class:`IMedium` and :py:class:`IMediumAttachment` for more
information about attaching media.
The specified device slot must not have a device attached to it,
or this method will fail.
You cannot attach a device to a newly created machine until
this machine's settings are saved to disk using
:py:func:`save_settings` .
If the medium is being attached indirectly, a new differencing medium
will implicitly be created for it and attached instead. If the
changes made to the machine settings (including this indirect
attachment) are later cancelled using :py:func:`discard_settings` ,
this implicitly created differencing medium will implicitly
be deleted.
in name of type str
Name of the storage controller to attach the device to.
in controller_port of type int
Port to attach the device to. For an IDE controller, 0 specifies
the primary controller and 1 specifies the secondary controller.
For a SCSI controller, this must range from 0 to 15; for a SATA controller,
from 0 to 29; for an SAS controller, from 0 to 7.
in device of type int
Device slot in the given port to attach the device to. This is only
relevant for IDE controllers, for which 0 specifies the master device and
1 specifies the slave device. For all other controller types, this must
be 0.
in type_p of type :class:`DeviceType`
Device type of the attached device. For media opened by
:py:func:`IVirtualBox.open_medium` , this must match the device type
specified there.
raises :class:`OleErrorInvalidarg`
SATA device, SATA port, IDE port or IDE slot out of range, or
file or UUID not found.
raises :class:`VBoxErrorInvalidObjectState`
Machine must be registered before media can be attached.
raises :class:`VBoxErrorInvalidVmState`
Invalid machine state.
raises :class:`VBoxErrorObjectInUse`
A medium is already attached to this or another virtual machine. | [
"Attaches",
"a",
"device",
"and",
"optionally",
"mounts",
"a",
"medium",
"to",
"the",
"given",
"storage",
"controller",
"(",
":",
"py",
":",
"class",
":",
"IStorageController",
"identified",
"by",
"@a",
"name",
")",
"at",
"the",
"indicated",
"port",
"and",
... | python | train |
stovorov/IteratorDecorator | IteratorDecorator/src.py | https://github.com/stovorov/IteratorDecorator/blob/9bc054a50758c19f41da8220f230beba1c2debbb/IteratorDecorator/src.py#L8-L90 | def iter_attribute(iterable_name) -> Union[Iterable, Callable]:
"""Decorator implementing Iterator interface with nicer manner.
Example
-------
@iter_attribute('my_attr'):
class DecoratedClass:
...
Warning:
========
When using PyCharm or MYPY you'll probably see issues with decorated class not being recognized as Iterator.
That's an issue which I could not overcome yet, it's probably due to the fact that interpretation of object
is being done statically rather than dynamically. MYPY checks for definition of methods in class code which
changes at runtime. Since __iter__ and __next__ are added dynamically MYPY cannot find those
defined in objects before object of a class is created. Possible workarounds for this issue are:
1. Define ``dummy`` __iter__ class like:
@iter_attribute('attr')
class Test:
def __init__(self) -> None:
self.attr = [1, 2, 3]
def __iter__(self):
pass
2. After creating object use cast or assert function denoting that particular instance inherits
from collections.Iterator:
assert isinstance(my_object, collections.Iterator)
:param iterable_name: string representing attribute name which has to be iterated
:return: DecoratedClass with implemented '__iter__' and '__next__' methods.
"""
def create_new_class(decorated_class) -> Union[Iterable, Callable]:
"""Class extender implementing __next__ and __iter__ methods.
:param decorated_class: class to be extended with iterator interface
:return: new class
"""
assert inspect.isclass(decorated_class), 'You can only decorate class objects!'
assert isinstance(iterable_name, str), 'Please provide attribute name string'
decorated_class.iterator_attr_index = 0
def __iter__(instance) -> Iterable:
"""Implement __iter__ method
:param instance: __iter__ uses instance of class which is being extended
:return: instance of decorated_class
"""
return instance
def __next__(instance) -> Any:
"""Implement __next__ method
:param instance: __next__ uses instance of class which is being extended
:return: instance of decorated_class
"""
assert hasattr(instance, iterable_name), \
'Decorated object does not have attribute named {}'.format(iterable_name)
assert isinstance(getattr(instance, iterable_name), collections.Iterable), \
'{} of object {} is not iterable'.format(iterable_name, instance.__class__.__name__)
ind = instance.iterator_attr_index
while ind < len(getattr(instance, iterable_name)):
val = getattr(instance, iterable_name)[ind]
instance.iterator_attr_index += 1
return val
instance.iterator_attr_index = 0
raise StopIteration
dct = dict(decorated_class.__dict__)
dct['__iter__'] = __iter__
dct['__next__'] = __next__
dct['iterator_attr_index'] = decorated_class.iterator_attr_index
return type(decorated_class.__name__, (collections.Iterable,), dct)
return create_new_class | [
"def",
"iter_attribute",
"(",
"iterable_name",
")",
"->",
"Union",
"[",
"Iterable",
",",
"Callable",
"]",
":",
"def",
"create_new_class",
"(",
"decorated_class",
")",
"->",
"Union",
"[",
"Iterable",
",",
"Callable",
"]",
":",
"\"\"\"Class extender implementing __n... | Decorator implementing Iterator interface with nicer manner.
Example
-------
@iter_attribute('my_attr'):
class DecoratedClass:
...
Warning:
========
When using PyCharm or MYPY you'll probably see issues with decorated class not being recognized as Iterator.
That's an issue which I could not overcome yet, it's probably due to the fact that interpretation of object
is being done statically rather than dynamically. MYPY checks for definition of methods in class code which
changes at runtime. Since __iter__ and __next__ are added dynamically MYPY cannot find those
defined in objects before object of a class is created. Possible workarounds for this issue are:
1. Define ``dummy`` __iter__ class like:
@iter_attribute('attr')
class Test:
def __init__(self) -> None:
self.attr = [1, 2, 3]
def __iter__(self):
pass
2. After creating object use cast or assert function denoting that particular instance inherits
from collections.Iterator:
assert isinstance(my_object, collections.Iterator)
:param iterable_name: string representing attribute name which has to be iterated
:return: DecoratedClass with implemented '__iter__' and '__next__' methods. | [
"Decorator",
"implementing",
"Iterator",
"interface",
"with",
"nicer",
"manner",
"."
] | python | test |
Bogdanp/dramatiq | dramatiq/broker.py | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/broker.py#L26-L44 | def get_broker() -> "Broker":
"""Get the global broker instance. If no global broker is set,
this initializes a RabbitmqBroker and returns it.
Returns:
Broker: The default Broker.
"""
global global_broker
if global_broker is None:
from .brokers.rabbitmq import RabbitmqBroker
set_broker(RabbitmqBroker(
host="127.0.0.1",
port=5672,
heartbeat=5,
connection_attempts=5,
blocked_connection_timeout=30,
))
return global_broker | [
"def",
"get_broker",
"(",
")",
"->",
"\"Broker\"",
":",
"global",
"global_broker",
"if",
"global_broker",
"is",
"None",
":",
"from",
".",
"brokers",
".",
"rabbitmq",
"import",
"RabbitmqBroker",
"set_broker",
"(",
"RabbitmqBroker",
"(",
"host",
"=",
"\"127.0.0.1\... | Get the global broker instance. If no global broker is set,
this initializes a RabbitmqBroker and returns it.
Returns:
Broker: The default Broker. | [
"Get",
"the",
"global",
"broker",
"instance",
".",
"If",
"no",
"global",
"broker",
"is",
"set",
"this",
"initializes",
"a",
"RabbitmqBroker",
"and",
"returns",
"it",
"."
] | python | train |
steder/goose | goose/core.py | https://github.com/steder/goose/blob/e9290b39fdd7b3842052e40995ee833eaf8f15db/goose/core.py#L30-L69 | def executeBatch(cursor, sql,
regex=r"(?mx) ([^';]* (?:'[^']*'[^';]*)*)",
comment_regex=r"(?mx) (?:^\s*$)|(?:--.*$)"):
"""
Takes a SQL file and executes it as many separate statements.
TODO: replace regexes with something easier to grok and extend.
"""
# First, strip comments
sql = "\n".join([x.strip().replace("%", "%%") for x in re.split(comment_regex, sql) if x.strip()])
# Stored procedures don't work with the above regex because many of them are
# made up multiple sql statements each delimited with a single ;
# where the regexes assume each statement delimited by a ; is a complete
# statement to send to mysql and execute.
#
# Here i'm simply checking for the delimiter statements (which seem to be
# mysql-only) and then using them as markers to start accumulating statements.
# So the first delimiter is the signal to start accumulating
# and the second delimiter is the signal to combine them into
# single sql compound statement and send it to mysql.
in_proc = False
statements = []
for st in re.split(regex, sql)[1:][::2]:
if st.strip().lower().startswith("delimiter"):
in_proc = not in_proc
if statements and not in_proc:
procedure = ";".join(statements)
statements = []
cursor.execute(procedure)
# skip the delimiter line
continue
if in_proc:
statements.append(st)
else:
cursor.execute(st) | [
"def",
"executeBatch",
"(",
"cursor",
",",
"sql",
",",
"regex",
"=",
"r\"(?mx) ([^';]* (?:'[^']*'[^';]*)*)\"",
",",
"comment_regex",
"=",
"r\"(?mx) (?:^\\s*$)|(?:--.*$)\"",
")",
":",
"# First, strip comments",
"sql",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"x",
".",
... | Takes a SQL file and executes it as many separate statements.
TODO: replace regexes with something easier to grok and extend. | [
"Takes",
"a",
"SQL",
"file",
"and",
"executes",
"it",
"as",
"many",
"separate",
"statements",
"."
] | python | train |
evandempsey/porter2-stemmer | porter2stemmer/porter2stemmer.py | https://github.com/evandempsey/porter2-stemmer/blob/949824b7767c25efb014ef738e682442fa70c10b/porter2stemmer/porter2stemmer.py#L124-L136 | def strip_possessives(self, word):
"""
Get rid of apostrophes indicating possession.
"""
if word.endswith("'s'"):
return word[:-3]
elif word.endswith("'s"):
return word[:-2]
elif word.endswith("'"):
return word[:-1]
else:
return word | [
"def",
"strip_possessives",
"(",
"self",
",",
"word",
")",
":",
"if",
"word",
".",
"endswith",
"(",
"\"'s'\"",
")",
":",
"return",
"word",
"[",
":",
"-",
"3",
"]",
"elif",
"word",
".",
"endswith",
"(",
"\"'s\"",
")",
":",
"return",
"word",
"[",
":"... | Get rid of apostrophes indicating possession. | [
"Get",
"rid",
"of",
"apostrophes",
"indicating",
"possession",
"."
] | python | train |
scivision/gridaurora | gridaurora/ztanh.py | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/ztanh.py#L22-L27 | def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray:
"""
typically call via setupz instead
"""
x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote
return np.tanh(x0)*gridmax+gridmin | [
"def",
"_ztanh",
"(",
"Np",
":",
"int",
",",
"gridmin",
":",
"float",
",",
"gridmax",
":",
"float",
")",
"->",
"np",
".",
"ndarray",
":",
"x0",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"3.14",
",",
"Np",
")",
"# arbitrarily picking 3.14 as where tanh... | typically call via setupz instead | [
"typically",
"call",
"via",
"setupz",
"instead"
] | python | train |
StackStorm/pybind | pybind/nos/v7_2_0/isns/isns_vrf/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/isns/isns_vrf/__init__.py#L217-L240 | def _set_isns_discovery_domain(self, v, load=False):
"""
Setter method for isns_discovery_domain, mapped from YANG variable /isns/isns_vrf/isns_discovery_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_isns_discovery_domain is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_isns_discovery_domain() directly.
YANG Description: This specifies configurations of Discovery Domain.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("isns_discovery_domain_name",isns_discovery_domain.isns_discovery_domain, yang_name="isns-discovery-domain", rest_name="discovery-domain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='isns-discovery-domain-name', extensions={u'tailf-common': {u'info': u'Configure Discovery Domain Parameters', u'cli-no-key-completion': None, u'alt-name': u'discovery-domain', u'hidden': u'isns-discovery-domain', u'callpoint': u'isns_discovery_domain_cp', u'cli-mode-name': u'config-dd-$(isns-discovery-domain-name)'}}), is_container='list', yang_name="isns-discovery-domain", rest_name="discovery-domain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure Discovery Domain Parameters', u'cli-no-key-completion': None, u'alt-name': u'discovery-domain', u'hidden': u'isns-discovery-domain', u'callpoint': u'isns_discovery_domain_cp', u'cli-mode-name': u'config-dd-$(isns-discovery-domain-name)'}}, namespace='urn:brocade.com:mgmt:brocade-isns', defining_module='brocade-isns', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """isns_discovery_domain must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("isns_discovery_domain_name",isns_discovery_domain.isns_discovery_domain, yang_name="isns-discovery-domain", rest_name="discovery-domain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='isns-discovery-domain-name', extensions={u'tailf-common': {u'info': u'Configure Discovery Domain Parameters', u'cli-no-key-completion': None, u'alt-name': u'discovery-domain', u'hidden': u'isns-discovery-domain', u'callpoint': u'isns_discovery_domain_cp', u'cli-mode-name': u'config-dd-$(isns-discovery-domain-name)'}}), is_container='list', yang_name="isns-discovery-domain", rest_name="discovery-domain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure Discovery Domain Parameters', u'cli-no-key-completion': None, u'alt-name': u'discovery-domain', u'hidden': u'isns-discovery-domain', u'callpoint': u'isns_discovery_domain_cp', u'cli-mode-name': u'config-dd-$(isns-discovery-domain-name)'}}, namespace='urn:brocade.com:mgmt:brocade-isns', defining_module='brocade-isns', yang_type='list', is_config=True)""",
})
self.__isns_discovery_domain = t
if hasattr(self, '_set'):
self._set() | [
"def",
"_set_isns_discovery_domain",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | Setter method for isns_discovery_domain, mapped from YANG variable /isns/isns_vrf/isns_discovery_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_isns_discovery_domain is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_isns_discovery_domain() directly.
YANG Description: This specifies configurations of Discovery Domain. | [
"Setter",
"method",
"for",
"isns_discovery_domain",
"mapped",
"from",
"YANG",
"variable",
"/",
"isns",
"/",
"isns_vrf",
"/",
"isns_discovery_domain",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in... | python | train |
gitpython-developers/GitPython | git/refs/symbolic.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/refs/symbolic.py#L632-L649 | def iter_items(cls, repo, common_path=None):
"""Find all refs in the repository
:param repo: is the Repo
:param common_path:
Optional keyword argument to the path which is to be shared by all
returned Ref objects.
Defaults to class specific portion if None assuring that only
refs suitable for the actual class are returned.
:return:
git.SymbolicReference[], each of them is guaranteed to be a symbolic
ref which is not detached and pointing to a valid ref
List is lexicographically sorted
The returned objects represent actual subclasses, such as Head or TagReference"""
return (r for r in cls._iter_items(repo, common_path) if r.__class__ == SymbolicReference or not r.is_detached) | [
"def",
"iter_items",
"(",
"cls",
",",
"repo",
",",
"common_path",
"=",
"None",
")",
":",
"return",
"(",
"r",
"for",
"r",
"in",
"cls",
".",
"_iter_items",
"(",
"repo",
",",
"common_path",
")",
"if",
"r",
".",
"__class__",
"==",
"SymbolicReference",
"or"... | Find all refs in the repository
:param repo: is the Repo
:param common_path:
Optional keyword argument to the path which is to be shared by all
returned Ref objects.
Defaults to class specific portion if None assuring that only
refs suitable for the actual class are returned.
:return:
git.SymbolicReference[], each of them is guaranteed to be a symbolic
ref which is not detached and pointing to a valid ref
List is lexicographically sorted
The returned objects represent actual subclasses, such as Head or TagReference | [
"Find",
"all",
"refs",
"in",
"the",
"repository"
] | python | train |
ph4r05/monero-serialize | monero_serialize/xmrrpc.py | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrrpc.py#L961-L972 | async def uint(self, elem, elem_type, params=None):
"""
Integer types
:param elem:
:param elem_type:
:param params:
:return:
"""
if self.writing:
return IntegerModel(elem, elem_type.WIDTH) if self.modelize else elem
else:
return elem.val if isinstance(elem, IModel) else elem | [
"async",
"def",
"uint",
"(",
"self",
",",
"elem",
",",
"elem_type",
",",
"params",
"=",
"None",
")",
":",
"if",
"self",
".",
"writing",
":",
"return",
"IntegerModel",
"(",
"elem",
",",
"elem_type",
".",
"WIDTH",
")",
"if",
"self",
".",
"modelize",
"e... | Integer types
:param elem:
:param elem_type:
:param params:
:return: | [
"Integer",
"types",
":",
"param",
"elem",
":",
":",
"param",
"elem_type",
":",
":",
"param",
"params",
":",
":",
"return",
":"
] | python | train |
holgern/pyedflib | pyedflib/edfreader.py | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L644-L685 | def readSignal(self, chn, start=0, n=None):
"""
Returns the physical data of signal chn. When start and n is set, a subset is returned
Parameters
----------
chn : int
channel number
start : int
start pointer (default is 0)
n : int
length of data to read (default is None, by which the complete data of the channel are returned)
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> x = f.readSignal(0,0,1000)
>>> int(x.shape[0])
1000
>>> x2 = f.readSignal(0)
>>> int(x2.shape[0])
120000
>>> f._close()
>>> del f
"""
if start < 0:
return np.array([])
if n is not None and n < 0:
return np.array([])
nsamples = self.getNSamples()
if chn < len(nsamples):
if n is None:
n = nsamples[chn]
elif n > nsamples[chn]:
return np.array([])
x = np.zeros(n, dtype=np.float64)
self.readsignal(chn, start, n, x)
return x
else:
return np.array([]) | [
"def",
"readSignal",
"(",
"self",
",",
"chn",
",",
"start",
"=",
"0",
",",
"n",
"=",
"None",
")",
":",
"if",
"start",
"<",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"n",
"is",
"not",
"None",
"and",
"n",
"<",
"0",
":"... | Returns the physical data of signal chn. When start and n is set, a subset is returned
Parameters
----------
chn : int
channel number
start : int
start pointer (default is 0)
n : int
length of data to read (default is None, by which the complete data of the channel are returned)
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> x = f.readSignal(0,0,1000)
>>> int(x.shape[0])
1000
>>> x2 = f.readSignal(0)
>>> int(x2.shape[0])
120000
>>> f._close()
>>> del f | [
"Returns",
"the",
"physical",
"data",
"of",
"signal",
"chn",
".",
"When",
"start",
"and",
"n",
"is",
"set",
"a",
"subset",
"is",
"returned"
] | python | train |
LuqueDaniel/pybooru | pybooru/api_danbooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_danbooru.py#L1259-L1266 | def forum_topic_undelete(self, topic_id):
"""Un delete a topic (Login requries) (Moderator+) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id.
"""
return self._get('forum_topics/{0}/undelete.json'.format(topic_id),
method='POST', auth=True) | [
"def",
"forum_topic_undelete",
"(",
"self",
",",
"topic_id",
")",
":",
"return",
"self",
".",
"_get",
"(",
"'forum_topics/{0}/undelete.json'",
".",
"format",
"(",
"topic_id",
")",
",",
"method",
"=",
"'POST'",
",",
"auth",
"=",
"True",
")"
] | Un delete a topic (Login requries) (Moderator+) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id. | [
"Un",
"delete",
"a",
"topic",
"(",
"Login",
"requries",
")",
"(",
"Moderator",
"+",
")",
"(",
"UNTESTED",
")",
"."
] | python | train |
proteanhq/protean | src/protean/core/exceptions.py | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/exceptions.py#L52-L59 | def normalized_messages(self, no_field_name='_entity'):
"""Return all the error messages as a dictionary"""
if isinstance(self.messages, dict):
return self.messages
if not self.field_names:
return {no_field_name: self.messages}
return dict((name, self.messages) for name in self.field_names) | [
"def",
"normalized_messages",
"(",
"self",
",",
"no_field_name",
"=",
"'_entity'",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"messages",
",",
"dict",
")",
":",
"return",
"self",
".",
"messages",
"if",
"not",
"self",
".",
"field_names",
":",
"return",... | Return all the error messages as a dictionary | [
"Return",
"all",
"the",
"error",
"messages",
"as",
"a",
"dictionary"
] | python | train |
kivy/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/debug.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/debug.py#L170-L236 | def fake_exc_info(exc_info, filename, lineno):
"""Helper for `translate_exception`."""
exc_type, exc_value, tb = exc_info
# figure the real context out
if tb is not None:
real_locals = tb.tb_frame.f_locals.copy()
ctx = real_locals.get('context')
if ctx:
locals = ctx.get_all()
else:
locals = {}
for name, value in real_locals.iteritems():
if name.startswith('l_') and value is not missing:
locals[name[2:]] = value
# if there is a local called __jinja_exception__, we get
# rid of it to not break the debug functionality.
locals.pop('__jinja_exception__', None)
else:
locals = {}
# assamble fake globals we need
globals = {
'__name__': filename,
'__file__': filename,
'__jinja_exception__': exc_info[:2],
# we don't want to keep the reference to the template around
# to not cause circular dependencies, but we mark it as Jinja
# frame for the ProcessedTraceback
'__jinja_template__': None
}
# and fake the exception
code = compile('\n' * (lineno - 1) + raise_helper, filename, 'exec')
# if it's possible, change the name of the code. This won't work
# on some python environments such as google appengine
try:
if tb is None:
location = 'template'
else:
function = tb.tb_frame.f_code.co_name
if function == 'root':
location = 'top-level template code'
elif function.startswith('block_'):
location = 'block "%s"' % function[6:]
else:
location = 'template'
code = CodeType(0, code.co_nlocals, code.co_stacksize,
code.co_flags, code.co_code, code.co_consts,
code.co_names, code.co_varnames, filename,
location, code.co_firstlineno,
code.co_lnotab, (), ())
except:
pass
# execute the code and catch the new traceback
try:
exec code in globals, locals
except:
exc_info = sys.exc_info()
new_tb = exc_info[2].tb_next
# return without this frame
return exc_info[:2] + (new_tb,) | [
"def",
"fake_exc_info",
"(",
"exc_info",
",",
"filename",
",",
"lineno",
")",
":",
"exc_type",
",",
"exc_value",
",",
"tb",
"=",
"exc_info",
"# figure the real context out",
"if",
"tb",
"is",
"not",
"None",
":",
"real_locals",
"=",
"tb",
".",
"tb_frame",
"."... | Helper for `translate_exception`. | [
"Helper",
"for",
"translate_exception",
"."
] | python | train |
rytilahti/python-eq3bt | eq3bt/eq3cli.py | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L44-L49 | def temp(dev, target):
""" Gets or sets the target temperature."""
click.echo("Current target temp: %s" % dev.target_temperature)
if target:
click.echo("Setting target temp: %s" % target)
dev.target_temperature = target | [
"def",
"temp",
"(",
"dev",
",",
"target",
")",
":",
"click",
".",
"echo",
"(",
"\"Current target temp: %s\"",
"%",
"dev",
".",
"target_temperature",
")",
"if",
"target",
":",
"click",
".",
"echo",
"(",
"\"Setting target temp: %s\"",
"%",
"target",
")",
"dev"... | Gets or sets the target temperature. | [
"Gets",
"or",
"sets",
"the",
"target",
"temperature",
"."
] | python | train |
dustin/twitty-twister | twittytwister/streaming.py | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/streaming.py#L102-L119 | def fromDict(cls, data):
"""
Fill this objects attributes from a dict for known properties.
"""
obj = cls()
obj.raw = data
for name, value in data.iteritems():
if cls.SIMPLE_PROPS and name in cls.SIMPLE_PROPS:
setattr(obj, name, value)
elif cls.COMPLEX_PROPS and name in cls.COMPLEX_PROPS:
value = cls.COMPLEX_PROPS[name].fromDict(value)
setattr(obj, name, value)
elif cls.LIST_PROPS and name in cls.LIST_PROPS:
value = [cls.LIST_PROPS[name].fromDict(item)
for item in value]
setattr(obj, name, value)
return obj | [
"def",
"fromDict",
"(",
"cls",
",",
"data",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"obj",
".",
"raw",
"=",
"data",
"for",
"name",
",",
"value",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"if",
"cls",
".",
"SIMPLE_PROPS",
"and",
"name",
"in",
... | Fill this objects attributes from a dict for known properties. | [
"Fill",
"this",
"objects",
"attributes",
"from",
"a",
"dict",
"for",
"known",
"properties",
"."
] | python | train |
rix0rrr/gcl | gcl/ast.py | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast.py#L516-L525 | def applyIndex(self, lst, right):
"""Apply a list to something else."""
if len(right) != 1:
raise exceptions.EvaluationError('%r can only be applied to one argument, got %r' % (self.left, self.right))
right = right[0]
if isinstance(right, int):
return lst[right]
raise exceptions.EvaluationError("Can't apply %r to argument (%r): integer expected, got %r" % (self.left, self.right, right)) | [
"def",
"applyIndex",
"(",
"self",
",",
"lst",
",",
"right",
")",
":",
"if",
"len",
"(",
"right",
")",
"!=",
"1",
":",
"raise",
"exceptions",
".",
"EvaluationError",
"(",
"'%r can only be applied to one argument, got %r'",
"%",
"(",
"self",
".",
"left",
",",
... | Apply a list to something else. | [
"Apply",
"a",
"list",
"to",
"something",
"else",
"."
] | python | train |
bitesofcode/projex | projex/xbuild/builder.py | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xbuild/builder.py#L1713-L1764 | def fromFile(filename):
"""
Parses the inputted xml file information and generates a builder
for it.
:param filename | <str>
:return <Builder> || None
"""
xdata = None
ydata = None
# try parsing an XML file
try:
xdata = ElementTree.parse(filename).getroot()
except StandardError:
xdata = None
if xdata is None:
# try parsing a yaml file
if yaml:
with open(filename, 'r') as f:
text = f.read()
try:
ydata = yaml.load(text)
except StandardError:
return None
else:
log.warning('Could not process yaml builder!')
# load a yaml definition
if type(ydata) == dict:
typ = ydata.get('type')
module = ydata.get('module')
builder = Builder.plugin(typ, module)
if builder:
return builder.fromYaml(ydata, os.path.dirname(filename))
else:
log.warning('Could not find builder: {0}'.format(typ))
# load an xml definition
elif xdata is not None:
typ = xdata.get('type')
module = xdata.get('module')
builder = Builder.plugin(typ, module)
if builder:
return builder.fromXml(xdata, os.path.dirname(filename))
else:
log.warning('Could not find builder: {0}'.format(typ))
return None | [
"def",
"fromFile",
"(",
"filename",
")",
":",
"xdata",
"=",
"None",
"ydata",
"=",
"None",
"# try parsing an XML file",
"try",
":",
"xdata",
"=",
"ElementTree",
".",
"parse",
"(",
"filename",
")",
".",
"getroot",
"(",
")",
"except",
"StandardError",
":",
"x... | Parses the inputted xml file information and generates a builder
for it.
:param filename | <str>
:return <Builder> || None | [
"Parses",
"the",
"inputted",
"xml",
"file",
"information",
"and",
"generates",
"a",
"builder",
"for",
"it",
".",
":",
"param",
"filename",
"|",
"<str",
">",
":",
"return",
"<Builder",
">",
"||",
"None"
] | python | train |
Anaconda-Platform/anaconda-client | binstar_client/utils/config.py | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/utils/config.py#L101-L128 | def get_server_api(token=None, site=None, cls=None, config=None, **kwargs):
"""
Get the anaconda server api class
"""
if not cls:
from binstar_client import Binstar
cls = Binstar
config = config if config is not None else get_config(site=site)
url = config.get('url', DEFAULT_URL)
logger.info("Using Anaconda API: %s", url)
if token:
logger.debug("Using token from command line args")
elif 'BINSTAR_API_TOKEN' in os.environ:
logger.debug("Using token from environment variable BINSTAR_API_TOKEN")
token = os.environ['BINSTAR_API_TOKEN']
elif 'ANACONDA_API_TOKEN' in os.environ:
logger.debug("Using token from environment variable ANACONDA_API_TOKEN")
token = os.environ['ANACONDA_API_TOKEN']
else:
token = load_token(url)
verify = config.get('ssl_verify', config.get('verify_ssl', True))
return cls(token, domain=url, verify=verify, **kwargs) | [
"def",
"get_server_api",
"(",
"token",
"=",
"None",
",",
"site",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"config",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"cls",
":",
"from",
"binstar_client",
"import",
"Binstar",
"cls",
"=",
... | Get the anaconda server api class | [
"Get",
"the",
"anaconda",
"server",
"api",
"class"
] | python | train |
markovmodel/msmtools | msmtools/analysis/dense/decomposition.py | https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/dense/decomposition.py#L476-L519 | def timescales(T, tau=1, k=None, reversible=False, mu=None):
r"""Compute implied time scales of given transition matrix
Parameters
----------
T : (M, M) ndarray
Transition matrix
tau : int, optional
lag time
k : int, optional
Number of time scales
reversible : bool, optional
Indicate that transition matirx is reversible
mu : (M,) ndarray, optional
Stationary distribution of T
Returns
-------
ts : (N,) ndarray
Implied time scales of the transition matrix.
If k=None then N=M else N=k
Notes
-----
If reversible=True the the eigenvalues of the similar symmetric
matrix `\sqrt(\mu_i / \mu_j) p_{ij}` will be computed.
The precomputed stationary distribution will only be used if
reversible=True.
"""
values = eigenvalues(T, reversible=reversible, mu=mu)
"""Sort by absolute value"""
ind = np.argsort(np.abs(values))[::-1]
values = values[ind]
if k is None:
values = values
else:
values = values[0:k]
"""Compute implied time scales"""
return timescales_from_eigenvalues(values, tau) | [
"def",
"timescales",
"(",
"T",
",",
"tau",
"=",
"1",
",",
"k",
"=",
"None",
",",
"reversible",
"=",
"False",
",",
"mu",
"=",
"None",
")",
":",
"values",
"=",
"eigenvalues",
"(",
"T",
",",
"reversible",
"=",
"reversible",
",",
"mu",
"=",
"mu",
")"... | r"""Compute implied time scales of given transition matrix
Parameters
----------
T : (M, M) ndarray
Transition matrix
tau : int, optional
lag time
k : int, optional
Number of time scales
reversible : bool, optional
Indicate that transition matirx is reversible
mu : (M,) ndarray, optional
Stationary distribution of T
Returns
-------
ts : (N,) ndarray
Implied time scales of the transition matrix.
If k=None then N=M else N=k
Notes
-----
If reversible=True the the eigenvalues of the similar symmetric
matrix `\sqrt(\mu_i / \mu_j) p_{ij}` will be computed.
The precomputed stationary distribution will only be used if
reversible=True. | [
"r",
"Compute",
"implied",
"time",
"scales",
"of",
"given",
"transition",
"matrix"
] | python | train |
jaredLunde/redis_structures | redis_structures/__init__.py | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L407-L410 | def decr(self, key, by=1):
""" Decrements @key by @by
-> #int the value of @key after the decrement """
return self._client.decr(self.get_key(key), by) | [
"def",
"decr",
"(",
"self",
",",
"key",
",",
"by",
"=",
"1",
")",
":",
"return",
"self",
".",
"_client",
".",
"decr",
"(",
"self",
".",
"get_key",
"(",
"key",
")",
",",
"by",
")"
] | Decrements @key by @by
-> #int the value of @key after the decrement | [
"Decrements"
] | python | train |
hvac/hvac | hvac/api/auth_methods/github.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/auth_methods/github.py#L191-L216 | def login(self, token, use_token=True, mount_point=DEFAULT_MOUNT_POINT):
"""Login using GitHub access token.
Supported methods:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param token: GitHub personal API token.
:type token: str | unicode
:param use_token: if True, uses the token in the response received from the auth request to set the "token"
attribute on the the :py:meth:`hvac.adapters.Adapter` instance under the _adapater Client attribute.
:type use_token: bool
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the login request.
:rtype: dict
"""
params = {
'token': token,
}
api_path = '/v1/auth/{mount_point}/login'.format(mount_point=mount_point)
return self._adapter.login(
url=api_path,
use_token=use_token,
json=params,
) | [
"def",
"login",
"(",
"self",
",",
"token",
",",
"use_token",
"=",
"True",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"token",
",",
"}",
"api_path",
"=",
"'/v1/auth/{mount_point}/login'",
".",
"format",
"(",
... | Login using GitHub access token.
Supported methods:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param token: GitHub personal API token.
:type token: str | unicode
:param use_token: if True, uses the token in the response received from the auth request to set the "token"
attribute on the the :py:meth:`hvac.adapters.Adapter` instance under the _adapater Client attribute.
:type use_token: bool
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the login request.
:rtype: dict | [
"Login",
"using",
"GitHub",
"access",
"token",
"."
] | python | train |
bububa/pyTOP | pyTOP/fenxiao.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/fenxiao.py#L93-L102 | def get(self, session, **kwargs):
'''taobao.fenxiao.cooperation.get 获取供应商的合作关系信息
获取供应商的合作关系信息'''
request = TOPRequest('taobao.fenxiao.cooperation.get')
for k, v in kwargs.iteritems():
if k not in ('status', 'start_date', 'end_date', 'trade_type', 'page_no', 'page_size') and v==None: continue
request[k] = v
self.create(self.execute(request, session), fields=['total_results','cooperations'], models={'cooperations':Cooperation})
return self.cooperations | [
"def",
"get",
"(",
"self",
",",
"session",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.fenxiao.cooperation.get'",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"not",
"in",
"... | taobao.fenxiao.cooperation.get 获取供应商的合作关系信息
获取供应商的合作关系信息 | [
"taobao",
".",
"fenxiao",
".",
"cooperation",
".",
"get",
"获取供应商的合作关系信息",
"获取供应商的合作关系信息"
] | python | train |
erdewit/ib_insync | ib_insync/ib.py | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/ib.py#L1172-L1191 | def reqTickByTickData(
self, contract: Contract, tickType: str,
numberOfTicks: int = 0, ignoreSize: bool = False) -> Ticker:
"""
Subscribe to tick-by-tick data and return the Ticker that
holds the ticks in ticker.tickByTicks.
https://interactivebrokers.github.io/tws-api/tick_data.html
Args:
contract: Contract of interest.
tickType: One of 'Last', 'AllLast', 'BidAsk' or 'MidPoint'.
numberOfTicks: Number of ticks or 0 for unlimited.
ignoreSize: Ignore bid/ask ticks that only update the size.
"""
reqId = self.client.getReqId()
ticker = self.wrapper.startTicker(reqId, contract, tickType)
self.client.reqTickByTickData(
reqId, contract, tickType, numberOfTicks, ignoreSize)
return ticker | [
"def",
"reqTickByTickData",
"(",
"self",
",",
"contract",
":",
"Contract",
",",
"tickType",
":",
"str",
",",
"numberOfTicks",
":",
"int",
"=",
"0",
",",
"ignoreSize",
":",
"bool",
"=",
"False",
")",
"->",
"Ticker",
":",
"reqId",
"=",
"self",
".",
"clie... | Subscribe to tick-by-tick data and return the Ticker that
holds the ticks in ticker.tickByTicks.
https://interactivebrokers.github.io/tws-api/tick_data.html
Args:
contract: Contract of interest.
tickType: One of 'Last', 'AllLast', 'BidAsk' or 'MidPoint'.
numberOfTicks: Number of ticks or 0 for unlimited.
ignoreSize: Ignore bid/ask ticks that only update the size. | [
"Subscribe",
"to",
"tick",
"-",
"by",
"-",
"tick",
"data",
"and",
"return",
"the",
"Ticker",
"that",
"holds",
"the",
"ticks",
"in",
"ticker",
".",
"tickByTicks",
"."
] | python | train |
matthewdeanmartin/jiggle_version | build_utils.py | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/build_utils.py#L143-L170 | def execute_get_text(command): # type: (str) ->str
"""
Execute shell command and return stdout txt
:param command:
:return:
"""
try:
_ = subprocess.run
try:
completed = subprocess.run(
command,
check=True,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
except subprocess.CalledProcessError as cpe:
raise
else:
return completed.stdout.decode('utf-8') + completed.stderr.decode("utf-8")
except AttributeError:
try:
p = subprocess.Popen(command.split(" "), stdout=subprocess.PIPE)
out, err = p.communicate()
except subprocess.CalledProcessError as cpe:
raise
else:
return str(out) + str(err) | [
"def",
"execute_get_text",
"(",
"command",
")",
":",
"# type: (str) ->str",
"try",
":",
"_",
"=",
"subprocess",
".",
"run",
"try",
":",
"completed",
"=",
"subprocess",
".",
"run",
"(",
"command",
",",
"check",
"=",
"True",
",",
"shell",
"=",
"True",
",",... | Execute shell command and return stdout txt
:param command:
:return: | [
"Execute",
"shell",
"command",
"and",
"return",
"stdout",
"txt",
":",
"param",
"command",
":",
":",
"return",
":"
] | python | train |
ucsb-cs/submit | submit/models.py | https://github.com/ucsb-cs/submit/blob/92810c81255a4fc6bbebac1ac8aae856fd576ffe/submit/models.py#L625-L627 | def can_view(self, user):
"""Return whether or not `user` can view the submission."""
return user in self.group.users or self.project.can_view(user) | [
"def",
"can_view",
"(",
"self",
",",
"user",
")",
":",
"return",
"user",
"in",
"self",
".",
"group",
".",
"users",
"or",
"self",
".",
"project",
".",
"can_view",
"(",
"user",
")"
] | Return whether or not `user` can view the submission. | [
"Return",
"whether",
"or",
"not",
"user",
"can",
"view",
"the",
"submission",
"."
] | python | train |
xym-tool/xym | xym/xym.py | https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L237-L253 | def add_line_references(self, input_model):
"""
This function is a part of the model post-processing pipeline. For
each line in the module, it adds a reference to the line number in
the original draft/RFC from where the module line was extracted.
:param input_model: The YANG model to be processed
:return: Modified YANG model, where line numbers from the RFC/Draft
text file are added as comments at the end of each line in
the modified model
"""
output_model = []
for ln in input_model:
line_len = len(ln[0])
line_ref = ('// %4d' % ln[1]).rjust((self.max_line_len - line_len + 7), ' ')
new_line = '%s %s\n' % (ln[0].rstrip(' \r\n\t\f'), line_ref)
output_model.append([new_line, ln[1]])
return output_model | [
"def",
"add_line_references",
"(",
"self",
",",
"input_model",
")",
":",
"output_model",
"=",
"[",
"]",
"for",
"ln",
"in",
"input_model",
":",
"line_len",
"=",
"len",
"(",
"ln",
"[",
"0",
"]",
")",
"line_ref",
"=",
"(",
"'// %4d'",
"%",
"ln",
"[",
"1... | This function is a part of the model post-processing pipeline. For
each line in the module, it adds a reference to the line number in
the original draft/RFC from where the module line was extracted.
:param input_model: The YANG model to be processed
:return: Modified YANG model, where line numbers from the RFC/Draft
text file are added as comments at the end of each line in
the modified model | [
"This",
"function",
"is",
"a",
"part",
"of",
"the",
"model",
"post",
"-",
"processing",
"pipeline",
".",
"For",
"each",
"line",
"in",
"the",
"module",
"it",
"adds",
"a",
"reference",
"to",
"the",
"line",
"number",
"in",
"the",
"original",
"draft",
"/",
... | python | train |
bhmm/bhmm | bhmm/hidden/api.py | https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L44-L62 | def set_implementation(impl):
"""
Sets the implementation of this module
Parameters
----------
impl : str
One of ["python", "c"]
"""
global __impl__
if impl.lower() == 'python':
__impl__ = __IMPL_PYTHON__
elif impl.lower() == 'c':
__impl__ = __IMPL_C__
else:
import warnings
warnings.warn('Implementation '+impl+' is not known. Using the fallback python implementation.')
__impl__ = __IMPL_PYTHON__ | [
"def",
"set_implementation",
"(",
"impl",
")",
":",
"global",
"__impl__",
"if",
"impl",
".",
"lower",
"(",
")",
"==",
"'python'",
":",
"__impl__",
"=",
"__IMPL_PYTHON__",
"elif",
"impl",
".",
"lower",
"(",
")",
"==",
"'c'",
":",
"__impl__",
"=",
"__IMPL_... | Sets the implementation of this module
Parameters
----------
impl : str
One of ["python", "c"] | [
"Sets",
"the",
"implementation",
"of",
"this",
"module"
] | python | train |
nvbn/thefuck | thefuck/conf.py | https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/conf.py#L82-L89 | def _priority_from_env(self, val):
"""Gets priority pairs from env."""
for part in val.split(':'):
try:
rule, priority = part.split('=')
yield rule, int(priority)
except ValueError:
continue | [
"def",
"_priority_from_env",
"(",
"self",
",",
"val",
")",
":",
"for",
"part",
"in",
"val",
".",
"split",
"(",
"':'",
")",
":",
"try",
":",
"rule",
",",
"priority",
"=",
"part",
".",
"split",
"(",
"'='",
")",
"yield",
"rule",
",",
"int",
"(",
"pr... | Gets priority pairs from env. | [
"Gets",
"priority",
"pairs",
"from",
"env",
"."
] | python | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAData/data_resample.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_resample.py#L30-L201 | def QA_data_tick_resample_1min(tick, type_='1min', if_drop=True):
"""
tick 采样为 分钟数据
1. 仅使用将 tick 采样为 1 分钟数据
2. 仅测试过,与通达信 1 分钟数据达成一致
3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试
demo:
df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001',
start='2018-08-01 09:25:00',
end='2018-08-03 15:00:00')
df_min = QA_data_tick_resample_1min(df)
"""
tick = tick.assign(amount=tick.price * tick.vol)
resx = pd.DataFrame()
_dates = set(tick.date)
for date in sorted(list(_dates)):
_data = tick.loc[tick.date == date]
# morning min bar
_data1 = _data[time(9,
25):time(11,
30)].resample(
type_,
closed='left',
base=30,
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data1.columns = _data1.columns.droplevel(0)
# do fix on the first and last bar
# 某些股票某些日期没有集合竞价信息,譬如 002468 在 2017 年 6 月 5 日的数据
if len(_data.loc[time(9, 25):time(9, 25)]) > 0:
_data1.loc[time(9,
31):time(9,
31),
'open'] = _data1.loc[time(9,
26):time(9,
26),
'open'].values
_data1.loc[time(9,
31):time(9,
31),
'high'] = _data1.loc[time(9,
26):time(9,
31),
'high'].max()
_data1.loc[time(9,
31):time(9,
31),
'low'] = _data1.loc[time(9,
26):time(9,
31),
'low'].min()
_data1.loc[time(9,
31):time(9,
31),
'vol'] = _data1.loc[time(9,
26):time(9,
31),
'vol'].sum()
_data1.loc[time(9,
31):time(9,
31),
'amount'] = _data1.loc[time(9,
26):time(9,
31),
'amount'].sum()
# 通达信分笔数据有的有 11:30 数据,有的没有
if len(_data.loc[time(11, 30):time(11, 30)]) > 0:
_data1.loc[time(11,
30):time(11,
30),
'high'] = _data1.loc[time(11,
30):time(11,
31),
'high'].max()
_data1.loc[time(11,
30):time(11,
30),
'low'] = _data1.loc[time(11,
30):time(11,
31),
'low'].min()
_data1.loc[time(11,
30):time(11,
30),
'close'] = _data1.loc[time(11,
31):time(11,
31),
'close'].values
_data1.loc[time(11,
30):time(11,
30),
'vol'] = _data1.loc[time(11,
30):time(11,
31),
'vol'].sum()
_data1.loc[time(11,
30):time(11,
30),
'amount'] = _data1.loc[time(11,
30):time(11,
31),
'amount'].sum()
_data1 = _data1.loc[time(9, 31):time(11, 30)]
# afternoon min bar
_data2 = _data[time(13,
0):time(15,
0)].resample(
type_,
closed='left',
base=30,
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data2.columns = _data2.columns.droplevel(0)
# 沪市股票在 2018-08-20 起,尾盘 3 分钟集合竞价
if (pd.Timestamp(date) <
pd.Timestamp('2018-08-20')) and (tick.code.iloc[0][0] == '6'):
# 避免出现 tick 数据没有 1:00 的值
if len(_data.loc[time(13, 0):time(13, 0)]) > 0:
_data2.loc[time(15,
0):time(15,
0),
'high'] = _data2.loc[time(15,
0):time(15,
1),
'high'].max()
_data2.loc[time(15,
0):time(15,
0),
'low'] = _data2.loc[time(15,
0):time(15,
1),
'low'].min()
_data2.loc[time(15,
0):time(15,
0),
'close'] = _data2.loc[time(15,
1):time(15,
1),
'close'].values
else:
# 避免出现 tick 数据没有 15:00 的值
if len(_data.loc[time(13, 0):time(13, 0)]) > 0:
_data2.loc[time(15,
0):time(15,
0)] = _data2.loc[time(15,
1):time(15,
1)].values
_data2 = _data2.loc[time(13, 1):time(15, 0)]
resx = resx.append(_data1).append(_data2)
resx['vol'] = resx['vol'] * 100.0
resx['volume'] = resx['vol']
resx['type'] = '1min'
if if_drop:
resx = resx.dropna()
return resx.reset_index().drop_duplicates().set_index(['datetime', 'code']) | [
"def",
"QA_data_tick_resample_1min",
"(",
"tick",
",",
"type_",
"=",
"'1min'",
",",
"if_drop",
"=",
"True",
")",
":",
"tick",
"=",
"tick",
".",
"assign",
"(",
"amount",
"=",
"tick",
".",
"price",
"*",
"tick",
".",
"vol",
")",
"resx",
"=",
"pd",
".",
... | tick 采样为 分钟数据
1. 仅使用将 tick 采样为 1 分钟数据
2. 仅测试过,与通达信 1 分钟数据达成一致
3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试
demo:
df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001',
start='2018-08-01 09:25:00',
end='2018-08-03 15:00:00')
df_min = QA_data_tick_resample_1min(df) | [
"tick",
"采样为",
"分钟数据",
"1",
".",
"仅使用将",
"tick",
"采样为",
"1",
"分钟数据",
"2",
".",
"仅测试过,与通达信",
"1",
"分钟数据达成一致",
"3",
".",
"经测试,可以匹配",
"QA",
".",
"QA_fetch_get_stock_transaction",
"得到的数据,其他类型数据未测试",
"demo",
":",
"df",
"=",
"QA",
".",
"QA_fetch_get_stock_transactio... | python | train |
SHTOOLS/SHTOOLS | pyshtools/shclasses/shwindow.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L653-L712 | def coupling_matrix(self, lmax, nwin=None, weights=None, mode='full'):
"""
Return the coupling matrix of the first nwin tapers. This matrix
relates the global power spectrum to the expectation of the localized
multitaper spectrum.
Usage
-----
Mmt = x.coupling_matrix(lmax, [nwin, weights, mode])
Returns
-------
Mmt : ndarray, shape (lmax+lwin+1, lmax+1) or (lmax+1, lmax+1) or
(lmax-lwin+1, lmax+1)
Parameters
----------
lmax : int
Spherical harmonic bandwidth of the global power spectrum.
nwin : int, optional, default = x.nwin
Number of tapers used in the mutlitaper spectral analysis.
weights : ndarray, optional, default = x.weights
Taper weights used with the multitaper spectral analyses.
mode : str, opitonal, default = 'full'
'full' returns a biased output spectrum of size lmax+lwin+1. The
input spectrum is assumed to be zero for degrees l>lmax.
'same' returns a biased output spectrum with the same size
(lmax+1) as the input spectrum. The input spectrum is assumed to be
zero for degrees l>lmax.
'valid' returns a biased spectrum with size lmax-lwin+1. This
returns only that part of the biased spectrum that is not
influenced by the input spectrum beyond degree lmax.
"""
if weights is not None:
if nwin is not None:
if len(weights) != nwin:
raise ValueError(
'Length of weights must be equal to nwin. ' +
'len(weights) = {:d}, nwin = {:d}'.format(len(weights),
nwin))
else:
if len(weights) != self.nwin:
raise ValueError(
'Length of weights must be equal to nwin. ' +
'len(weights) = {:d}, nwin = {:d}'.format(len(weights),
self.nwin))
if mode == 'full':
return self._coupling_matrix(lmax, nwin=nwin, weights=weights)
elif mode == 'same':
cmatrix = self._coupling_matrix(lmax, nwin=nwin,
weights=weights)
return cmatrix[:lmax+1, :]
elif mode == 'valid':
cmatrix = self._coupling_matrix(lmax, nwin=nwin,
weights=weights)
return cmatrix[:lmax - self.lwin+1, :]
else:
raise ValueError("mode has to be 'full', 'same' or 'valid', not "
"{}".format(mode)) | [
"def",
"coupling_matrix",
"(",
"self",
",",
"lmax",
",",
"nwin",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"mode",
"=",
"'full'",
")",
":",
"if",
"weights",
"is",
"not",
"None",
":",
"if",
"nwin",
"is",
"not",
"None",
":",
"if",
"len",
"(",
... | Return the coupling matrix of the first nwin tapers. This matrix
relates the global power spectrum to the expectation of the localized
multitaper spectrum.
Usage
-----
Mmt = x.coupling_matrix(lmax, [nwin, weights, mode])
Returns
-------
Mmt : ndarray, shape (lmax+lwin+1, lmax+1) or (lmax+1, lmax+1) or
(lmax-lwin+1, lmax+1)
Parameters
----------
lmax : int
Spherical harmonic bandwidth of the global power spectrum.
nwin : int, optional, default = x.nwin
Number of tapers used in the mutlitaper spectral analysis.
weights : ndarray, optional, default = x.weights
Taper weights used with the multitaper spectral analyses.
mode : str, opitonal, default = 'full'
'full' returns a biased output spectrum of size lmax+lwin+1. The
input spectrum is assumed to be zero for degrees l>lmax.
'same' returns a biased output spectrum with the same size
(lmax+1) as the input spectrum. The input spectrum is assumed to be
zero for degrees l>lmax.
'valid' returns a biased spectrum with size lmax-lwin+1. This
returns only that part of the biased spectrum that is not
influenced by the input spectrum beyond degree lmax. | [
"Return",
"the",
"coupling",
"matrix",
"of",
"the",
"first",
"nwin",
"tapers",
".",
"This",
"matrix",
"relates",
"the",
"global",
"power",
"spectrum",
"to",
"the",
"expectation",
"of",
"the",
"localized",
"multitaper",
"spectrum",
"."
] | python | train |
adamchainz/django-mysql | django_mysql/models/handler.py | https://github.com/adamchainz/django-mysql/blob/967daa4245cf55c9bc5dc018e560f417c528916a/django_mysql/models/handler.py#L218-L231 | def _is_simple_query(cls, query):
"""
Inspect the internals of the Query and say if we think its WHERE clause
can be used in a HANDLER statement
"""
return (
not query.low_mark
and not query.high_mark
and not query.select
and not query.group_by
and not query.distinct
and not query.order_by
and len(query.alias_map) <= 1
) | [
"def",
"_is_simple_query",
"(",
"cls",
",",
"query",
")",
":",
"return",
"(",
"not",
"query",
".",
"low_mark",
"and",
"not",
"query",
".",
"high_mark",
"and",
"not",
"query",
".",
"select",
"and",
"not",
"query",
".",
"group_by",
"and",
"not",
"query",
... | Inspect the internals of the Query and say if we think its WHERE clause
can be used in a HANDLER statement | [
"Inspect",
"the",
"internals",
"of",
"the",
"Query",
"and",
"say",
"if",
"we",
"think",
"its",
"WHERE",
"clause",
"can",
"be",
"used",
"in",
"a",
"HANDLER",
"statement"
] | python | train |
Jaymon/prom | prom/model.py | https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L182-L192 | def create(cls, fields=None, **fields_kwargs):
"""
create an instance of cls with the passed in fields and set it into the db
fields -- dict -- field_name keys, with their respective values
**fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also
"""
# NOTE -- you cannot use hydrate/populate here because populate alters modified fields
instance = cls(fields, **fields_kwargs)
instance.save()
return instance | [
"def",
"create",
"(",
"cls",
",",
"fields",
"=",
"None",
",",
"*",
"*",
"fields_kwargs",
")",
":",
"# NOTE -- you cannot use hydrate/populate here because populate alters modified fields",
"instance",
"=",
"cls",
"(",
"fields",
",",
"*",
"*",
"fields_kwargs",
")",
"... | create an instance of cls with the passed in fields and set it into the db
fields -- dict -- field_name keys, with their respective values
**fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also | [
"create",
"an",
"instance",
"of",
"cls",
"with",
"the",
"passed",
"in",
"fields",
"and",
"set",
"it",
"into",
"the",
"db"
] | python | train |
Esri/ArcREST | src/arcrest/common/geometry.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/geometry.py#L137-L148 | def asDictionary(self):
""" returns the object as a python dictionary """
#
template = {"x" : self._x,
"y" : self._y,
"spatialReference" : self.spatialReference
}
if not self._z is None:
template['z'] = self._z
if not self._m is None:
template['z'] = self._m
return template | [
"def",
"asDictionary",
"(",
"self",
")",
":",
"#",
"template",
"=",
"{",
"\"x\"",
":",
"self",
".",
"_x",
",",
"\"y\"",
":",
"self",
".",
"_y",
",",
"\"spatialReference\"",
":",
"self",
".",
"spatialReference",
"}",
"if",
"not",
"self",
".",
"_z",
"i... | returns the object as a python dictionary | [
"returns",
"the",
"object",
"as",
"a",
"python",
"dictionary"
] | python | train |
inspirehep/harvesting-kit | harvestingkit/ftp_utils.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L229-L253 | def rmdir(self, foldername):
""" Delete a folder from the server.
:param foldername: the folder to be deleted.
:type foldername: string
"""
current_folder = self._ftp.pwd()
try:
self.cd(foldername)
except error_perm:
print('550 Delete operation failed folder %s '
'does not exist!' % (foldername,))
else:
self.cd(current_folder)
try:
self._ftp.rmd(foldername)
except error_perm: # folder not empty
self.cd(foldername)
contents = self.ls()
#delete the files
map(self._ftp.delete, contents[0])
#delete the subfolders
map(self.rmdir, contents[1])
self.cd(current_folder)
self._ftp.rmd(foldername) | [
"def",
"rmdir",
"(",
"self",
",",
"foldername",
")",
":",
"current_folder",
"=",
"self",
".",
"_ftp",
".",
"pwd",
"(",
")",
"try",
":",
"self",
".",
"cd",
"(",
"foldername",
")",
"except",
"error_perm",
":",
"print",
"(",
"'550 Delete operation failed fold... | Delete a folder from the server.
:param foldername: the folder to be deleted.
:type foldername: string | [
"Delete",
"a",
"folder",
"from",
"the",
"server",
"."
] | python | valid |
ruipgil/TrackToTrip | tracktotrip/similarity.py | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L113-L136 | def closest_point(a, b, p):
"""Finds closest point in a line segment
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to find in the segment
Returns:
(float, float): x and y coordinates of the closest point
"""
ap = [p[0]-a[0], p[1]-a[1]]
ab = [b[0]-a[0], b[1]-a[1]]
mag = float(ab[0]**2 + ab[1]**2)
proj = dot(ap, ab)
if mag ==0 :
dist = 0
else:
dist = proj / mag
if dist < 0:
return [a[0], a[1]]
elif dist > 1:
return [b[0], b[1]]
else:
return [a[0] + ab[0] * dist, a[1] + ab[1] * dist] | [
"def",
"closest_point",
"(",
"a",
",",
"b",
",",
"p",
")",
":",
"ap",
"=",
"[",
"p",
"[",
"0",
"]",
"-",
"a",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
"]",
"ab",
"=",
"[",
"b",
"[",
"0",
"]",
"-",
"a",
"[",
... | Finds closest point in a line segment
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to find in the segment
Returns:
(float, float): x and y coordinates of the closest point | [
"Finds",
"closest",
"point",
"in",
"a",
"line",
"segment"
] | python | train |
HewlettPackard/python-hpOneView | hpOneView/resources/servers/server_hardware.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/servers/server_hardware.py#L147-L164 | def get_ilo_sso_url(self, ip=None):
"""
Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface. If the server hardware is
unsupported, the resulting URL will not use SSO and the iLO web interface will prompt for credentials.
This is not supported on G7/iLO3 or earlier servers.
Args:
ip: IP address or host name of the server's iLO management processor
Returns:
URL
"""
uri = "{}/iloSsoUrl".format(self.data["uri"])
if ip:
uri = "{}?ip={}".format(uri, ip)
return self._helper.do_get(uri) | [
"def",
"get_ilo_sso_url",
"(",
"self",
",",
"ip",
"=",
"None",
")",
":",
"uri",
"=",
"\"{}/iloSsoUrl\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"\"uri\"",
"]",
")",
"if",
"ip",
":",
"uri",
"=",
"\"{}?ip={}\"",
".",
"format",
"(",
"uri",
",",
... | Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface. If the server hardware is
unsupported, the resulting URL will not use SSO and the iLO web interface will prompt for credentials.
This is not supported on G7/iLO3 or earlier servers.
Args:
ip: IP address or host name of the server's iLO management processor
Returns:
URL | [
"Retrieves",
"the",
"URL",
"to",
"launch",
"a",
"Single",
"Sign",
"-",
"On",
"(",
"SSO",
")",
"session",
"for",
"the",
"iLO",
"web",
"interface",
".",
"If",
"the",
"server",
"hardware",
"is",
"unsupported",
"the",
"resulting",
"URL",
"will",
"not",
"use"... | python | train |
saltstack/salt | salt/modules/win_service.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L320-L340 | def get_enabled():
'''
Return a list of enabled services. Enabled is defined as a service that is
marked to Auto Start.
Returns:
list: A list of enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
raw_services = _get_services()
services = set()
for service in raw_services:
if info(service['ServiceName'])['StartType'] in ['Auto']:
services.add(service['ServiceName'])
return sorted(services) | [
"def",
"get_enabled",
"(",
")",
":",
"raw_services",
"=",
"_get_services",
"(",
")",
"services",
"=",
"set",
"(",
")",
"for",
"service",
"in",
"raw_services",
":",
"if",
"info",
"(",
"service",
"[",
"'ServiceName'",
"]",
")",
"[",
"'StartType'",
"]",
"in... | Return a list of enabled services. Enabled is defined as a service that is
marked to Auto Start.
Returns:
list: A list of enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled | [
"Return",
"a",
"list",
"of",
"enabled",
"services",
".",
"Enabled",
"is",
"defined",
"as",
"a",
"service",
"that",
"is",
"marked",
"to",
"Auto",
"Start",
"."
] | python | train |
spacetelescope/drizzlepac | drizzlepac/hlautils/astrometric_utils.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L807-L855 | def build_self_reference(filename, clean_wcs=False):
""" This function creates a reference, undistorted WCS that can be used to
apply a correction to the WCS of the input file.
Parameters
----------
filename : str
Filename of image which will be corrected, and which will form the basis
of the undistorted WCS.
clean_wcs : bool
Specify whether or not to return the WCS object without any distortion
information, or any history of the original input image. This converts
the output from `utils.output_wcs()` into a pristine `~stwcs.wcsutils.HSTWCS` object.
Returns
-------
customwcs : `stwcs.wcsutils.HSTWCS`
HSTWCS object which contains the undistorted WCS representing the entire
field-of-view for the input image.
Examples
--------
This function can be used with the following syntax to apply a shift/rot/scale
change to the same image:
>>> import buildref
>>> from drizzlepac import updatehdr
>>> filename = "jce501erq_flc.fits"
>>> wcslin = buildref.build_self_reference(filename)
>>> updatehdr.updatewcs_with_shift(filename, wcslin, xsh=49.5694,
... ysh=19.2203, rot = 359.998, scale = 0.9999964)
"""
if 'sipwcs' in filename:
sciname = 'sipwcs'
else:
sciname = 'sci'
wcslin = build_reference_wcs([filename], sciname=sciname)
if clean_wcs:
wcsbase = wcslin.wcs
customwcs = build_hstwcs(wcsbase.crval[0], wcsbase.crval[1], wcsbase.crpix[0],
wcsbase.crpix[1], wcslin._naxis1, wcslin._naxis2,
wcslin.pscale, wcslin.orientat)
else:
customwcs = wcslin
return customwcs | [
"def",
"build_self_reference",
"(",
"filename",
",",
"clean_wcs",
"=",
"False",
")",
":",
"if",
"'sipwcs'",
"in",
"filename",
":",
"sciname",
"=",
"'sipwcs'",
"else",
":",
"sciname",
"=",
"'sci'",
"wcslin",
"=",
"build_reference_wcs",
"(",
"[",
"filename",
"... | This function creates a reference, undistorted WCS that can be used to
apply a correction to the WCS of the input file.
Parameters
----------
filename : str
Filename of image which will be corrected, and which will form the basis
of the undistorted WCS.
clean_wcs : bool
Specify whether or not to return the WCS object without any distortion
information, or any history of the original input image. This converts
the output from `utils.output_wcs()` into a pristine `~stwcs.wcsutils.HSTWCS` object.
Returns
-------
customwcs : `stwcs.wcsutils.HSTWCS`
HSTWCS object which contains the undistorted WCS representing the entire
field-of-view for the input image.
Examples
--------
This function can be used with the following syntax to apply a shift/rot/scale
change to the same image:
>>> import buildref
>>> from drizzlepac import updatehdr
>>> filename = "jce501erq_flc.fits"
>>> wcslin = buildref.build_self_reference(filename)
>>> updatehdr.updatewcs_with_shift(filename, wcslin, xsh=49.5694,
... ysh=19.2203, rot = 359.998, scale = 0.9999964) | [
"This",
"function",
"creates",
"a",
"reference",
"undistorted",
"WCS",
"that",
"can",
"be",
"used",
"to",
"apply",
"a",
"correction",
"to",
"the",
"WCS",
"of",
"the",
"input",
"file",
"."
] | python | train |
tylertreat/BigQuery-Python | bigquery/client.py | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1417-L1438 | def get_all_tables(self, dataset_id, project_id=None):
"""Retrieve a list of tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table data for.
project_id: str
Unique ``str`` identifying the BigQuery project contains the dataset
Returns
-------
A ``list`` with all table names
"""
tables_data = self._get_all_tables_for_dataset(dataset_id, project_id)
tables = []
for table in tables_data.get('tables', []):
table_name = table.get('tableReference', {}).get('tableId')
if table_name:
tables.append(table_name)
return tables | [
"def",
"get_all_tables",
"(",
"self",
",",
"dataset_id",
",",
"project_id",
"=",
"None",
")",
":",
"tables_data",
"=",
"self",
".",
"_get_all_tables_for_dataset",
"(",
"dataset_id",
",",
"project_id",
")",
"tables",
"=",
"[",
"]",
"for",
"table",
"in",
"tabl... | Retrieve a list of tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table data for.
project_id: str
Unique ``str`` identifying the BigQuery project contains the dataset
Returns
-------
A ``list`` with all table names | [
"Retrieve",
"a",
"list",
"of",
"tables",
"for",
"the",
"dataset",
"."
] | python | train |
taskcluster/taskcluster-client.py | taskcluster/utils.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/utils.py#L123-L136 | def dumpJson(obj, **kwargs):
""" Match JS's JSON.stringify. When using the default seperators,
base64 encoding JSON results in \n sequences in the output. Hawk
barfs in your face if you have that in the text"""
def handleDateAndBinaryForJs(x):
if six.PY3 and isinstance(x, six.binary_type):
x = x.decode()
if isinstance(x, datetime.datetime) or isinstance(x, datetime.date):
return stringDate(x)
else:
return x
d = json.dumps(obj, separators=(',', ':'), default=handleDateAndBinaryForJs, **kwargs)
assert '\n' not in d
return d | [
"def",
"dumpJson",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"handleDateAndBinaryForJs",
"(",
"x",
")",
":",
"if",
"six",
".",
"PY3",
"and",
"isinstance",
"(",
"x",
",",
"six",
".",
"binary_type",
")",
":",
"x",
"=",
"x",
".",
"decode",... | Match JS's JSON.stringify. When using the default seperators,
base64 encoding JSON results in \n sequences in the output. Hawk
barfs in your face if you have that in the text | [
"Match",
"JS",
"s",
"JSON",
".",
"stringify",
".",
"When",
"using",
"the",
"default",
"seperators",
"base64",
"encoding",
"JSON",
"results",
"in",
"\\",
"n",
"sequences",
"in",
"the",
"output",
".",
"Hawk",
"barfs",
"in",
"your",
"face",
"if",
"you",
"ha... | python | train |
log2timeline/plaso | plaso/engine/zeromq_queue.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/zeromq_queue.py#L334-L371 | def PopItem(self):
"""Pops an item off the queue.
If no ZeroMQ socket has been created, one will be created the first
time this method is called.
Returns:
object: item from the queue.
Raises:
KeyboardInterrupt: if the process is sent a KeyboardInterrupt while
popping an item.
QueueEmpty: if the queue is empty, and no item could be popped within the
queue timeout.
RuntimeError: if closed or terminate event is missing.
zmq.error.ZMQError: if a ZeroMQ error occurs.
"""
if not self._zmq_socket:
self._CreateZMQSocket()
if not self._closed_event or not self._terminate_event:
raise RuntimeError('Missing closed or terminate event.')
logger.debug(
'Pop on {0:s} queue, port {1:d}'.format(self.name, self.port))
last_retry_timestamp = time.time() + self.timeout_seconds
while not self._closed_event.is_set() or not self._terminate_event.is_set():
try:
return self._ReceiveItemOnActivity(self._zmq_socket)
except errors.QueueEmpty:
if time.time() > last_retry_timestamp:
raise
except KeyboardInterrupt:
self.Close(abort=True)
raise | [
"def",
"PopItem",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_zmq_socket",
":",
"self",
".",
"_CreateZMQSocket",
"(",
")",
"if",
"not",
"self",
".",
"_closed_event",
"or",
"not",
"self",
".",
"_terminate_event",
":",
"raise",
"RuntimeError",
"(",
... | Pops an item off the queue.
If no ZeroMQ socket has been created, one will be created the first
time this method is called.
Returns:
object: item from the queue.
Raises:
KeyboardInterrupt: if the process is sent a KeyboardInterrupt while
popping an item.
QueueEmpty: if the queue is empty, and no item could be popped within the
queue timeout.
RuntimeError: if closed or terminate event is missing.
zmq.error.ZMQError: if a ZeroMQ error occurs. | [
"Pops",
"an",
"item",
"off",
"the",
"queue",
"."
] | python | train |
twilio/twilio-python | twilio/rest/authy/v1/service/entity/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/authy/v1/service/entity/__init__.py#L327-L341 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EntityContext for this EntityInstance
:rtype: twilio.rest.authy.v1.service.entity.EntityContext
"""
if self._context is None:
self._context = EntityContext(
self._version,
service_sid=self._solution['service_sid'],
identity=self._solution['identity'],
)
return self._context | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"EntityContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"i... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EntityContext for this EntityInstance
:rtype: twilio.rest.authy.v1.service.entity.EntityContext | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train |
LuqueDaniel/pybooru | pybooru/api_moebooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_moebooru.py#L370-L378 | def wiki_revert(self, title, version):
"""Function to revert a specific wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page to update.
version (int): The version to revert to.
"""
params = {'title': title, 'version': version}
return self._get('wiki/revert', params, method='PUT') | [
"def",
"wiki_revert",
"(",
"self",
",",
"title",
",",
"version",
")",
":",
"params",
"=",
"{",
"'title'",
":",
"title",
",",
"'version'",
":",
"version",
"}",
"return",
"self",
".",
"_get",
"(",
"'wiki/revert'",
",",
"params",
",",
"method",
"=",
"'PUT... | Function to revert a specific wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page to update.
version (int): The version to revert to. | [
"Function",
"to",
"revert",
"a",
"specific",
"wiki",
"page",
"(",
"Requires",
"login",
")",
"(",
"UNTESTED",
")",
"."
] | python | train |
PyGithub/PyGithub | github/Repository.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/Repository.py#L2154-L2163 | def get_languages(self):
"""
:calls: `GET /repos/:owner/:repo/languages <http://developer.github.com/v3/repos>`_
:rtype: dict of string to integer
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/languages"
)
return data | [
"def",
"get_languages",
"(",
"self",
")",
":",
"headers",
",",
"data",
"=",
"self",
".",
"_requester",
".",
"requestJsonAndCheck",
"(",
"\"GET\"",
",",
"self",
".",
"url",
"+",
"\"/languages\"",
")",
"return",
"data"
] | :calls: `GET /repos/:owner/:repo/languages <http://developer.github.com/v3/repos>`_
:rtype: dict of string to integer | [
":",
"calls",
":",
"GET",
"/",
"repos",
"/",
":",
"owner",
"/",
":",
"repo",
"/",
"languages",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"repos",
">",
"_",
":",
"rtype",
":",
"dict",
"of",
"string",
"to",
"intege... | python | train |
knipknap/SpiffWorkflow | SpiffWorkflow/specs/Trigger.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Trigger.py#L97-L103 | def deserialize(cls, serializer, wf_spec, s_state, **kwargs):
"""
Deserializes the trigger using the provided serializer.
"""
return serializer.deserialize_trigger(wf_spec,
s_state,
**kwargs) | [
"def",
"deserialize",
"(",
"cls",
",",
"serializer",
",",
"wf_spec",
",",
"s_state",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"serializer",
".",
"deserialize_trigger",
"(",
"wf_spec",
",",
"s_state",
",",
"*",
"*",
"kwargs",
")"
] | Deserializes the trigger using the provided serializer. | [
"Deserializes",
"the",
"trigger",
"using",
"the",
"provided",
"serializer",
"."
] | python | valid |
esheldon/fitsio | fitsio/header.py | https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/header.py#L372-L438 | def _record2card(self, record):
"""
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello '
KEYSC = 'hello ' / a comment for string
KEYDC = 3.14159265358979 / a comment for pi
KEYLC = 323423432 / a comment for long
basically,
- 8 chars, left aligned, for the keyword name
- a space
- 20 chars for value, left aligned for strings, right aligned for
numbers
- if there is a comment, one space followed by / then another space
then the comment out to 80 chars
"""
name = record['name']
value = record['value']
v_isstring = isstring(value)
if name == 'COMMENT':
# card = 'COMMENT %s' % value
card = 'COMMENT %s' % value
elif name == 'CONTINUE':
card = 'CONTINUE %s' % value
elif name == 'HISTORY':
card = 'HISTORY %s' % value
else:
if len(name) > 8:
card = 'HIERARCH %s= ' % name
else:
card = '%-8s= ' % name[0:8]
# these may be string representations of data, or actual strings
if v_isstring:
value = str(value)
if len(value) > 0:
if value[0] != "'":
# this is a string representing a string header field
# make it look like it will look in the header
value = "'" + value + "'"
vstr = '%-20s' % value
else:
vstr = "%20s" % value
else:
vstr = "''"
else:
vstr = '%20s' % value
card += vstr
if 'comment' in record:
card += ' / %s' % record['comment']
if v_isstring and len(card) > 80:
card = card[0:79] + "'"
else:
card = card[0:80]
return card | [
"def",
"_record2card",
"(",
"self",
",",
"record",
")",
":",
"name",
"=",
"record",
"[",
"'name'",
"]",
"value",
"=",
"record",
"[",
"'value'",
"]",
"v_isstring",
"=",
"isstring",
"(",
"value",
")",
"if",
"name",
"==",
"'COMMENT'",
":",
"# card = 'COMMEN... | when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello '
KEYSC = 'hello ' / a comment for string
KEYDC = 3.14159265358979 / a comment for pi
KEYLC = 323423432 / a comment for long
basically,
- 8 chars, left aligned, for the keyword name
- a space
- 20 chars for value, left aligned for strings, right aligned for
numbers
- if there is a comment, one space followed by / then another space
then the comment out to 80 chars | [
"when",
"we",
"add",
"new",
"records",
"they",
"don",
"t",
"have",
"a",
"card",
"this",
"sort",
"of",
"fakes",
"it",
"up",
"similar",
"to",
"what",
"cfitsio",
"does",
"just",
"for",
"display",
"purposes",
".",
"e",
".",
"g",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/qos_mpls/map_/inexp_outexp/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/qos_mpls/map_/inexp_outexp/__init__.py#L131-L152 | def _set_in_exp(self, v, load=False):
"""
Setter method for in_exp, mapped from YANG variable /qos_mpls/map/inexp_outexp/in_exp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_exp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_exp() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("in_exp_in_values",in_exp.in_exp, yang_name="in-exp", rest_name="in-exp", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='in-exp-in-values', extensions={u'tailf-common': {u'info': u'Map Inexp value to Outexp value', u'cli-suppress-mode': None, u'cli-incomplete-no': None, u'cli-suppress-list-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'QosMplsInexpOutexpCallpoint'}}), is_container='list', yang_name="in-exp", rest_name="in-exp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Map Inexp value to Outexp value', u'cli-suppress-mode': None, u'cli-incomplete-no': None, u'cli-suppress-list-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'QosMplsInexpOutexpCallpoint'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mpls', defining_module='brocade-qos-mpls', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """in_exp must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("in_exp_in_values",in_exp.in_exp, yang_name="in-exp", rest_name="in-exp", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='in-exp-in-values', extensions={u'tailf-common': {u'info': u'Map Inexp value to Outexp value', u'cli-suppress-mode': None, u'cli-incomplete-no': None, u'cli-suppress-list-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'QosMplsInexpOutexpCallpoint'}}), is_container='list', yang_name="in-exp", rest_name="in-exp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Map Inexp value to Outexp value', u'cli-suppress-mode': None, u'cli-incomplete-no': None, u'cli-suppress-list-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'callpoint': u'QosMplsInexpOutexpCallpoint'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mpls', defining_module='brocade-qos-mpls', yang_type='list', is_config=True)""",
})
self.__in_exp = t
if hasattr(self, '_set'):
self._set() | [
"def",
"_set_in_exp",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | Setter method for in_exp, mapped from YANG variable /qos_mpls/map/inexp_outexp/in_exp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_exp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_exp() directly. | [
"Setter",
"method",
"for",
"in_exp",
"mapped",
"from",
"YANG",
"variable",
"/",
"qos_mpls",
"/",
"map",
"/",
"inexp_outexp",
"/",
"in_exp",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"... | python | train |
dailymuse/oz | oz/redis/__init__.py | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/redis/__init__.py#L12-L37 | def create_connection():
"""Sets up a redis configuration"""
global _cached_connection
settings = oz.settings
if settings["redis_cache_connections"] and _cached_connection != None:
return _cached_connection
else:
conn = redis.StrictRedis(
host=settings["redis_host"],
port=settings["redis_port"],
db=settings["redis_db"],
password=settings["redis_password"],
decode_responses=settings["redis_decode_responses"],
ssl=settings["redis_use_ssl"],
ssl_keyfile=settings["redis_ssl_keyfile"],
ssl_certfile=settings["redis_ssl_certfile"],
ssl_cert_reqs=settings["redis_ssl_cert_reqs"],
ssl_ca_certs=settings["redis_ssl_ca_certs"]
)
if settings["redis_cache_connections"]:
_cached_connection = conn
return conn | [
"def",
"create_connection",
"(",
")",
":",
"global",
"_cached_connection",
"settings",
"=",
"oz",
".",
"settings",
"if",
"settings",
"[",
"\"redis_cache_connections\"",
"]",
"and",
"_cached_connection",
"!=",
"None",
":",
"return",
"_cached_connection",
"else",
":",... | Sets up a redis configuration | [
"Sets",
"up",
"a",
"redis",
"configuration"
] | python | train |
obriencj/python-javatools | javatools/opcodes.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/opcodes.py#L231-L255 | def disassemble(bytecode):
"""
Generator. Disassembles Java bytecode into a sequence of (offset,
code, args) tuples
:type bytecode: bytes
"""
offset = 0
end = len(bytecode)
while offset < end:
orig_offset = offset
code = bytecode[offset]
if not isinstance(code, int): # Py3
code = ord(code)
offset += 1
args = tuple()
fmt = get_arg_format(code)
if fmt:
args, offset = fmt(bytecode, offset)
yield (orig_offset, code, args) | [
"def",
"disassemble",
"(",
"bytecode",
")",
":",
"offset",
"=",
"0",
"end",
"=",
"len",
"(",
"bytecode",
")",
"while",
"offset",
"<",
"end",
":",
"orig_offset",
"=",
"offset",
"code",
"=",
"bytecode",
"[",
"offset",
"]",
"if",
"not",
"isinstance",
"(",... | Generator. Disassembles Java bytecode into a sequence of (offset,
code, args) tuples
:type bytecode: bytes | [
"Generator",
".",
"Disassembles",
"Java",
"bytecode",
"into",
"a",
"sequence",
"of",
"(",
"offset",
"code",
"args",
")",
"tuples",
":",
"type",
"bytecode",
":",
"bytes"
] | python | train |
numenta/nupic | src/nupic/algorithms/backtracking_tm.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1927-L1973 | def _inferPhase1(self, activeColumns, useStartCells):
"""
Update the inference active state from the last set of predictions
and the current bottom-up.
This looks at:
- ``infPredictedState['t-1']``
This modifies:
- ``infActiveState['t']``
:param activeColumns: (list) active bottom-ups
:param useStartCells: (bool) If true, ignore previous predictions and simply
turn on the start cells in the active columns
:returns: (bool) True if the current input was sufficiently predicted, OR if
we started over on startCells. False indicates that the current input
was NOT predicted, and we are now bursting on most columns.
"""
# Init to zeros to start
self.infActiveState['t'].fill(0)
# Phase 1 - turn on predicted cells in each column receiving bottom-up
# If we are following a reset, activate only the start cell in each
# column that has bottom-up
numPredictedColumns = 0
if useStartCells:
for c in activeColumns:
self.infActiveState['t'][c, 0] = 1
# else, turn on any predicted cells in each column. If there are none, then
# turn on all cells (burst the column)
else:
for c in activeColumns:
predictingCells = numpy.where(self.infPredictedState['t-1'][c] == 1)[0]
numPredictingCells = len(predictingCells)
if numPredictingCells > 0:
self.infActiveState['t'][c, predictingCells] = 1
numPredictedColumns += 1
else:
self.infActiveState['t'][c, :] = 1 # whole column bursts
# Did we predict this input well enough?
if useStartCells or numPredictedColumns >= 0.50 * len(activeColumns):
return True
else:
return False | [
"def",
"_inferPhase1",
"(",
"self",
",",
"activeColumns",
",",
"useStartCells",
")",
":",
"# Init to zeros to start",
"self",
".",
"infActiveState",
"[",
"'t'",
"]",
".",
"fill",
"(",
"0",
")",
"# Phase 1 - turn on predicted cells in each column receiving bottom-up",
"#... | Update the inference active state from the last set of predictions
and the current bottom-up.
This looks at:
- ``infPredictedState['t-1']``
This modifies:
- ``infActiveState['t']``
:param activeColumns: (list) active bottom-ups
:param useStartCells: (bool) If true, ignore previous predictions and simply
turn on the start cells in the active columns
:returns: (bool) True if the current input was sufficiently predicted, OR if
we started over on startCells. False indicates that the current input
was NOT predicted, and we are now bursting on most columns. | [
"Update",
"the",
"inference",
"active",
"state",
"from",
"the",
"last",
"set",
"of",
"predictions",
"and",
"the",
"current",
"bottom",
"-",
"up",
"."
] | python | valid |
mnooner256/pyqrcode | pyqrcode/builder.py | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1107-L1241 | def _svg(code, version, file, scale=1, module_color='#000', background=None,
quiet_zone=4, xmldecl=True, svgns=True, title=None, svgclass='pyqrcode',
lineclass='pyqrline', omithw=False, debug=False):
"""This function writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line. The file parameter is used to
specify where to write the document to. It can either be a writable (binary)
stream or a file path. The scale parameter is sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code to small to be read efficiently.
Increasing the scale will make the code larger. This method will accept
fractional scales (e.g. 2.5).
:param module_color: Color of the QR code (default: ``#000`` (black))
:param background: Optional background color.
(default: ``None`` (no background))
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
:param xmldecl: Inidcates if the XML declaration header should be written
(default: ``True``)
:param svgns: Indicates if the SVG namespace should be written
(default: ``True``)
:param title: Optional title of the generated SVG document.
:param svgclass: The CSS class of the SVG document
(if set to ``None``, the SVG element won't have a class).
:param lineclass: The CSS class of the path element
(if set to ``None``, the path won't have a class).
:param omithw: Indicates if width and height attributes should be
omitted (default: ``False``). If these attributes are omitted,
a ``viewBox`` attribute will be added to the document.
:param debug: Inidicates if errors in the QR code should be added to the
output (default: ``False``).
"""
from functools import partial
from xml.sax.saxutils import quoteattr
def write_unicode(write_meth, unicode_str):
"""\
Encodes the provided string into UTF-8 and writes the result using
the `write_meth`.
"""
write_meth(unicode_str.encode('utf-8'))
def line(x, y, length, relative):
"""Returns coordinates to draw a line with the provided length.
"""
return '{0}{1} {2}h{3}'.format(('m' if relative else 'M'), x, y, length)
def errline(col_number, row_number):
"""Returns the coordinates to draw an error bit.
"""
# Debug path uses always absolute coordinates
# .5 == stroke / 2
return line(col_number + quiet_zone, row_number + quiet_zone + .5, 1, False)
f, autoclose = _get_writable(file, 'wb')
write = partial(write_unicode, f.write)
write_bytes = f.write
# Write the document header
if xmldecl:
write_bytes(b'<?xml version="1.0" encoding="UTF-8"?>\n')
write_bytes(b'<svg')
if svgns:
write_bytes(b' xmlns="http://www.w3.org/2000/svg"')
size = tables.version_size[version] * scale + (2 * quiet_zone * scale)
if not omithw:
write(' height="{0}" width="{0}"'.format(size))
else:
write(' viewBox="0 0 {0} {0}"'.format(size))
if svgclass is not None:
write_bytes(b' class=')
write(quoteattr(svgclass))
write_bytes(b'>')
if title is not None:
write('<title>{0}</title>'.format(title))
# Draw a background rectangle if necessary
if background is not None:
write('<path fill="{1}" d="M0 0h{0}v{0}h-{0}z"/>'
.format(size, background))
write_bytes(b'<path')
if scale != 1:
write(' transform="scale({0})"'.format(scale))
if module_color is not None:
write_bytes(b' stroke=')
write(quoteattr(module_color))
if lineclass is not None:
write_bytes(b' class=')
write(quoteattr(lineclass))
write_bytes(b' d="')
# Used to keep track of unknown/error coordinates.
debug_path = ''
# Current pen pointer position
x, y = -quiet_zone, quiet_zone - .5 # .5 == stroke-width / 2
wrote_bit = False
# Loop through each row of the code
for rnumber, row in enumerate(code):
start_column = 0 # Reset the starting column number
coord = '' # Reset row coordinates
y += 1 # Pen position on y-axis
length = 0 # Reset line length
# Examine every bit in the row
for colnumber, bit in enumerate(row):
if bit == 1:
length += 1
else:
if length:
x = start_column - x
coord += line(x, y, length, relative=wrote_bit)
x = start_column + length
y = 0 # y-axis won't change unless the row changes
length = 0
wrote_bit = True
start_column = colnumber + 1
if debug and bit != 0:
debug_path += errline(colnumber, rnumber)
if length:
x = start_column - x
coord += line(x, y, length, relative=wrote_bit)
x = start_column + length
wrote_bit = True
write(coord)
# Close path
write_bytes(b'"/>')
if debug and debug_path:
write_bytes(b'<path')
if scale != 1:
write(' transform="scale({0})"'.format(scale))
write(' class="pyqrerr" stroke="red" d="{0}"/>'.format(debug_path))
# Close document
write_bytes(b'</svg>\n')
if autoclose:
f.close() | [
"def",
"_svg",
"(",
"code",
",",
"version",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"'#000'",
",",
"background",
"=",
"None",
",",
"quiet_zone",
"=",
"4",
",",
"xmldecl",
"=",
"True",
",",
"svgns",
"=",
"True",
",",
"title",
... | This function writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line. The file parameter is used to
specify where to write the document to. It can either be a writable (binary)
stream or a file path. The scale parameter is sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code to small to be read efficiently.
Increasing the scale will make the code larger. This method will accept
fractional scales (e.g. 2.5).
:param module_color: Color of the QR code (default: ``#000`` (black))
:param background: Optional background color.
(default: ``None`` (no background))
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
:param xmldecl: Inidcates if the XML declaration header should be written
(default: ``True``)
:param svgns: Indicates if the SVG namespace should be written
(default: ``True``)
:param title: Optional title of the generated SVG document.
:param svgclass: The CSS class of the SVG document
(if set to ``None``, the SVG element won't have a class).
:param lineclass: The CSS class of the path element
(if set to ``None``, the path won't have a class).
:param omithw: Indicates if width and height attributes should be
omitted (default: ``False``). If these attributes are omitted,
a ``viewBox`` attribute will be added to the document.
:param debug: Inidicates if errors in the QR code should be added to the
output (default: ``False``). | [
"This",
"function",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"SVG",
"document",
".",
"The",
"code",
"is",
"drawn",
"by",
"drawing",
"only",
"the",
"modules",
"corresponding",
"to",
"a",
"1",
".",
"They",
"are",
"drawn",
"using",
"a",
"line",
"... | python | train |
resync/resync | resync/client.py | https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/client.py#L799-L830 | def log_status(self, in_sync=True, incremental=False, audit=False,
same=None, created=0, updated=0, deleted=0, to_delete=0):
"""Write log message regarding status in standard form.
Split this off so all messages from baseline/audit/incremental
are written in a consistent form.
"""
if (audit):
words = {'created': 'to create',
'updated': 'to update',
'deleted': 'to delete'}
else:
words = {'created': 'created',
'updated': 'updated',
'deleted': 'deleted'}
if in_sync:
# status rather than action
status = "NO CHANGES" if incremental else "IN SYNC"
else:
if audit:
status = "NOT IN SYNC"
elif (to_delete > deleted):
# will need --delete
status = "PART APPLIED" if incremental else"PART SYNCED"
words['deleted'] = 'to delete (--delete)'
deleted = to_delete
else:
status = "CHANGES APPLIED" if incremental else "SYNCED"
same = "" if (same is None) else ("same=%d, " % same)
self.logger.warning("Status: %15s (%s%s=%d, %s=%d, %s=%d)" %
(status, same, words['created'], created,
words['updated'], updated, words['deleted'], deleted)) | [
"def",
"log_status",
"(",
"self",
",",
"in_sync",
"=",
"True",
",",
"incremental",
"=",
"False",
",",
"audit",
"=",
"False",
",",
"same",
"=",
"None",
",",
"created",
"=",
"0",
",",
"updated",
"=",
"0",
",",
"deleted",
"=",
"0",
",",
"to_delete",
"... | Write log message regarding status in standard form.
Split this off so all messages from baseline/audit/incremental
are written in a consistent form. | [
"Write",
"log",
"message",
"regarding",
"status",
"in",
"standard",
"form",
"."
] | python | train |
sci-bots/svg-model | svg_model/data_frame.py | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/data_frame.py#L11-L44 | def get_shape_areas(df_shapes, shape_i_columns, signed=False):
'''
Return a `pandas.Series` indexed by `shape_i_columns` (i.e., each entry
corresponds to a single shape/polygon), containing the following columns
the area of each shape.
If `signed=True`, a positive area value corresponds to a clockwise loop,
whereas a negative area value corresponds to a counter-clockwise loop.
'''
# Make a copy of the SVG data frame since we need to add columns to it.
df_i = df_shapes.copy()
df_i['vertex_count'] = (df_i.groupby(shape_i_columns)['x']
.transform('count'))
df_i['area_a'] = df_i.x
df_i['area_b'] = df_i.y
# Vector form of [Shoelace formula][1].
#
# [1]: http://en.wikipedia.org/wiki/Shoelace_formula
df_i.loc[df_i.vertex_i == df_i.vertex_count - 1, 'area_a'] *= df_i.loc[df_i.vertex_i == 0, 'y'].values
df_i.loc[df_i.vertex_i < df_i.vertex_count - 1, 'area_a'] *= df_i.loc[df_i.vertex_i > 0, 'y'].values
df_i.loc[df_i.vertex_i == df_i.vertex_count - 1, 'area_b'] *= df_i.loc[df_i.vertex_i == 0, 'x'].values
df_i.loc[df_i.vertex_i < df_i.vertex_count - 1, 'area_b'] *= df_i.loc[df_i.vertex_i > 0, 'x'].values
area_components = df_i.groupby(shape_i_columns)[['area_a', 'area_b']].sum()
shape_areas = .5 * (area_components['area_b'] - area_components['area_a'])
if not signed:
shape_areas.name = 'area'
return shape_areas.abs()
else:
shape_areas.name = 'signed_area'
return shape_areas | [
"def",
"get_shape_areas",
"(",
"df_shapes",
",",
"shape_i_columns",
",",
"signed",
"=",
"False",
")",
":",
"# Make a copy of the SVG data frame since we need to add columns to it.",
"df_i",
"=",
"df_shapes",
".",
"copy",
"(",
")",
"df_i",
"[",
"'vertex_count'",
"]",
"... | Return a `pandas.Series` indexed by `shape_i_columns` (i.e., each entry
corresponds to a single shape/polygon), containing the following columns
the area of each shape.
If `signed=True`, a positive area value corresponds to a clockwise loop,
whereas a negative area value corresponds to a counter-clockwise loop. | [
"Return",
"a",
"pandas",
".",
"Series",
"indexed",
"by",
"shape_i_columns",
"(",
"i",
".",
"e",
".",
"each",
"entry",
"corresponds",
"to",
"a",
"single",
"shape",
"/",
"polygon",
")",
"containing",
"the",
"following",
"columns",
"the",
"area",
"of",
"each"... | python | train |
tompollard/tableone | tableone.py | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L311-L332 | def _tukey(self,x,threshold):
"""
Count outliers according to Tukey's rule.
Where Q1 is the lower quartile and Q3 is the upper quartile,
an outlier is an observation outside of the range:
[Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)]
k = 1.5 indicates an outlier
k = 3.0 indicates an outlier that is "far out"
"""
vals = x.values[~np.isnan(x.values)]
try:
q1, q3 = np.percentile(vals, [25, 75])
iqr = q3 - q1
low_bound = q1 - (iqr * threshold)
high_bound = q3 + (iqr * threshold)
outliers = np.where((vals > high_bound) | (vals < low_bound))
except:
outliers = []
return outliers | [
"def",
"_tukey",
"(",
"self",
",",
"x",
",",
"threshold",
")",
":",
"vals",
"=",
"x",
".",
"values",
"[",
"~",
"np",
".",
"isnan",
"(",
"x",
".",
"values",
")",
"]",
"try",
":",
"q1",
",",
"q3",
"=",
"np",
".",
"percentile",
"(",
"vals",
",",... | Count outliers according to Tukey's rule.
Where Q1 is the lower quartile and Q3 is the upper quartile,
an outlier is an observation outside of the range:
[Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)]
k = 1.5 indicates an outlier
k = 3.0 indicates an outlier that is "far out" | [
"Count",
"outliers",
"according",
"to",
"Tukey",
"s",
"rule",
"."
] | python | train |
Workiva/furious | furious/async.py | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L263-L268 | def set_execution_context(self, execution_context):
"""Set the ExecutionContext this async is executing under."""
if self._execution_context:
raise errors.AlreadyInContextError
self._execution_context = execution_context | [
"def",
"set_execution_context",
"(",
"self",
",",
"execution_context",
")",
":",
"if",
"self",
".",
"_execution_context",
":",
"raise",
"errors",
".",
"AlreadyInContextError",
"self",
".",
"_execution_context",
"=",
"execution_context"
] | Set the ExecutionContext this async is executing under. | [
"Set",
"the",
"ExecutionContext",
"this",
"async",
"is",
"executing",
"under",
"."
] | python | train |
salu133445/pypianoroll | pypianoroll/multitrack.py | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L830-L884 | def save(self, filename, compressed=True):
"""
Save the multitrack pianoroll to a (compressed) npz file, which can be
later loaded by :meth:`pypianoroll.Multitrack.load`.
Notes
-----
To reduce the file size, the pianorolls are first converted to instances
of scipy.sparse.csc_matrix, whose component arrays are then collected
and saved to a npz file.
Parameters
----------
filename : str
The name of the npz file to which the mulitrack pianoroll is saved.
compressed : bool
True to save to a compressed npz file. False to save to an
uncompressed npz file. Defaults to True.
"""
def update_sparse(target_dict, sparse_matrix, name):
"""Turn `sparse_matrix` into a scipy.sparse.csc_matrix and update
its component arrays to the `target_dict` with key as `name`
suffixed with its component type string."""
csc = csc_matrix(sparse_matrix)
target_dict[name+'_csc_data'] = csc.data
target_dict[name+'_csc_indices'] = csc.indices
target_dict[name+'_csc_indptr'] = csc.indptr
target_dict[name+'_csc_shape'] = csc.shape
self.check_validity()
array_dict = {'tempo': self.tempo}
info_dict = {'beat_resolution': self.beat_resolution,
'name': self.name}
if self.downbeat is not None:
array_dict['downbeat'] = self.downbeat
for idx, track in enumerate(self.tracks):
update_sparse(array_dict, track.pianoroll,
'pianoroll_{}'.format(idx))
info_dict[str(idx)] = {'program': track.program,
'is_drum': track.is_drum,
'name': track.name}
if not filename.endswith('.npz'):
filename += '.npz'
if compressed:
np.savez_compressed(filename, **array_dict)
else:
np.savez(filename, **array_dict)
compression = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED
with zipfile.ZipFile(filename, 'a') as zip_file:
zip_file.writestr('info.json', json.dumps(info_dict), compression) | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"compressed",
"=",
"True",
")",
":",
"def",
"update_sparse",
"(",
"target_dict",
",",
"sparse_matrix",
",",
"name",
")",
":",
"\"\"\"Turn `sparse_matrix` into a scipy.sparse.csc_matrix and update\n its component... | Save the multitrack pianoroll to a (compressed) npz file, which can be
later loaded by :meth:`pypianoroll.Multitrack.load`.
Notes
-----
To reduce the file size, the pianorolls are first converted to instances
of scipy.sparse.csc_matrix, whose component arrays are then collected
and saved to a npz file.
Parameters
----------
filename : str
The name of the npz file to which the mulitrack pianoroll is saved.
compressed : bool
True to save to a compressed npz file. False to save to an
uncompressed npz file. Defaults to True. | [
"Save",
"the",
"multitrack",
"pianoroll",
"to",
"a",
"(",
"compressed",
")",
"npz",
"file",
"which",
"can",
"be",
"later",
"loaded",
"by",
":",
"meth",
":",
"pypianoroll",
".",
"Multitrack",
".",
"load",
"."
] | python | train |
awslabs/serverless-application-model | samtranslator/plugins/policies/policy_templates_plugin.py | https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/policies/policy_templates_plugin.py#L31-L78 | def on_before_transform_resource(self, logical_id, resource_type, resource_properties):
"""
Hook method that gets called before "each" SAM resource gets processed
:param string logical_id: Logical ID of the resource being processed
:param string resource_type: Type of the resource being processed
:param dict resource_properties: Properties of the resource
:return: Nothing
"""
if not self._is_supported(resource_type):
return
function_policies = FunctionPolicies(resource_properties, self._policy_template_processor)
if len(function_policies) == 0:
# No policies to process
return
result = []
for policy_entry in function_policies.get():
if policy_entry.type is not PolicyTypes.POLICY_TEMPLATE:
# If we don't know the type, skip processing and pass to result as is.
result.append(policy_entry.data)
continue
# We are processing policy templates. We know they have a particular structure:
# {"templateName": { parameter_values_dict }}
template_data = policy_entry.data
template_name = list(template_data.keys())[0]
template_parameters = list(template_data.values())[0]
try:
# 'convert' will return a list of policy statements
result.append(self._policy_template_processor.convert(template_name, template_parameters))
except InsufficientParameterValues as ex:
# Exception's message will give lot of specific details
raise InvalidResourceException(logical_id, str(ex))
except InvalidParameterValues:
raise InvalidResourceException(logical_id,
"Must specify valid parameter values for policy template '{}'"
.format(template_name))
# Save the modified policies list to the input
resource_properties[FunctionPolicies.POLICIES_PROPERTY_NAME] = result | [
"def",
"on_before_transform_resource",
"(",
"self",
",",
"logical_id",
",",
"resource_type",
",",
"resource_properties",
")",
":",
"if",
"not",
"self",
".",
"_is_supported",
"(",
"resource_type",
")",
":",
"return",
"function_policies",
"=",
"FunctionPolicies",
"(",... | Hook method that gets called before "each" SAM resource gets processed
:param string logical_id: Logical ID of the resource being processed
:param string resource_type: Type of the resource being processed
:param dict resource_properties: Properties of the resource
:return: Nothing | [
"Hook",
"method",
"that",
"gets",
"called",
"before",
"each",
"SAM",
"resource",
"gets",
"processed"
] | python | train |
Nic30/hwtGraph | hwtGraph/elk/fromHwt/flattenPorts.py | https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/fromHwt/flattenPorts.py#L18-L26 | def _flattenPortsSide(side: List[LNode]) -> List[LNode]:
"""
Flatten hierarchical ports on node side
"""
new_side = []
for i in side:
for new_p in flattenPort(i):
new_side.append(new_p)
return new_side | [
"def",
"_flattenPortsSide",
"(",
"side",
":",
"List",
"[",
"LNode",
"]",
")",
"->",
"List",
"[",
"LNode",
"]",
":",
"new_side",
"=",
"[",
"]",
"for",
"i",
"in",
"side",
":",
"for",
"new_p",
"in",
"flattenPort",
"(",
"i",
")",
":",
"new_side",
".",
... | Flatten hierarchical ports on node side | [
"Flatten",
"hierarchical",
"ports",
"on",
"node",
"side"
] | python | train |
jstitch/MambuPy | MambuPy/rest/mambuclient.py | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuclient.py#L41-L109 | def preprocess(self):
"""Preprocessing.
Flattens the object. Important data comes on the 'client'
dictionary inside of the response. Instead, every element of the
'client' dictionary is taken out to the main attrs dictionary.
Removes repeated chars from firstName, middleName and lastName
fields. Adds a firstLastName and secondLastName fields for
clients using more than one last name.
Adds a 'name' field joining all names in to one string. IMHO
Mambu does an awful job with names. Besides, this is useful on
loan accounts. They get a 'holder' field added somewhere, which
may be an individual client, or a group. So to get the holder
name, you just access the 'holder'['name']. No matter if you
have a client loan or a group loan, you get the name of the
holder.
Creates and 'address' field that holds the very first address on
the addresses field, to ease the use of the
perhaps-current-or-most-important address of the client.
Creates a field for each documentId type with the value of the
documentId, to ease the use of docuemnt IDs. That way if you
have a document Id named 'CURP', then you access it directly via
the 'CURP' field, instead of going all the way through the
idDocuments field.
"""
super(MambuClient,self).preprocess()
try:
for k,v in self['client'].items():
self[k] = v
del(self.attrs['client'])
except Exception as e:
pass
try:
self['firstName'] = scrc(self['firstName'], " ").strip()
except Exception as e:
self['firstName'] = ""
try:
self['middleName'] = scrc(self['middleName'], " ").strip()
except Exception as ex:
self['middleName'] = ""
self['givenName'] = scrc(self["firstName"] + ((" " + self["middleName"]) if self["middleName"] != "" else ""), " ").strip()
self['lastName'] = scrc(self['lastName'], " ").strip()
self['firstLastName'] = " ".join(self['lastName'].split(" ")[:-1]) if len(self['lastName'].split(" ")) > 1 else self['lastName']
self['secondLastName'] = " ".join(self['lastName'].split(" ")[-1:]) if len(self['lastName'].split(" ")) > 1 else ""
self['name'] = scrc("%s %s" % (self['givenName'], self['lastName']), " ").strip()
self['address'] = {}
try:
for name,item in self['addresses'][0].items():
try:
self['addresses'][0][name] = item.strip()
self['address'][name] = item.strip()
except AttributeError:
pass
except (KeyError, IndexError):
pass
try:
for idDoc in self['idDocuments']:
self[idDoc['documentType']] = idDoc['documentId']
except KeyError:
pass | [
"def",
"preprocess",
"(",
"self",
")",
":",
"super",
"(",
"MambuClient",
",",
"self",
")",
".",
"preprocess",
"(",
")",
"try",
":",
"for",
"k",
",",
"v",
"in",
"self",
"[",
"'client'",
"]",
".",
"items",
"(",
")",
":",
"self",
"[",
"k",
"]",
"=... | Preprocessing.
Flattens the object. Important data comes on the 'client'
dictionary inside of the response. Instead, every element of the
'client' dictionary is taken out to the main attrs dictionary.
Removes repeated chars from firstName, middleName and lastName
fields. Adds a firstLastName and secondLastName fields for
clients using more than one last name.
Adds a 'name' field joining all names in to one string. IMHO
Mambu does an awful job with names. Besides, this is useful on
loan accounts. They get a 'holder' field added somewhere, which
may be an individual client, or a group. So to get the holder
name, you just access the 'holder'['name']. No matter if you
have a client loan or a group loan, you get the name of the
holder.
Creates and 'address' field that holds the very first address on
the addresses field, to ease the use of the
perhaps-current-or-most-important address of the client.
Creates a field for each documentId type with the value of the
documentId, to ease the use of docuemnt IDs. That way if you
have a document Id named 'CURP', then you access it directly via
the 'CURP' field, instead of going all the way through the
idDocuments field. | [
"Preprocessing",
"."
] | python | train |
saltstack/salt | salt/modules/boto_vpc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2116-L2181 | def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None,
gateway_id=None, instance_id=None, interface_id=None, tags=None,
region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None):
'''
Checks if a route exists.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test'
'''
if not any((route_table_name, route_table_id)):
raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.')
if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)):
raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, '
'interface id or VPC peering connection id.')
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if route_table_id:
filter_parameters['route_table_ids'] = [route_table_id]
if route_table_name:
filter_parameters['filters']['tag:Name'] = route_table_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
route_tables = conn.get_all_route_tables(**filter_parameters)
if len(route_tables) != 1:
raise SaltInvocationError('Found more than one route table.')
route_check = {'destination_cidr_block': destination_cidr_block,
'gateway_id': gateway_id,
'instance_id': instance_id,
'interface_id': interface_id,
'vpc_peering_connection_id': vpc_peering_connection_id
}
for route_match in route_tables[0].routes:
route_dict = {'destination_cidr_block': route_match.destination_cidr_block,
'gateway_id': route_match.gateway_id,
'instance_id': route_match.instance_id,
'interface_id': route_match.interface_id,
'vpc_peering_connection_id': vpc_peering_connection_id
}
route_comp = set(route_dict.items()) ^ set(route_check.items())
if not route_comp:
log.info('Route %s exists.', destination_cidr_block)
return {'exists': True}
log.warning('Route %s does not exist.', destination_cidr_block)
return {'exists': False}
except BotoServerError as e:
return {'error': __utils__['boto.get_error'](e)} | [
"def",
"route_exists",
"(",
"destination_cidr_block",
",",
"route_table_name",
"=",
"None",
",",
"route_table_id",
"=",
"None",
",",
"gateway_id",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"interface_id",
"=",
"None",
",",
"tags",
"=",
"None",
",",
... | Checks if a route exists.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' | [
"Checks",
"if",
"a",
"route",
"exists",
"."
] | python | train |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L4756-L4765 | def libvlc_media_list_event_manager(p_ml):
'''Get libvlc_event_manager from this media list instance.
The p_event_manager is immutable, so you don't have to hold the lock.
@param p_ml: a media list instance.
@return: libvlc_event_manager.
'''
f = _Cfunctions.get('libvlc_media_list_event_manager', None) or \
_Cfunction('libvlc_media_list_event_manager', ((1,),), class_result(EventManager),
ctypes.c_void_p, MediaList)
return f(p_ml) | [
"def",
"libvlc_media_list_event_manager",
"(",
"p_ml",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_list_event_manager'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_list_event_manager'",
",",
"(",
"(",
"1",
",",
")",
",",
")"... | Get libvlc_event_manager from this media list instance.
The p_event_manager is immutable, so you don't have to hold the lock.
@param p_ml: a media list instance.
@return: libvlc_event_manager. | [
"Get",
"libvlc_event_manager",
"from",
"this",
"media",
"list",
"instance",
".",
"The",
"p_event_manager",
"is",
"immutable",
"so",
"you",
"don",
"t",
"have",
"to",
"hold",
"the",
"lock",
"."
] | python | train |
chrisrink10/basilisp | src/basilisp/lang/multifn.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/multifn.py#L46-L54 | def get_method(self, key: T) -> Optional[Method]:
"""Return the method which would handle this dispatch key or
None if no method defined for this key and no default."""
method_cache = self.methods
# The 'type: ignore' comment below silences a spurious MyPy error
# about having a return statement in a method which does not return.
return Maybe(method_cache.entry(key, None)).or_else(
lambda: method_cache.entry(self._default, None) # type: ignore
) | [
"def",
"get_method",
"(",
"self",
",",
"key",
":",
"T",
")",
"->",
"Optional",
"[",
"Method",
"]",
":",
"method_cache",
"=",
"self",
".",
"methods",
"# The 'type: ignore' comment below silences a spurious MyPy error",
"# about having a return statement in a method which doe... | Return the method which would handle this dispatch key or
None if no method defined for this key and no default. | [
"Return",
"the",
"method",
"which",
"would",
"handle",
"this",
"dispatch",
"key",
"or",
"None",
"if",
"no",
"method",
"defined",
"for",
"this",
"key",
"and",
"no",
"default",
"."
] | python | test |
project-ncl/pnc-cli | pnc_cli/products.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/products.py#L116-L122 | def list_products(page_size=200, page_index=0, sort="", q=""):
"""
List all Products
"""
content = list_products_raw(page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | [
"def",
"list_products",
"(",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"content",
"=",
"list_products_raw",
"(",
"page_size",
",",
"page_index",
",",
"sort",
",",
"q",
")",
"if",
... | List all Products | [
"List",
"all",
"Products"
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L362-L378 | def get_interface_switchport_output_switchport_acceptable_frame_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
acceptable_frame_type = ET.SubElement(switchport, "acceptable-frame-type")
acceptable_frame_type.text = kwargs.pop('acceptable_frame_type')
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"get_interface_switchport_output_switchport_acceptable_frame_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_switchport",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_switchp... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Alignak-monitoring/alignak | alignak/objects/satellitelink.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/satellitelink.py#L770-L777 | def wait_new_conf(self):
"""Send a HTTP request to the satellite (GET /wait_new_conf)
:return: True if wait new conf, otherwise False
:rtype: bool
"""
logger.debug("Wait new configuration for %s, %s %s", self.name, self.alive, self.reachable)
return self.con.get('_wait_new_conf') | [
"def",
"wait_new_conf",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Wait new configuration for %s, %s %s\"",
",",
"self",
".",
"name",
",",
"self",
".",
"alive",
",",
"self",
".",
"reachable",
")",
"return",
"self",
".",
"con",
".",
"get",
"(",
... | Send a HTTP request to the satellite (GET /wait_new_conf)
:return: True if wait new conf, otherwise False
:rtype: bool | [
"Send",
"a",
"HTTP",
"request",
"to",
"the",
"satellite",
"(",
"GET",
"/",
"wait_new_conf",
")"
] | python | train |
numenta/nupic | src/nupic/algorithms/fdrutilities.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L278-L315 | def generateSequences(nPatterns=10, patternLen=500, patternActivity=50,
hubs=[2,6], seqLength=[5,6,7],
nSimpleSequences=50, nHubSequences=50):
"""
Generate a set of simple and hub sequences. A simple sequence contains
a randomly chosen set of elements from 0 to 'nCoinc-1'. A hub sequence
always contains a hub element in the middle of it.
Parameters:
-----------------------------------------------
nPatterns: the number of patterns to use in the sequences.
patternLen: The number of elements in each pattern
patternActivity: The number of elements that should be active in
each pattern
hubs: which of the elements will be used as hubs.
seqLength: a list of possible sequence lengths. The length of each
sequence will be randomly chosen from here.
nSimpleSequences: The number of simple sequences to generate
nHubSequences: The number of hub sequences to generate
retval: (seqList, patterns)
seqList: a list of sequences. Each sequence is itself a list
containing the input pattern indices for that sequence.
patterns: the input patterns used in the seqList.
"""
# Create the input patterns
patterns = generateCoincMatrix(nCoinc=nPatterns, length=patternLen,
activity=patternActivity)
# Create the raw sequences
seqList = generateSimpleSequences(nCoinc=nPatterns, seqLength=seqLength,
nSeq=nSimpleSequences) + \
generateHubSequences(nCoinc=nPatterns, hubs=hubs, seqLength=seqLength,
nSeq=nHubSequences)
# Return results
return (seqList, patterns) | [
"def",
"generateSequences",
"(",
"nPatterns",
"=",
"10",
",",
"patternLen",
"=",
"500",
",",
"patternActivity",
"=",
"50",
",",
"hubs",
"=",
"[",
"2",
",",
"6",
"]",
",",
"seqLength",
"=",
"[",
"5",
",",
"6",
",",
"7",
"]",
",",
"nSimpleSequences",
... | Generate a set of simple and hub sequences. A simple sequence contains
a randomly chosen set of elements from 0 to 'nCoinc-1'. A hub sequence
always contains a hub element in the middle of it.
Parameters:
-----------------------------------------------
nPatterns: the number of patterns to use in the sequences.
patternLen: The number of elements in each pattern
patternActivity: The number of elements that should be active in
each pattern
hubs: which of the elements will be used as hubs.
seqLength: a list of possible sequence lengths. The length of each
sequence will be randomly chosen from here.
nSimpleSequences: The number of simple sequences to generate
nHubSequences: The number of hub sequences to generate
retval: (seqList, patterns)
seqList: a list of sequences. Each sequence is itself a list
containing the input pattern indices for that sequence.
patterns: the input patterns used in the seqList. | [
"Generate",
"a",
"set",
"of",
"simple",
"and",
"hub",
"sequences",
".",
"A",
"simple",
"sequence",
"contains",
"a",
"randomly",
"chosen",
"set",
"of",
"elements",
"from",
"0",
"to",
"nCoinc",
"-",
"1",
".",
"A",
"hub",
"sequence",
"always",
"contains",
"... | python | valid |
googledatalab/pydatalab | google/datalab/ml/_tensorboard.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_tensorboard.py#L82-L93 | def stop(pid):
"""Shut down a specific process.
Args:
pid: the pid of the process to shutdown.
"""
if psutil.pid_exists(pid):
try:
p = psutil.Process(pid)
p.kill()
except Exception:
pass | [
"def",
"stop",
"(",
"pid",
")",
":",
"if",
"psutil",
".",
"pid_exists",
"(",
"pid",
")",
":",
"try",
":",
"p",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"p",
".",
"kill",
"(",
")",
"except",
"Exception",
":",
"pass"
] | Shut down a specific process.
Args:
pid: the pid of the process to shutdown. | [
"Shut",
"down",
"a",
"specific",
"process",
"."
] | python | train |
pygobject/pgi | pgi/overrides/GObject.py | https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GObject.py#L458-L476 | def signal_handler_block(obj, handler_id):
"""Blocks the signal handler from being invoked until
handler_unblock() is called.
:param GObject.Object obj:
Object instance to block handlers for.
:param int handler_id:
Id of signal to block.
:returns:
A context manager which optionally can be used to
automatically unblock the handler:
.. code-block:: python
with GObject.signal_handler_block(obj, id):
pass
"""
GObjectModule.signal_handler_block(obj, handler_id)
return _HandlerBlockManager(obj, handler_id) | [
"def",
"signal_handler_block",
"(",
"obj",
",",
"handler_id",
")",
":",
"GObjectModule",
".",
"signal_handler_block",
"(",
"obj",
",",
"handler_id",
")",
"return",
"_HandlerBlockManager",
"(",
"obj",
",",
"handler_id",
")"
] | Blocks the signal handler from being invoked until
handler_unblock() is called.
:param GObject.Object obj:
Object instance to block handlers for.
:param int handler_id:
Id of signal to block.
:returns:
A context manager which optionally can be used to
automatically unblock the handler:
.. code-block:: python
with GObject.signal_handler_block(obj, id):
pass | [
"Blocks",
"the",
"signal",
"handler",
"from",
"being",
"invoked",
"until",
"handler_unblock",
"()",
"is",
"called",
"."
] | python | train |
ubernostrum/django-soapbox | soapbox/models.py | https://github.com/ubernostrum/django-soapbox/blob/f9189e1ddf47175f2392b92c7a0a902817ee1e93/soapbox/models.py#L36-L45 | def match(self, url):
"""
Return a list of all active Messages which match the given
URL.
"""
return list({
message for message in self.active() if
message.is_global or message.match(url)
}) | [
"def",
"match",
"(",
"self",
",",
"url",
")",
":",
"return",
"list",
"(",
"{",
"message",
"for",
"message",
"in",
"self",
".",
"active",
"(",
")",
"if",
"message",
".",
"is_global",
"or",
"message",
".",
"match",
"(",
"url",
")",
"}",
")"
] | Return a list of all active Messages which match the given
URL. | [
"Return",
"a",
"list",
"of",
"all",
"active",
"Messages",
"which",
"match",
"the",
"given",
"URL",
"."
] | python | train |
googledatalab/pydatalab | google/datalab/storage/commands/_storage.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L34-L51 | def _extract_gcs_api_response_error(message):
""" A helper function to extract user-friendly error messages from service exceptions.
Args:
message: An error message from an exception. If this is from our HTTP client code, it
will actually be a tuple.
Returns:
A modified version of the message that is less cryptic.
"""
try:
if len(message) == 3:
# Try treat the last part as JSON
data = json.loads(message[2])
return data['error']['errors'][0]['message']
except Exception:
pass
return message | [
"def",
"_extract_gcs_api_response_error",
"(",
"message",
")",
":",
"try",
":",
"if",
"len",
"(",
"message",
")",
"==",
"3",
":",
"# Try treat the last part as JSON",
"data",
"=",
"json",
".",
"loads",
"(",
"message",
"[",
"2",
"]",
")",
"return",
"data",
... | A helper function to extract user-friendly error messages from service exceptions.
Args:
message: An error message from an exception. If this is from our HTTP client code, it
will actually be a tuple.
Returns:
A modified version of the message that is less cryptic. | [
"A",
"helper",
"function",
"to",
"extract",
"user",
"-",
"friendly",
"error",
"messages",
"from",
"service",
"exceptions",
"."
] | python | train |
AtteqCom/zsl | src/zsl/utils/nginx_push_helper.py | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/nginx_push_helper.py#L43-L50 | def push(self, channel_id, data):
"""Push message with POST ``data`` for ``channel_id``
"""
channel_path = self.channel_path(channel_id)
response = requests.post(channel_path, data)
return response.json() | [
"def",
"push",
"(",
"self",
",",
"channel_id",
",",
"data",
")",
":",
"channel_path",
"=",
"self",
".",
"channel_path",
"(",
"channel_id",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"channel_path",
",",
"data",
")",
"return",
"response",
".",
"j... | Push message with POST ``data`` for ``channel_id`` | [
"Push",
"message",
"with",
"POST",
"data",
"for",
"channel_id"
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_1_01a/system_monitor/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/system_monitor/__init__.py#L275-L296 | def _set_MM(self, v, load=False):
"""
Setter method for MM, mapped from YANG variable /system_monitor/MM (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_MM is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_MM() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=MM.MM, is_container='container', presence=False, yang_name="MM", rest_name="MM", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure threshold setting for \n component:MM', u'cli-incomplete-no': None}}, namespace='urn:brocade.com:mgmt:brocade-system-monitor', defining_module='brocade-system-monitor', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """MM must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=MM.MM, is_container='container', presence=False, yang_name="MM", rest_name="MM", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure threshold setting for \n component:MM', u'cli-incomplete-no': None}}, namespace='urn:brocade.com:mgmt:brocade-system-monitor', defining_module='brocade-system-monitor', yang_type='container', is_config=True)""",
})
self.__MM = t
if hasattr(self, '_set'):
self._set() | [
"def",
"_set_MM",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"=... | Setter method for MM, mapped from YANG variable /system_monitor/MM (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_MM is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_MM() directly. | [
"Setter",
"method",
"for",
"MM",
"mapped",
"from",
"YANG",
"variable",
"/",
"system_monitor",
"/",
"MM",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
... | python | train |
kibitzr/kibitzr | kibitzr/cli.py | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/cli.py#L61-L65 | def once(ctx, name):
"""Run kibitzr checks once and exit"""
from kibitzr.app import Application
app = Application()
sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) | [
"def",
"once",
"(",
"ctx",
",",
"name",
")",
":",
"from",
"kibitzr",
".",
"app",
"import",
"Application",
"app",
"=",
"Application",
"(",
")",
"sys",
".",
"exit",
"(",
"app",
".",
"run",
"(",
"once",
"=",
"True",
",",
"log_level",
"=",
"ctx",
".",
... | Run kibitzr checks once and exit | [
"Run",
"kibitzr",
"checks",
"once",
"and",
"exit"
] | python | train |
jobovy/galpy | galpy/potential/SpiralArmsPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/SpiralArmsPotential.py#L585-L590 | def _dD_dR(self, R):
"""Return numpy array of dD/dR from D1 up to and including Dn."""
HNn_R_sina = self._HNn / R / self._sin_alpha
return HNn_R_sina * (0.3 * (HNn_R_sina + 0.3 * HNn_R_sina**2. + 1) / R / (0.3 * HNn_R_sina + 1)**2
- (1/R * (1 + 0.6 * HNn_R_sina) / (0.3 * HNn_R_sina + 1))) | [
"def",
"_dD_dR",
"(",
"self",
",",
"R",
")",
":",
"HNn_R_sina",
"=",
"self",
".",
"_HNn",
"/",
"R",
"/",
"self",
".",
"_sin_alpha",
"return",
"HNn_R_sina",
"*",
"(",
"0.3",
"*",
"(",
"HNn_R_sina",
"+",
"0.3",
"*",
"HNn_R_sina",
"**",
"2.",
"+",
"1"... | Return numpy array of dD/dR from D1 up to and including Dn. | [
"Return",
"numpy",
"array",
"of",
"dD",
"/",
"dR",
"from",
"D1",
"up",
"to",
"and",
"including",
"Dn",
"."
] | python | train |
rndusr/torf | torf/_torrent.py | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L707-L718 | def convert(self):
"""
Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all
values encoded to :class:`bytes`, :class:`int`, :class:`list` or
:class:`OrderedDict`
:raises MetainfoError: on values that cannot be converted properly
"""
try:
return utils.encode_dict(self.metainfo)
except ValueError as e:
raise error.MetainfoError(str(e)) | [
"def",
"convert",
"(",
"self",
")",
":",
"try",
":",
"return",
"utils",
".",
"encode_dict",
"(",
"self",
".",
"metainfo",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"error",
".",
"MetainfoError",
"(",
"str",
"(",
"e",
")",
")"
] | Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all
values encoded to :class:`bytes`, :class:`int`, :class:`list` or
:class:`OrderedDict`
:raises MetainfoError: on values that cannot be converted properly | [
"Return",
":",
"attr",
":",
"metainfo",
"with",
"all",
"keys",
"encoded",
"to",
":",
"class",
":",
"bytes",
"and",
"all",
"values",
"encoded",
"to",
":",
"class",
":",
"bytes",
":",
"class",
":",
"int",
":",
"class",
":",
"list",
"or",
":",
"class",
... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.