text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def load_field(self, state, field_name, field_type):
"""
Load a field of a given object, without resolving hierachy
:param state: angr state where we want to load the object attribute
:type SimState
:param field_name: name of the attribute
:type str
:param field_... | [
"def",
"load_field",
"(",
"self",
",",
"state",
",",
"field_name",
",",
"field_type",
")",
":",
"field_ref",
"=",
"SimSootValue_InstanceFieldRef",
"(",
"self",
".",
"heap_alloc_id",
",",
"self",
".",
"type",
",",
"field_name",
",",
"field_type",
")",
"return",... | 41.307692 | 21.769231 |
def address_offset(self):
"""
Byte address offset of this node relative to it's parent
If this node is an array, it's index must be known
Raises
------
ValueError
If this property is referenced on a node whose array index is not
fully defined
... | [
"def",
"address_offset",
"(",
"self",
")",
":",
"if",
"self",
".",
"inst",
".",
"is_array",
":",
"if",
"self",
".",
"current_idx",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Index of array element must be known to derive address\"",
")",
"# Calculate the \"fl... | 33.333333 | 20.944444 |
def commitreturn(self,qstring,vals=()):
"commit and return result. This is intended for sql UPDATE ... RETURNING"
with self.withcur() as cur:
cur.execute(qstring,vals)
return cur.fetchone() | [
"def",
"commitreturn",
"(",
"self",
",",
"qstring",
",",
"vals",
"=",
"(",
")",
")",
":",
"with",
"self",
".",
"withcur",
"(",
")",
"as",
"cur",
":",
"cur",
".",
"execute",
"(",
"qstring",
",",
"vals",
")",
"return",
"cur",
".",
"fetchone",
"(",
... | 41 | 13.8 |
async def on_isupport_targmax(self, value):
""" The maximum number of targets certain types of commands can affect. """
if not value:
return
for entry in value.split(','):
command, limit = entry.split(':', 1)
if not limit:
continue
... | [
"async",
"def",
"on_isupport_targmax",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"for",
"entry",
"in",
"value",
".",
"split",
"(",
"','",
")",
":",
"command",
",",
"limit",
"=",
"entry",
".",
"split",
"(",
"':'",
",",
... | 35.3 | 13.8 |
def save(self, **kwargs):
"""
Method that creates the translations tasks for every selected instance
:param kwargs:
:return:
"""
try:
# result_ids = []
manager = Manager()
for item in self.model_class.objects.language(manager.get_main_... | [
"def",
"save",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# result_ids = []",
"manager",
"=",
"Manager",
"(",
")",
"for",
"item",
"in",
"self",
".",
"model_class",
".",
"objects",
".",
"language",
"(",
"manager",
".",
"get_main_language... | 46.058824 | 28.294118 |
def every_other(x, name=None):
"""Drops every other value from the tensor and returns a 1D tensor.
This is useful if you are running multiple inputs through a model tower
before splitting them and you want to line it up with some other data.
Args:
x: the target tensor.
name: the name for this op, defa... | [
"def",
"every_other",
"(",
"x",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'every_other'",
",",
"[",
"x",
"]",
")",
"as",
"scope",
":",
"x",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"x",
",",
"name",
... | 30.894737 | 20.368421 |
def to_cloudformation(self, **kwargs):
"""Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds.
:param dict kwargs: already-converted resources that may need to be modified when converting this \
macro to pure CloudFormation
:returns: a list of vanill... | [
"def",
"to_cloudformation",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"resources",
"=",
"[",
"]",
"api_generator",
"=",
"ApiGenerator",
"(",
"self",
".",
"logical_id",
",",
"self",
".",
"CacheClusterEnabled",
",",
"self",
".",
"CacheClusterSize",
",",
... | 53.578947 | 26.605263 |
def compute_invalidation_globs(bootstrap_options):
"""
Combine --pythonpath and --pants_config_files(pants.ini) files that are in {buildroot} dir
with those invalidation_globs provided by users
:param bootstrap_options:
:return: A list of invalidation_globs
"""
buildroot = get_buildroot()
... | [
"def",
"compute_invalidation_globs",
"(",
"bootstrap_options",
")",
":",
"buildroot",
"=",
"get_buildroot",
"(",
")",
"invalidation_globs",
"=",
"[",
"]",
"globs",
"=",
"bootstrap_options",
".",
"pythonpath",
"+",
"bootstrap_options",
".",
"pants_config_files",
"+",
... | 40.727273 | 19.272727 |
def add_fields(self, fields):
"""
Adds all of the passed fields to the table's current field list
:param fields: The fields to select from ``table``. This can be
a single field, a tuple of fields, or a list of fields. Each field can be a string
or ``Field`` instance
... | [
"def",
"add_fields",
"(",
"self",
",",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"string_types",
")",
":",
"fields",
"=",
"[",
"fields",
"]",
"elif",
"type",
"(",
"fields",
")",
"is",
"tuple",
":",
"fields",
"=",
"list",
"(",
"field... | 41.75 | 22 |
def smart_cast(var, type_):
"""
casts var to type, and tries to be clever when var is a string
Args:
var (object): variable to cast
type_ (type or str): type to attempt to cast to
Returns:
object:
CommandLine:
python -m utool.util_type --exec-smart_cast
Exampl... | [
"def",
"smart_cast",
"(",
"var",
",",
"type_",
")",
":",
"#if isinstance(type_, tuple):",
"# for trytype in type_:",
"# try:",
"# return trytype(var)",
"# except Exception:",
"# pass",
"# raise TypeError('Cant figure out type=%r' % (type_,))",
... | 29.293478 | 16.206522 |
def get_absolute_path(cls, root: str, path: str) -> str:
"""Returns the absolute location of ``path`` relative to ``root``.
``root`` is the path configured for this `StaticFileHandler`
(in most cases the ``static_path`` `Application` setting).
This class method may be overridden in sub... | [
"def",
"get_absolute_path",
"(",
"cls",
",",
"root",
":",
"str",
",",
"path",
":",
"str",
")",
"->",
"str",
":",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"path",
")",
")",
"return",... | 41.466667 | 21.933333 |
def project(self, axis):
""" Project this vector onto the given axis. """
projection = self.get_projection(axis)
self.assign(projection) | [
"def",
"project",
"(",
"self",
",",
"axis",
")",
":",
"projection",
"=",
"self",
".",
"get_projection",
"(",
"axis",
")",
"self",
".",
"assign",
"(",
"projection",
")"
] | 39.25 | 7.75 |
def id_to_fqname(self, uuid, type=None):
"""
Return fq_name and type for uuid
If `type` is provided check that uuid is actually
a resource of type `type`. Raise HttpError if it's
not the case.
:param uuid: resource uuid
:type uuid: UUIDv4 str
:param type... | [
"def",
"id_to_fqname",
"(",
"self",
",",
"uuid",
",",
"type",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"uuid\"",
":",
"uuid",
"}",
"result",
"=",
"self",
".",
"post_json",
"(",
"self",
".",
"make_url",
"(",
"\"/id-to-fqname\"",
")",
",",
"data",
")... | 33.916667 | 18.666667 |
def DEFINE_choice(name, default, choices, help):
"""A helper for defining choice string options."""
_CONFIG.DEFINE_choice(name, default, choices, help) | [
"def",
"DEFINE_choice",
"(",
"name",
",",
"default",
",",
"choices",
",",
"help",
")",
":",
"_CONFIG",
".",
"DEFINE_choice",
"(",
"name",
",",
"default",
",",
"choices",
",",
"help",
")"
] | 51 | 7 |
def image_path_from_index(self, index):
"""
given image index, find out full path
Parameters:
----------
index: int
index of a specific image
Returns:
----------
full path of this image
"""
assert self.image_set_index is not No... | [
"def",
"image_path_from_index",
"(",
"self",
",",
"index",
")",
":",
"assert",
"self",
".",
"image_set_index",
"is",
"not",
"None",
",",
"\"Dataset not initialized\"",
"name",
"=",
"self",
".",
"image_set_index",
"[",
"index",
"]",
"image_file",
"=",
"os",
"."... | 33.941176 | 18.411765 |
def from_array(array):
"""
Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
... | [
"def",
"from_array",
"(",
"array",
")",
":",
"if",
"array",
"is",
"None",
"or",
"not",
"array",
":",
"return",
"None",
"# end if",
"assert_type_or_raise",
"(",
"array",
",",
"dict",
",",
"parameter_name",
"=",
"\"array\"",
")",
"from",
"pytgbot",
".",
"api... | 46.153846 | 26.615385 |
def save(self, rup_array):
"""
Store the ruptures in array format.
"""
self.nruptures += len(rup_array)
offset = len(self.datastore['rupgeoms'])
rup_array.array['gidx1'] += offset
rup_array.array['gidx2'] += offset
previous = self.datastore.get_attr('rupt... | [
"def",
"save",
"(",
"self",
",",
"rup_array",
")",
":",
"self",
".",
"nruptures",
"+=",
"len",
"(",
"rup_array",
")",
"offset",
"=",
"len",
"(",
"self",
".",
"datastore",
"[",
"'rupgeoms'",
"]",
")",
"rup_array",
".",
"array",
"[",
"'gidx1'",
"]",
"+... | 41.428571 | 10.428571 |
def _update_column_info(self):
"""
Used for validation during parsing, and additional
book-keeping. For internal use only.
"""
del self.columnnames[:]
del self.columntypes[:]
del self.columnpytypes[:]
for child in self.getElementsByTagName(ligolw.Column.tagName):
if self.validcolumns is not None:
... | [
"def",
"_update_column_info",
"(",
"self",
")",
":",
"del",
"self",
".",
"columnnames",
"[",
":",
"]",
"del",
"self",
".",
"columntypes",
"[",
":",
"]",
"del",
"self",
".",
"columnpytypes",
"[",
":",
"]",
"for",
"child",
"in",
"self",
".",
"getElements... | 52.173913 | 30.086957 |
def generate(self):
'''
Generate noise samples.
Returns:
`np.ndarray` of samples.
'''
generated_arr = np.random.normal(loc=self.__mu, scale=self.__sigma, size=self.__output_shape)
if self.noise_sampler is not None:
self.noise_samp... | [
"def",
"generate",
"(",
"self",
")",
":",
"generated_arr",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"loc",
"=",
"self",
".",
"__mu",
",",
"scale",
"=",
"self",
".",
"__sigma",
",",
"size",
"=",
"self",
".",
"__output_shape",
")",
"if",
"self",
... | 34.307692 | 22.615385 |
def stdout(prev, endl='\n', thru=False):
"""This pipe read data from previous iterator and write it to stdout.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param endl: The end-of-line symbol for each output.
:type endl: str
:param thru: If true, data will passed to next generat... | [
"def",
"stdout",
"(",
"prev",
",",
"endl",
"=",
"'\\n'",
",",
"thru",
"=",
"False",
")",
":",
"for",
"i",
"in",
"prev",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"str",
"(",
"i",
")",
"+",
"endl",
")",
"if",
"thru",
":",
"yield",
"i"
] | 31.625 | 15.75 |
def step(self):
"""Perform a single step of the morphological Chan-Vese evolution."""
# Assign attributes to local variables for convenience.
u = self._u
if u is None:
raise ValueError("the levelset function is not set "
"(use set_levelse... | [
"def",
"step",
"(",
"self",
")",
":",
"# Assign attributes to local variables for convenience.",
"u",
"=",
"self",
".",
"_u",
"if",
"u",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"the levelset function is not set \"",
"\"(use set_levelset)\"",
")",
"data",
"=",... | 31.242424 | 18 |
def set_mode (filename, flags):
"""Set mode flags for given filename if not already set."""
try:
mode = os.lstat(filename).st_mode
except OSError:
# ignore
return
if not (mode & flags):
try:
os.chmod(filename, flags | mode)
except OSError as msg:
... | [
"def",
"set_mode",
"(",
"filename",
",",
"flags",
")",
":",
"try",
":",
"mode",
"=",
"os",
".",
"lstat",
"(",
"filename",
")",
".",
"st_mode",
"except",
"OSError",
":",
"# ignore",
"return",
"if",
"not",
"(",
"mode",
"&",
"flags",
")",
":",
"try",
... | 32 | 17.416667 |
def get_subprocess_output(cls, command, ignore_stderr=True, **kwargs):
"""Get the output of an executed command.
:param command: An iterable representing the command to execute (e.g. ['ls', '-al']).
:param ignore_stderr: Whether or not to ignore stderr output vs interleave it with stdout.
:raises: `Pro... | [
"def",
"get_subprocess_output",
"(",
"cls",
",",
"command",
",",
"ignore_stderr",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ignore_stderr",
"is",
"False",
":",
"kwargs",
".",
"setdefault",
"(",
"'stderr'",
",",
"subprocess",
".",
"STDOUT",
")"... | 48 | 25 |
def resolve_freezer(freezer):
"""
Locate the appropriate freezer given FREEZER or string input from the programmer.
:param freezer: FREEZER constant or string for the freezer that is requested. (None = FREEZER.DEFAULT)
:return:
"""
# Set default freezer if there was none
if not freezer:
... | [
"def",
"resolve_freezer",
"(",
"freezer",
")",
":",
"# Set default freezer if there was none",
"if",
"not",
"freezer",
":",
"return",
"_Default",
"(",
")",
"# Allow character based lookups as well",
"if",
"isinstance",
"(",
"freezer",
",",
"six",
".",
"string_types",
... | 31.92 | 21.84 |
def _aix_loadavg():
'''
Return the load average on AIX
'''
# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69
uptime = __salt__['cmd.run']('uptime')
ldavg = uptime.split('load average')
load_avg = ldavg[1].split()
return {'1-min': load_avg[1].strip(','),
... | [
"def",
"_aix_loadavg",
"(",
")",
":",
"# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69",
"uptime",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'uptime'",
")",
"ldavg",
"=",
"uptime",
".",
"split",
"(",
"'load average'",
")",
"load_avg",
"="... | 34.454545 | 14.090909 |
def pymatgen_mol(self):
"""
Returns pymatgen Molecule object.
"""
sp = []
coords = []
for atom in ob.OBMolAtomIter(self._obmol):
sp.append(atom.GetAtomicNum())
coords.append([atom.GetX(), atom.GetY(), atom.GetZ()])
return Molecule(sp, coord... | [
"def",
"pymatgen_mol",
"(",
"self",
")",
":",
"sp",
"=",
"[",
"]",
"coords",
"=",
"[",
"]",
"for",
"atom",
"in",
"ob",
".",
"OBMolAtomIter",
"(",
"self",
".",
"_obmol",
")",
":",
"sp",
".",
"append",
"(",
"atom",
".",
"GetAtomicNum",
"(",
")",
")... | 31.3 | 10.7 |
def serialize_operator_not_equal(self, op):
"""
Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.
Example::
<not-equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
... | [
"def",
"serialize_operator_not_equal",
"(",
"self",
",",
"op",
")",
":",
"elem",
"=",
"etree",
".",
"Element",
"(",
"'not-equals'",
")",
"return",
"self",
".",
"serialize_value_list",
"(",
"elem",
",",
"op",
".",
"args",
")"
] | 31.214286 | 15.214286 |
def write(self, nml_path, force=False, sort=False):
"""Write Namelist to a Fortran 90 namelist file.
>>> nml = f90nml.read('input.nml')
>>> nml.write('out.nml')
"""
nml_is_file = hasattr(nml_path, 'read')
if not force and not nml_is_file and os.path.isfile(nml_path):
... | [
"def",
"write",
"(",
"self",
",",
"nml_path",
",",
"force",
"=",
"False",
",",
"sort",
"=",
"False",
")",
":",
"nml_is_file",
"=",
"hasattr",
"(",
"nml_path",
",",
"'read'",
")",
"if",
"not",
"force",
"and",
"not",
"nml_is_file",
"and",
"os",
".",
"p... | 36.375 | 16.8125 |
def rule110_network():
"""A network of three elements which follows the logic of the Rule 110
cellular automaton with current and previous state (0, 0, 0).
"""
tpm = np.array([[0, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
[0, ... | [
"def",
"rule110_network",
"(",
")",
":",
"tpm",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0",
",",
"0",
",",
"0",
"]",
",",
"[",
"1",
",",
"0",
",",
"1",
"]",
",",
"[",
"1",
",",
"1",
",",
"0",
"]",
",",
"[",
"1",
",",
"1",
",",
"1",
... | 35.923077 | 10.769231 |
def write_to_sdpa(sdp, filename):
"""Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str.
"""
# Coefficient matrices
row_offsets ... | [
"def",
"write_to_sdpa",
"(",
"sdp",
",",
"filename",
")",
":",
"# Coefficient matrices",
"row_offsets",
"=",
"[",
"0",
"]",
"cumulative_sum",
"=",
"0",
"for",
"block_size",
"in",
"sdp",
".",
"block_struct",
":",
"cumulative_sum",
"+=",
"block_size",
"**",
"2",... | 42.042857 | 14.328571 |
def discard_last(self, indices):
"""Discard the triggers added in the latest update"""
for i in indices:
self.buffer_expire[i] = self.buffer_expire[i][:-1]
self.buffer[i] = self.buffer[i][:-1] | [
"def",
"discard_last",
"(",
"self",
",",
"indices",
")",
":",
"for",
"i",
"in",
"indices",
":",
"self",
".",
"buffer_expire",
"[",
"i",
"]",
"=",
"self",
".",
"buffer_expire",
"[",
"i",
"]",
"[",
":",
"-",
"1",
"]",
"self",
".",
"buffer",
"[",
"i... | 45.6 | 10.6 |
def leave_swarm(force=bool):
'''
Force the minion to leave the swarm
force
Will force the minion/worker/manager to leave the swarm
CLI Example:
.. code-block:: bash
salt '*' swarm.leave_swarm force=False
'''
salt_return = {}
__context__['client'].swarm.leave(force=for... | [
"def",
"leave_swarm",
"(",
"force",
"=",
"bool",
")",
":",
"salt_return",
"=",
"{",
"}",
"__context__",
"[",
"'client'",
"]",
".",
"swarm",
".",
"leave",
"(",
"force",
"=",
"force",
")",
"output",
"=",
"__context__",
"[",
"'server_name'",
"]",
"+",
"' ... | 24.277778 | 22.944444 |
def display_weyl(decomps):
"""Construct and display 3D plot of canonical coordinates"""
tx, ty, tz = list(zip(*decomps))
rcParams['axes.labelsize'] = 24
rcParams['font.family'] = 'serif'
rcParams['font.serif'] = ['Computer Modern Roman']
rcParams['text.usetex'] = True
fig = pyplot.figure()
... | [
"def",
"display_weyl",
"(",
"decomps",
")",
":",
"tx",
",",
"ty",
",",
"tz",
"=",
"list",
"(",
"zip",
"(",
"*",
"decomps",
")",
")",
"rcParams",
"[",
"'axes.labelsize'",
"]",
"=",
"24",
"rcParams",
"[",
"'font.family'",
"]",
"=",
"'serif'",
"rcParams",... | 35.904762 | 17.396825 |
def update(self, attributes=None):
"""
Updates the resource with attributes.
"""
if attributes is None:
attributes = {}
headers = self.__class__.create_headers(attributes)
headers.update(self._update_headers())
result = self._client._put(
... | [
"def",
"update",
"(",
"self",
",",
"attributes",
"=",
"None",
")",
":",
"if",
"attributes",
"is",
"None",
":",
"attributes",
"=",
"{",
"}",
"headers",
"=",
"self",
".",
"__class__",
".",
"create_headers",
"(",
"attributes",
")",
"headers",
".",
"update",... | 24.45 | 18.15 |
def piece_file(input_f, chunk_size):
"""
Provides a streaming interface to file data in chunks of even size, which
avoids memoryerrors from loading whole files into RAM to pass to `pieces`.
"""
chunk = input_f.read(chunk_size)
total_bytes = 0
while chunk:
... | [
"def",
"piece_file",
"(",
"input_f",
",",
"chunk_size",
")",
":",
"chunk",
"=",
"input_f",
".",
"read",
"(",
"chunk_size",
")",
"total_bytes",
"=",
"0",
"while",
"chunk",
":",
"yield",
"chunk",
"chunk",
"=",
"input_f",
".",
"read",
"(",
"chunk_size",
")"... | 37.090909 | 13.454545 |
def repository(self, only):
"""Update repositories lists
"""
print("\nCheck and update repositories:\n")
default = self.meta.default_repositories
enabled = self.meta.repositories
if only:
enabled = only
for repo in enabled:
if check_for_loc... | [
"def",
"repository",
"(",
"self",
",",
"only",
")",
":",
"print",
"(",
"\"\\nCheck and update repositories:\\n\"",
")",
"default",
"=",
"self",
".",
"meta",
".",
"default_repositories",
"enabled",
"=",
"self",
".",
"meta",
".",
"repositories",
"if",
"only",
":... | 40.214286 | 11.75 |
def post(self, request, *args, **kwargs):
"""Handle post request"""
try:
kwargs = self.load_object(kwargs)
except Exception as e:
return self.render_te_response({
'title': str(e),
})
if not self.has_permission(request):
ret... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"kwargs",
"=",
"self",
".",
"load_object",
"(",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"self",
".",
"render_te_respo... | 33.214286 | 13.857143 |
def cpmaximum(image, structure=np.ones((3,3),dtype=bool),offset=None):
"""Find the local maximum at each point in the image, using the given structuring element
image - a 2-d array of doubles
structure - a boolean structuring element indicating which
local elements should be sampled
... | [
"def",
"cpmaximum",
"(",
"image",
",",
"structure",
"=",
"np",
".",
"ones",
"(",
"(",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"bool",
")",
",",
"offset",
"=",
"None",
")",
":",
"center",
"=",
"np",
".",
"array",
"(",
"structure",
".",
"shape",
"... | 46.428571 | 16.285714 |
def groupby(self, dimensions, container_type=None, group_type=None, **kwargs):
"""Groups object by one or more dimensions
Applies groupby operation over the specified dimensions
returning an object of type container_type (expected to be
dictionary-like) containing the groups.
A... | [
"def",
"groupby",
"(",
"self",
",",
"dimensions",
",",
"container_type",
"=",
"None",
",",
"group_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"ndims",
"==",
"1",
":",
"self",
".",
"param",
".",
"warning",
"(",
"'Cannot s... | 46.37931 | 21.724138 |
def tile_x_size(self, zoom):
"""
Width of a tile in SRID units at zoom level.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_x_size is deprecated"))
validate_zoom(zoom)
return round(self.x_size / self.matrix_width(zoom), ROUND) | [
"def",
"tile_x_size",
"(",
"self",
",",
"zoom",
")",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
"(",
"\"tile_x_size is deprecated\"",
")",
")",
"validate_zoom",
"(",
"zoom",
")",
"return",
"round",
"(",
"self",
".",
"x_size",
"/",
"self",
".",
... | 32.333333 | 16.333333 |
def plot_plane(where="back", texture=None):
"""Plot a plane at a particular location in the viewbox.
:param str where: 'back', 'front', 'left', 'right', 'top', 'bottom'
:param texture: {texture}
:return: :any:`Mesh`
"""
fig = gcf()
xmin, xmax = fig.xlim
ymin, ymax = fig.ylim
zmin, z... | [
"def",
"plot_plane",
"(",
"where",
"=",
"\"back\"",
",",
"texture",
"=",
"None",
")",
":",
"fig",
"=",
"gcf",
"(",
")",
"xmin",
",",
"xmax",
"=",
"fig",
".",
"xlim",
"ymin",
",",
"ymax",
"=",
"fig",
".",
"ylim",
"zmin",
",",
"zmax",
"=",
"fig",
... | 32.261905 | 10.666667 |
def roots(self):
"""The list of word roots.
Ambiguous cases are separated with pipe character by default.
Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries.
"""
if not self.is_tagged(ANALYSIS):
self.tag_analysis(... | [
"def",
"roots",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"ANALYSIS",
")",
":",
"self",
".",
"tag_analysis",
"(",
")",
"return",
"self",
".",
"get_analysis_element",
"(",
"ROOT",
")"
] | 40 | 20.111111 |
def get_user_info(self, user_id, lang="zh_CN"):
"""
获取用户基本信息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/user/info... | [
"def",
"get_user_info",
"(",
"self",
",",
"user_id",
",",
"lang",
"=",
"\"zh_CN\"",
")",
":",
"return",
"self",
".",
"get",
"(",
"url",
"=",
"\"https://api.weixin.qq.com/cgi-bin/user/info\"",
",",
"params",
"=",
"{",
"\"access_token\"",
":",
"self",
".",
"toke... | 28.75 | 15.625 |
def map_data(self, map_name):
"""Return the map data for a map by name or path."""
with gfile.Open(os.path.join(self.data_dir, "Maps", map_name), "rb") as f:
return f.read() | [
"def",
"map_data",
"(",
"self",
",",
"map_name",
")",
":",
"with",
"gfile",
".",
"Open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_dir",
",",
"\"Maps\"",
",",
"map_name",
")",
",",
"\"rb\"",
")",
"as",
"f",
":",
"return",
"f",
... | 46 | 17 |
def _update_code_urls(self):
"""
Read the code and update all links.
"""
to_ignore = [".gitignore", ".keep"]
for root, _, files in PyFunceble.walk(
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.directory_separator
+ "PyFunceble"
+ PyF... | [
"def",
"_update_code_urls",
"(",
"self",
")",
":",
"to_ignore",
"=",
"[",
"\".gitignore\"",
",",
"\".keep\"",
"]",
"for",
"root",
",",
"_",
",",
"files",
"in",
"PyFunceble",
".",
"walk",
"(",
"PyFunceble",
".",
"CURRENT_DIRECTORY",
"+",
"PyFunceble",
".",
... | 44.393443 | 27.147541 |
def _update_settings(self, new_settings, enforce_helpstring=True):
"""
This method does the work of updating settings. Can be passed with
enforce_helpstring = False which you may want if allowing end users to
add arbitrary metadata via the settings system.
Preferable to use upda... | [
"def",
"_update_settings",
"(",
"self",
",",
"new_settings",
",",
"enforce_helpstring",
"=",
"True",
")",
":",
"for",
"raw_setting_name",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"new_settings",
")",
":",
"setting_name",
"=",
"raw_setting_name",
".",
... | 47.969697 | 27.727273 |
def cli(argv=None):
"""CLI entry point for mozdownload."""
kwargs = parse_arguments(argv or sys.argv[1:])
log_level = kwargs.pop('log_level')
logging.basicConfig(format='%(levelname)s | %(message)s', level=log_level)
logger = logging.getLogger(__name__)
# Configure logging levels for sub modul... | [
"def",
"cli",
"(",
"argv",
"=",
"None",
")",
":",
"kwargs",
"=",
"parse_arguments",
"(",
"argv",
"or",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"log_level",
"=",
"kwargs",
".",
"pop",
"(",
"'log_level'",
")",
"logging",
".",
"basicConfig",
"(",
... | 35.7 | 18.366667 |
async def get_oauth_token(consumer_key, consumer_secret, callback_uri="oob"):
"""
Get a temporary oauth token
Parameters
----------
consumer_key : str
Your consumer key
consumer_secret : str
Your consumer secret
callback_uri : str, optional
Callback uri, defaults to ... | [
"async",
"def",
"get_oauth_token",
"(",
"consumer_key",
",",
"consumer_secret",
",",
"callback_uri",
"=",
"\"oob\"",
")",
":",
"client",
"=",
"BasePeonyClient",
"(",
"consumer_key",
"=",
"consumer_key",
",",
"consumer_secret",
"=",
"consumer_secret",
",",
"api_versi... | 24.066667 | 20 |
def coerce_to_decimal(value):
"""Attempt to coerce the value to a Decimal, or raise an error if unable to do so."""
if isinstance(value, decimal.Decimal):
return value
else:
try:
return decimal.Decimal(value)
except decimal.InvalidOperation as e:
raise GraphQL... | [
"def",
"coerce_to_decimal",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"decimal",
".",
"Decimal",
")",
":",
"return",
"value",
"else",
":",
"try",
":",
"return",
"decimal",
".",
"Decimal",
"(",
"value",
")",
"except",
"decimal",
".",
... | 37.222222 | 11.777778 |
def _label_setter(self, new_label, current_label, attr_label, default=np.NaN, use_names_default=False):
"""Generalized setter of default meta attributes
Parameters
----------
new_label : str
New label to use in the Meta object
current_label : str
... | [
"def",
"_label_setter",
"(",
"self",
",",
"new_label",
",",
"current_label",
",",
"attr_label",
",",
"default",
"=",
"np",
".",
"NaN",
",",
"use_names_default",
"=",
"False",
")",
":",
"if",
"new_label",
"not",
"in",
"self",
".",
"attrs",
"(",
")",
":",
... | 41.586207 | 19.189655 |
def _d2f(self, x):
""" Evaluates the cost Hessian.
"""
d2f_dPg2 = lil_matrix((self._ng, 1)) # w.r.t p.u. Pg
d2f_dQg2 = lil_matrix((self._ng, 1)) # w.r.t p.u. Qg]
for i in self._ipol:
p_cost = list(self._gn[i].p_cost)
d2f_dPg2[i, 0] = polyval(polyder(p_cos... | [
"def",
"_d2f",
"(",
"self",
",",
"x",
")",
":",
"d2f_dPg2",
"=",
"lil_matrix",
"(",
"(",
"self",
".",
"_ng",
",",
"1",
")",
")",
"# w.r.t p.u. Pg",
"d2f_dQg2",
"=",
"lil_matrix",
"(",
"(",
"self",
".",
"_ng",
",",
"1",
")",
")",
"# w.r.t p.u. Qg]",
... | 40.85 | 21.25 |
def gene_dir(self):
"""Gene folder"""
if self.root_dir:
return op.join(self.root_dir, self.id)
else:
return None | [
"def",
"gene_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"root_dir",
":",
"return",
"op",
".",
"join",
"(",
"self",
".",
"root_dir",
",",
"self",
".",
"id",
")",
"else",
":",
"return",
"None"
] | 25.833333 | 15 |
def delete_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
"""
Delete a model.
:param args: :class:`argparse.Namespace` with "input", "backend", "args", "meta", \
"update_default", "username", "password", "remote_repo", \
"templ... | [
"def",
"delete_model",
"(",
"args",
":",
"argparse",
".",
"Namespace",
",",
"backend",
":",
"StorageBackend",
",",
"log",
":",
"logging",
".",
"Logger",
")",
":",
"try",
":",
"meta",
"=",
"backend",
".",
"index",
".",
"remove_model",
"(",
"args",
".",
... | 40.625 | 22.291667 |
def retain_all(self, items):
"""
Retains only the items that are contained in the specified collection. It means, items which are not present in
the specified collection are removed from this list.
:param items: (Collection), collections which includes the elements to be retained in thi... | [
"def",
"retain_all",
"(",
"self",
",",
"items",
")",
":",
"check_not_none",
"(",
"items",
",",
"\"Value can't be None\"",
")",
"data_items",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"check_not_none",
"(",
"item",
",",
"\"Value can't be None\"",
")",
... | 50.428571 | 26.428571 |
def bind(cls, param=None, **kwargs):
"""Bind middleware's method as endpoint.
"""
def stick(function, **binding):
if not asyncio.iscoroutine(function):
function = asyncio.coroutine(function)
bindings = getattr(function, STICKER, [])
bindings.ap... | [
"def",
"bind",
"(",
"cls",
",",
"param",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"stick",
"(",
"function",
",",
"*",
"*",
"binding",
")",
":",
"if",
"not",
"asyncio",
".",
"iscoroutine",
"(",
"function",
")",
":",
"function",
"=",
... | 40.692308 | 7.076923 |
def addCondition(self, *fns, **kwargs):
"""Add a boolean predicate function to expression's list of parse actions. See
:class:`setParseAction` for function call signatures. Unlike ``setParseAction``,
functions passed to ``addCondition`` need to return boolean success/fail of the condition.
... | [
"def",
"addCondition",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"kwargs",
".",
"get",
"(",
"\"message\"",
",",
"\"failed user-defined condition\"",
")",
"exc_type",
"=",
"ParseFatalException",
"if",
"kwargs",
".",
"get",
... | 51.928571 | 29.535714 |
def file_lines_map_expectation(cls, func):
"""Constructs an expectation using file lines map semantics.
The file_lines_map_expectations decorator handles boilerplate issues
surrounding the common pattern of evaluating truthiness of some
condition on an line by line basis in a file.
... | [
"def",
"file_lines_map_expectation",
"(",
"cls",
",",
"func",
")",
":",
"if",
"PY3",
":",
"argspec",
"=",
"inspect",
".",
"getfullargspec",
"(",
"func",
")",
"[",
"0",
"]",
"[",
"1",
":",
"]",
"else",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
... | 48.152381 | 26.714286 |
def confirm_answer(self, answer, message=None):
"""
Prompts the user to confirm a question with a yes/no prompt.
If no message is specified, the default message is: "You entered {}. Is this correct?"
:param answer: the answer to confirm.
:param message: a message to display rath... | [
"def",
"confirm_answer",
"(",
"self",
",",
"answer",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"\"\\nYou entered {0}. Is this correct?\"",
".",
"format",
"(",
"answer",
")",
"return",
"self",
".",
"prompt_for_y... | 53.090909 | 20.727273 |
def _for_element__get(self):
"""
Get/set the element this label points to. Return None if it
can't be found.
"""
id = self.get('for')
if not id:
return None
return self.body.get_element_by_id(id) | [
"def",
"_for_element__get",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"get",
"(",
"'for'",
")",
"if",
"not",
"id",
":",
"return",
"None",
"return",
"self",
".",
"body",
".",
"get_element_by_id",
"(",
"id",
")"
] | 28.444444 | 12.666667 |
def napalm_get(
task: Task,
getters: List[str],
getters_options: GetterOptionsDict = None,
**kwargs: Any
) -> Result:
"""
Gather information from network devices using napalm
Arguments:
getters: getters to use
getters_options (dict of dicts): When passing multiple getters yo... | [
"def",
"napalm_get",
"(",
"task",
":",
"Task",
",",
"getters",
":",
"List",
"[",
"str",
"]",
",",
"getters_options",
":",
"GetterOptionsDict",
"=",
"None",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Result",
":",
"device",
"=",
"task",
".",
"ho... | 30.703704 | 20.111111 |
def normalize(self):
"""
Returns a new table with values ranging from -1 to 1, reaching at least
one of these, unless there's no data.
"""
max_abs = max(self.table, key=abs)
if max_abs == 0:
raise ValueError("Can't normalize zeros")
return self / max_abs | [
"def",
"normalize",
"(",
"self",
")",
":",
"max_abs",
"=",
"max",
"(",
"self",
".",
"table",
",",
"key",
"=",
"abs",
")",
"if",
"max_abs",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Can't normalize zeros\"",
")",
"return",
"self",
"/",
"max_abs"
] | 31.111111 | 11.111111 |
def add2python(self, module=None, up=0, down=None, front=False,
must_exist=True):
'''Add a directory to the python path.
:parameter module: Optional module name to try to import once we
have found the directory
:parameter up: number of level to go up the directory... | [
"def",
"add2python",
"(",
"self",
",",
"module",
"=",
"None",
",",
"up",
"=",
"0",
",",
"down",
"=",
"None",
",",
"front",
"=",
"False",
",",
"must_exist",
"=",
"True",
")",
":",
"if",
"module",
":",
"try",
":",
"return",
"import_module",
"(",
"mod... | 36.410256 | 16.461538 |
def create_from_response_pdu(resp_pdu):
""" Create instance from response PDU.
:param resp_pdu: Byte array with request PDU.
:return: Instance of :class:`WriteSingleRegister`.
"""
write_single_register = WriteSingleRegister()
address, value = struct.unpack('>H' + conf.T... | [
"def",
"create_from_response_pdu",
"(",
"resp_pdu",
")",
":",
"write_single_register",
"=",
"WriteSingleRegister",
"(",
")",
"address",
",",
"value",
"=",
"struct",
".",
"unpack",
"(",
"'>H'",
"+",
"conf",
".",
"TYPE_CHAR",
",",
"resp_pdu",
"[",
"1",
":",
"5... | 32.928571 | 18.142857 |
def iterintervals(self, n=2):
"""Iterate over groups of `n` consecutive measurement points in the
time series.
"""
# tee the original iterator into n identical iterators
streams = tee(iter(self), n)
# advance the "cursor" on each iterator by an increasing
# offs... | [
"def",
"iterintervals",
"(",
"self",
",",
"n",
"=",
"2",
")",
":",
"# tee the original iterator into n identical iterators",
"streams",
"=",
"tee",
"(",
"iter",
"(",
"self",
")",
",",
"n",
")",
"# advance the \"cursor\" on each iterator by an increasing",
"# offset, e.g... | 35.708333 | 15.708333 |
def split(self, data):
""" Split data into list of string, each (self.width() - 1) length or less. If nul-length string
specified then empty list is returned
:param data: data to split
:return: list of str
"""
line = deepcopy(data)
line_width = (self.width() - 1)
lines = []
while len(line):
new_... | [
"def",
"split",
"(",
"self",
",",
"data",
")",
":",
"line",
"=",
"deepcopy",
"(",
"data",
")",
"line_width",
"=",
"(",
"self",
".",
"width",
"(",
")",
"-",
"1",
")",
"lines",
"=",
"[",
"]",
"while",
"len",
"(",
"line",
")",
":",
"new_line",
"="... | 21.48 | 19.44 |
def head(self, url, **kwargs):
"""Sends a HEAD request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param **kwargs: Optional arguments that ``request`` takes.
"""
kwargs.setdefault('allow_redirects', True)
return self.request(... | [
"def",
"head",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'allow_redirects'",
",",
"True",
")",
"return",
"self",
".",
"request",
"(",
"'head'",
",",
"url",
",",
"*",
"*",
"kwargs",
")"
] | 37.111111 | 17.444444 |
def _check_pid_changed(self):
"""Reads pidfile and returns False if its PID is ours, else a printable (maybe falsey) value."""
try:
with open(os.path.join(self._build_root, self._pantsd_pidfile), "r") as f:
pid_from_file = f.read()
except IOError:
return "[no file could be read]"
if ... | [
"def",
"_check_pid_changed",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_build_root",
",",
"self",
".",
"_pantsd_pidfile",
")",
",",
"\"r\"",
")",
"as",
"f",
":",
"pid_from_file",
"=",
"... | 36.363636 | 16.545455 |
def list_instances(self, filter=None):
"""List instances on GCE, optionally filtering the results.
:param str filter: Filter specification; see https://developers.google.com/compute/docs/reference/latest/instances/list for details.
:return: list of instances
"""
gce = self._conn... | [
"def",
"list_instances",
"(",
"self",
",",
"filter",
"=",
"None",
")",
":",
"gce",
"=",
"self",
".",
"_connect",
"(",
")",
"try",
":",
"request",
"=",
"gce",
".",
"instances",
"(",
")",
".",
"list",
"(",
"project",
"=",
"self",
".",
"_project_id",
... | 39.714286 | 20.095238 |
def check_refresh(opts, refresh=None):
'''
Check whether or not a refresh is necessary
Returns:
- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists
'''
return bool(
salt.utils.data.is_true(refresh) or
... | [
"def",
"check_refresh",
"(",
"opts",
",",
"refresh",
"=",
"None",
")",
":",
"return",
"bool",
"(",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"refresh",
")",
"or",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"rtag",
"(",
"opts",
")",
... | 26.428571 | 21.428571 |
def split_and_strip_without(string, exclude, separator_regexp=None):
"""Split a string into items, and trim any excess spaces
Any items in exclude are not in the returned list
>>> split_and_strip_without('fred, was, here ', ['was'])
['fred', 'here']
"""
result = split_and_strip(string, separa... | [
"def",
"split_and_strip_without",
"(",
"string",
",",
"exclude",
",",
"separator_regexp",
"=",
"None",
")",
":",
"result",
"=",
"split_and_strip",
"(",
"string",
",",
"separator_regexp",
")",
"if",
"not",
"exclude",
":",
"return",
"result",
"return",
"[",
"x",... | 34.416667 | 18.833333 |
def create_CTL(fname, tbl_name, col_list, TRUNC_OR_APPEND, delim=','):
"""
create_CTL(fname_control_file, tbl_name, src_file, cols, 'TRUNCATE')
"""
with open(fname, 'w') as ct:
ct.write('LOAD DATA\n')
ct.write(TRUNC_OR_APPEND + '\n')
ct.write('into table ' + tbl_name + '\n')
... | [
"def",
"create_CTL",
"(",
"fname",
",",
"tbl_name",
",",
"col_list",
",",
"TRUNC_OR_APPEND",
",",
"delim",
"=",
"','",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"ct",
":",
"ct",
".",
"write",
"(",
"'LOAD DATA\\n'",
")",
"ct",
"."... | 39.857143 | 12 |
def _init_client():
"""Initialize connection and create table if needed
"""
if client is not None:
return
global _mysql_kwargs, _table_name
_mysql_kwargs = {
'host': __opts__.get('mysql.host', '127.0.0.1'),
'user': __opts__.get('mysql.user', None),
'passwd': __opts__... | [
"def",
"_init_client",
"(",
")",
":",
"if",
"client",
"is",
"not",
"None",
":",
"return",
"global",
"_mysql_kwargs",
",",
"_table_name",
"_mysql_kwargs",
"=",
"{",
"'host'",
":",
"__opts__",
".",
"get",
"(",
"'mysql.host'",
",",
"'127.0.0.1'",
")",
",",
"'... | 37.357143 | 16.928571 |
def propagate_uncertainties(self, columns, depending_variables=None, cov_matrix='auto',
covariance_format="{}_{}_covariance",
uncertainty_format="{}_uncertainty"):
"""Propagates uncertainties (full covariance matrix) for a set of virtual columns.
... | [
"def",
"propagate_uncertainties",
"(",
"self",
",",
"columns",
",",
"depending_variables",
"=",
"None",
",",
"cov_matrix",
"=",
"'auto'",
",",
"covariance_format",
"=",
"\"{}_{}_covariance\"",
",",
"uncertainty_format",
"=",
"\"{}_uncertainty\"",
")",
":",
"names",
... | 51.639344 | 30.868852 |
def transition_matrix_partial_rev(C, P, S, maxiter=1000000, maxerr=1e-8):
"""Maximum likelihood estimation of transition matrix which is reversible on parts
Partially-reversible estimation of transition matrix. Maximizes the likelihood:
.. math:
P_S &=& arg max prod_{S, :} (p_ij)^c_ij \\
\... | [
"def",
"transition_matrix_partial_rev",
"(",
"C",
",",
"P",
",",
"S",
",",
"maxiter",
"=",
"1000000",
",",
"maxerr",
"=",
"1e-8",
")",
":",
"# test input",
"assert",
"np",
".",
"array_equal",
"(",
"C",
".",
"shape",
",",
"P",
".",
"shape",
")",
"# cons... | 28.938462 | 21.138462 |
def _notify_modified(self, change):
""" If a change occurs when we have a websocket connection active
notify the websocket client of the change.
"""
root = self.root_object()
if isinstance(root, Html):
name = change['name']
change = {
'ref... | [
"def",
"_notify_modified",
"(",
"self",
",",
"change",
")",
":",
"root",
"=",
"self",
".",
"root_object",
"(",
")",
"if",
"isinstance",
"(",
"root",
",",
"Html",
")",
":",
"name",
"=",
"change",
"[",
"'name'",
"]",
"change",
"=",
"{",
"'ref'",
":",
... | 34.857143 | 6.928571 |
def api_version(self, verbose=False):
'''
Get information about the API
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#api_version_information
'''
return self.__auth_req_get(self.rest_url, verbose=verbose) | [
"def",
"api_version",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"return",
"self",
".",
"__auth_req_get",
"(",
"self",
".",
"rest_url",
",",
"verbose",
"=",
"verbose",
")"
] | 41.333333 | 22.666667 |
def projected_inverse(L):
"""
Supernodal multifrontal projected inverse. The routine computes the projected inverse
.. math::
Y = P(L^{-T}L^{-1})
where :math:`L` is a Cholesky factor. On exit, the argument :math:`L` contains the
projected inverse :math:`Y`.
:param L: ... | [
"def",
"projected_inverse",
"(",
"L",
")",
":",
"assert",
"isinstance",
"(",
"L",
",",
"cspmatrix",
")",
"and",
"L",
".",
"is_factor",
"is",
"True",
",",
"\"L must be a cspmatrix factor\"",
"n",
"=",
"L",
".",
"symb",
".",
"n",
"snpost",
"=",
"L",
".",
... | 33.619718 | 27.366197 |
def set_do_not_order_list(self, restricted_list, on_error='fail'):
"""Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : container[Asset], SecurityList
The assets that cannot be ordered.
"""
if isinstance(restricted_list... | [
"def",
"set_do_not_order_list",
"(",
"self",
",",
"restricted_list",
",",
"on_error",
"=",
"'fail'",
")",
":",
"if",
"isinstance",
"(",
"restricted_list",
",",
"SecurityList",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`set_do_not_order_list(security_lists.leveraged_e... | 42.933333 | 20.366667 |
def _generateFind(self, **kwargs):
"""Generator which yields matches on AXChildren."""
for needle in self._generateChildren():
if needle._match(**kwargs):
yield needle | [
"def",
"_generateFind",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"needle",
"in",
"self",
".",
"_generateChildren",
"(",
")",
":",
"if",
"needle",
".",
"_match",
"(",
"*",
"*",
"kwargs",
")",
":",
"yield",
"needle"
] | 41.4 | 5.2 |
def import_template_json(template_json_string,allow_update=True, **kwargs):
"""
Add the template, type and typeattrs described
in a JSON file.
Delete type, typeattr entries in the DB that are not in the XML file
The assumption is that they have been deleted and are no longer require... | [
"def",
"import_template_json",
"(",
"template_json_string",
",",
"allow_update",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"try",
":",
"template_dict",
"=",
"json",
".",
"loads",
"(",
"temp... | 38.7 | 30.3 |
def info(name):
'''
Return user information
CLI Example:
.. code-block:: bash
salt '*' user.info root
'''
ret = {}
try:
data = pwd.getpwnam(name)
ret['gid'] = data.pw_gid
ret['groups'] = list_groups(name)
ret['home'] = data.pw_dir
ret['name'... | [
"def",
"info",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"}",
"try",
":",
"data",
"=",
"pwd",
".",
"getpwnam",
"(",
"name",
")",
"ret",
"[",
"'gid'",
"]",
"=",
"data",
".",
"pw_gid",
"ret",
"[",
"'groups'",
"]",
"=",
"list_groups",
"(",
"name",
"... | 26.8125 | 15.5 |
def console_size(fd=1):
"""Return console size as a (LINES, COLUMNS) tuple"""
try:
import fcntl
import termios
import struct
except ImportError:
size = os.getenv('LINES', 25), os.getenv('COLUMNS', 80)
else:
size = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGW... | [
"def",
"console_size",
"(",
"fd",
"=",
"1",
")",
":",
"try",
":",
"import",
"fcntl",
"import",
"termios",
"import",
"struct",
"except",
"ImportError",
":",
"size",
"=",
"os",
".",
"getenv",
"(",
"'LINES'",
",",
"25",
")",
",",
"os",
".",
"getenv",
"(... | 32.25 | 20.666667 |
def release_branches(self):
"""A dictionary that maps branch names to :class:`Release` objects."""
self.ensure_release_scheme('branches')
return dict((r.revision.branch, r) for r in self.releases.values()) | [
"def",
"release_branches",
"(",
"self",
")",
":",
"self",
".",
"ensure_release_scheme",
"(",
"'branches'",
")",
"return",
"dict",
"(",
"(",
"r",
".",
"revision",
".",
"branch",
",",
"r",
")",
"for",
"r",
"in",
"self",
".",
"releases",
".",
"values",
"(... | 56.5 | 13.5 |
def inc_from_lat(lat):
"""
Calculate inclination predicted from latitude using the dipole equation
Parameter
----------
lat : latitude in degrees
Returns
-------
inc : inclination calculated using the dipole equation
"""
rad = old_div(np.pi, 180.)
inc = old_div(np.arctan(2 ... | [
"def",
"inc_from_lat",
"(",
"lat",
")",
":",
"rad",
"=",
"old_div",
"(",
"np",
".",
"pi",
",",
"180.",
")",
"inc",
"=",
"old_div",
"(",
"np",
".",
"arctan",
"(",
"2",
"*",
"np",
".",
"tan",
"(",
"lat",
"*",
"rad",
")",
")",
",",
"rad",
")",
... | 23.133333 | 21.666667 |
def _start_collective_solver(self, state):
'''
Determines who from all the monitors monitoring this agent should
resolve the issue.
'''
own_address = state.agent.get_own_address()
monitors = [IRecipient(x) for x in state.descriptor.partners
if x.role =... | [
"def",
"_start_collective_solver",
"(",
"self",
",",
"state",
")",
":",
"own_address",
"=",
"state",
".",
"agent",
".",
"get_own_address",
"(",
")",
"monitors",
"=",
"[",
"IRecipient",
"(",
"x",
")",
"for",
"x",
"in",
"state",
".",
"descriptor",
".",
"pa... | 46.176471 | 17.117647 |
def build(self) -> str:
"""Return HTML representation of this document."""
self._set_autoreload()
return ''.join(child.html for child in self.childNodes) | [
"def",
"build",
"(",
"self",
")",
"->",
"str",
":",
"self",
".",
"_set_autoreload",
"(",
")",
"return",
"''",
".",
"join",
"(",
"child",
".",
"html",
"for",
"child",
"in",
"self",
".",
"childNodes",
")"
] | 43.5 | 12.5 |
def single(self, predicate):
"""
Returns single element that matches given predicate.
Raises:
* NoMatchingElement error if no matching elements are found
* MoreThanOneMatchingElement error if more than one matching
element is found
:param predicate: pr... | [
"def",
"single",
"(",
"self",
",",
"predicate",
")",
":",
"result",
"=",
"self",
".",
"where",
"(",
"predicate",
")",
".",
"to_list",
"(",
")",
"count",
"=",
"len",
"(",
"result",
")",
"if",
"count",
"==",
"0",
":",
"raise",
"NoMatchingElement",
"(",... | 38.631579 | 16.631579 |
def url(section="postGIS", config_file=None):
""" Retrieve the URL used to connect to the database.
Use this if you have your own means of accessing the database and do not
want to use :func:`engine` or :func:`connection`.
Parameters
----------
section : str, optional
The `config.ini` ... | [
"def",
"url",
"(",
"section",
"=",
"\"postGIS\"",
",",
"config_file",
"=",
"None",
")",
":",
"cfg",
".",
"load_config",
"(",
"config_file",
")",
"try",
":",
"pw",
"=",
"keyring",
".",
"get_password",
"(",
"cfg",
".",
"get",
"(",
"section",
",",
"\"data... | 37 | 23.984127 |
def inspect(obj):
"Open the inspector windows for a given object"
from gui.tools.inspector import InspectorTool
inspector = InspectorTool()
inspector.show(obj)
return inspector | [
"def",
"inspect",
"(",
"obj",
")",
":",
"from",
"gui",
".",
"tools",
".",
"inspector",
"import",
"InspectorTool",
"inspector",
"=",
"InspectorTool",
"(",
")",
"inspector",
".",
"show",
"(",
"obj",
")",
"return",
"inspector"
] | 31.833333 | 14.833333 |
def transform_grid_from_reference_frame(self, grid):
"""Transform a grid of (y,x) coordinates from the reference frame of the profile to the original observer \
reference frame, including a translation from the profile's centre.
Parameters
----------
grid : TransformedGrid(ndarr... | [
"def",
"transform_grid_from_reference_frame",
"(",
"self",
",",
"grid",
")",
":",
"transformed",
"=",
"np",
".",
"add",
"(",
"grid",
",",
"self",
".",
"centre",
")",
"return",
"transformed",
".",
"view",
"(",
"TransformedGrid",
")"
] | 45.090909 | 16.363636 |
def _get_choices(self):
"""
Returns menus specified in ``PAGE_MENU_TEMPLATES`` unless you provide
some custom choices in the field definition.
"""
if self._overridden_choices:
# Note: choices is a property on Field bound to _get_choices().
return self._cho... | [
"def",
"_get_choices",
"(",
"self",
")",
":",
"if",
"self",
".",
"_overridden_choices",
":",
"# Note: choices is a property on Field bound to _get_choices().",
"return",
"self",
".",
"_choices",
"else",
":",
"menus",
"=",
"getattr",
"(",
"settings",
",",
"\"PAGE_MENU_... | 39.545455 | 15 |
def angle_as_point(self, angle):
'''
Converts a given angle in degrees to the point coordinates on the arc's circle.
Inverse of point_to_angle.
>>> Arc((1, 1), 1, 0, 0, True).angle_as_point(0)
array([ 2., 1.])
>>> Arc((1, 1), 1, 0, 0, True).angle_as_point(90)
... | [
"def",
"angle_as_point",
"(",
"self",
",",
"angle",
")",
":",
"angle_rad",
"=",
"angle",
"*",
"np",
".",
"pi",
"/",
"180.0",
"return",
"self",
".",
"center",
"+",
"self",
".",
"radius",
"*",
"np",
".",
"array",
"(",
"[",
"np",
".",
"cos",
"(",
"a... | 40.142857 | 21.428571 |
def editRecord(self, record, pos=None):
"""
Prompts the user to edit using a preset editor defined in the
setRecordEditors method.
:param record | <orb.Table>
:return <bool> | success
"""
typ = type(record)
ed... | [
"def",
"editRecord",
"(",
"self",
",",
"record",
",",
"pos",
"=",
"None",
")",
":",
"typ",
"=",
"type",
"(",
"record",
")",
"editor",
"=",
"self",
".",
"_recordEditors",
".",
"get",
"(",
"typ",
")",
"if",
"not",
"editor",
":",
"return",
"False",
"i... | 31.238095 | 13.333333 |
def _log(self, message):
"""Log a debug message prefixed with order book name.
:param message: Debug message.
:type message: str | unicode
"""
self._logger.debug("{}: {}".format(self.name, message)) | [
"def",
"_log",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"{}: {}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"message",
")",
")"
] | 33.285714 | 12.142857 |
def wl_uris(self):
"""\
Returns cable IRIs to WikiLeaks (mirrors).
"""
def year_month(d):
date, time = d.split()
return date.split('-')[:2]
if not self.created:
raise ValueError('The "created" property must be provided')
year, month = y... | [
"def",
"wl_uris",
"(",
"self",
")",
":",
"def",
"year_month",
"(",
"d",
")",
":",
"date",
",",
"time",
"=",
"d",
".",
"split",
"(",
")",
"return",
"date",
".",
"split",
"(",
"'-'",
")",
"[",
":",
"2",
"]",
"if",
"not",
"self",
".",
"created",
... | 32.5 | 11.555556 |
def get_obj_name(obj, full=True):
""" Gets the #str name of @obj
@obj: any python object
@full: #bool returns with parent name as well if True
-> #str object name
..
from redis_structures.debug import get_parent_obj
get_obj_name(get_obj_name)
# ... | [
"def",
"get_obj_name",
"(",
"obj",
",",
"full",
"=",
"True",
")",
":",
"has_name_attr",
"=",
"hasattr",
"(",
"obj",
",",
"'__name__'",
")",
"if",
"has_name_attr",
"and",
"obj",
".",
"__name__",
"==",
"\"<lambda>\"",
":",
"try",
":",
"src",
"=",
"whitespa... | 31.606061 | 15.757576 |
def populate_native_libraries(version):
"""Populates ``binary-extension.rst`` with release-specific data.
Args:
version (str): The current version.
"""
with open(BINARY_EXT_TEMPLATE, "r") as file_obj:
template = file_obj.read()
contents = template.format(revision=version)
with o... | [
"def",
"populate_native_libraries",
"(",
"version",
")",
":",
"with",
"open",
"(",
"BINARY_EXT_TEMPLATE",
",",
"\"r\"",
")",
"as",
"file_obj",
":",
"template",
"=",
"file_obj",
".",
"read",
"(",
")",
"contents",
"=",
"template",
".",
"format",
"(",
"revision... | 34.636364 | 10.636364 |
def fetch_synchronous(self, endpoint_name, query_params=None):
"""Calls this instance's request_client's get method with the
specified component endpoint"""
endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name
if query_params is None:
query_params... | [
"def",
"fetch_synchronous",
"(",
"self",
",",
"endpoint_name",
",",
"query_params",
"=",
"None",
")",
":",
"endpoint_url",
"=",
"constants",
".",
"URL_PREFIX",
"+",
"\"/\"",
"+",
"self",
".",
"_version",
"+",
"\"/\"",
"+",
"endpoint_name",
"if",
"query_params"... | 38.5 | 23.5 |
def flavor_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all image flavors.
Generates a list of image flavors available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple ... | [
"def",
"flavor_field_data",
"(",
"request",
",",
"include_empty_option",
"=",
"False",
")",
":",
"flavors",
"=",
"flavor_list",
"(",
"request",
")",
"if",
"flavors",
":",
"flavors_list",
"=",
"sort_flavor_list",
"(",
"request",
",",
"flavors",
")",
"if",
"incl... | 33.666667 | 18.904762 |
def __ensure_provisioning_alarm(table_name, key_name):
""" Ensure that provisioning alarm threshold is not exceeded
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
"""
lookback_window_start = get_table_op... | [
"def",
"__ensure_provisioning_alarm",
"(",
"table_name",
",",
"key_name",
")",
":",
"lookback_window_start",
"=",
"get_table_option",
"(",
"key_name",
",",
"'lookback_window_start'",
")",
"lookback_period",
"=",
"get_table_option",
"(",
"key_name",
",",
"'lookback_period'... | 40.923913 | 15.673913 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.