text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_config_parameter_boolean(config: ConfigParser,
section: str,
param: str,
default: bool) -> bool:
"""
Get Boolean parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigPars... | [
"def",
"get_config_parameter_boolean",
"(",
"config",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"param",
":",
"str",
",",
"default",
":",
"bool",
")",
"->",
"bool",
":",
"try",
":",
"value",
"=",
"config",
".",
"getboolean",
"(",
"section",
"... | 35.086957 | 0.001206 |
def close(self):
"""
Closes the connection to the bridge.
"""
self.is_closed = True
self.is_ready = False
self._command_queue.put(None) | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"is_closed",
"=",
"True",
"self",
".",
"is_ready",
"=",
"False",
"self",
".",
"_command_queue",
".",
"put",
"(",
"None",
")"
] | 25.285714 | 0.010929 |
def com_google_fonts_check_negative_advance_width(ttFont):
""" Check that advance widths cannot be inferred as negative. """
failed = False
for glyphName in ttFont["glyf"].glyphs:
coords = ttFont["glyf"][glyphName].coordinates
rightX = coords[-3][0]
leftX = coords[-4][0]
advwidth = rightX - leftX
... | [
"def",
"com_google_fonts_check_negative_advance_width",
"(",
"ttFont",
")",
":",
"failed",
"=",
"False",
"for",
"glyphName",
"in",
"ttFont",
"[",
"\"glyf\"",
"]",
".",
"glyphs",
":",
"coords",
"=",
"ttFont",
"[",
"\"glyf\"",
"]",
"[",
"glyphName",
"]",
".",
... | 41.764706 | 0.009642 |
def _add_tabular_layer(self, tabular_layer, layer_name, save_style=False):
"""Add a tabular layer to the geopackage.
:param tabular_layer: The layer to add.
:type tabular_layer: QgsVectorLayer
:param layer_name: The name of the layer in the datastore.
:type layer_name: str
... | [
"def",
"_add_tabular_layer",
"(",
"self",
",",
"tabular_layer",
",",
"layer_name",
",",
"save_style",
"=",
"False",
")",
":",
"return",
"self",
".",
"_add_vector_layer",
"(",
"tabular_layer",
",",
"layer_name",
",",
"save_style",
")"
] | 38.333333 | 0.002424 |
def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
return s.uint32 + s.uint64 + s.uint32 + s.uint16 + s.uint32 + GetVarSize(self.UserAgent) + s.uint32 + s.uint8 | [
"def",
"Size",
"(",
"self",
")",
":",
"return",
"s",
".",
"uint32",
"+",
"s",
".",
"uint64",
"+",
"s",
".",
"uint32",
"+",
"s",
".",
"uint16",
"+",
"s",
".",
"uint32",
"+",
"GetVarSize",
"(",
"self",
".",
"UserAgent",
")",
"+",
"s",
".",
"uint3... | 30.25 | 0.012048 |
def addparentstofks(rels, fks):
"""
Get a list of relations, between parents and sons and a dict of
clases named in dia, and modifies the fks to add the parent as fk to get
order on the output of classes and replaces the base class of the son, to
put the class parent name.
"""
for j in rels:... | [
"def",
"addparentstofks",
"(",
"rels",
",",
"fks",
")",
":",
"for",
"j",
"in",
"rels",
":",
"son",
"=",
"index",
"(",
"fks",
",",
"j",
"[",
"1",
"]",
")",
"parent",
"=",
"index",
"(",
"fks",
",",
"j",
"[",
"0",
"]",
")",
"fks",
"[",
"son",
... | 39.692308 | 0.001894 |
def tuple_alter(tup, *pairs):
"""Return a copy of a tuple with some elements altered.
:param tup: The tuple to be copied.
:param pairs: Any number of (index, func) tuples where index is the index
of the item to alter and the new value is func(tup[index]).
"""
# timeit says that this is fast... | [
"def",
"tuple_alter",
"(",
"tup",
",",
"*",
"pairs",
")",
":",
"# timeit says that this is faster than a similar",
"tuple_list",
"=",
"list",
"(",
"tup",
")",
"for",
"i",
",",
"f",
"in",
"pairs",
":",
"tuple_list",
"[",
"i",
"]",
"=",
"f",
"(",
"tuple_list... | 37.166667 | 0.002188 |
def toxml(self):
"""
Exports this object into a LEMS XML object
"""
return '<Record quantity="{0}" scale="{1}" color="{2}" id="{3}"/>'.format(self.quantity,
self.scale,
... | [
"def",
"toxml",
"(",
"self",
")",
":",
"return",
"'<Record quantity=\"{0}\" scale=\"{1}\" color=\"{2}\" id=\"{3}\"/>'",
".",
"format",
"(",
"self",
".",
"quantity",
",",
"self",
".",
"scale",
",",
"self",
".",
"color",
",",
"self",
".",
"id",
")"
] | 48.111111 | 0.020408 |
def own_name(self, name, flags=0, name_aquired=None, name_lost=None):
"""[DEPRECATED] Asynchronously aquires a bus name.
Starts acquiring name on the bus specified by bus_type and calls
name_acquired and name_lost when the name is acquired respectively lost.
To receive name_aquired and name_lost callbacks, yo... | [
"def",
"own_name",
"(",
"self",
",",
"name",
",",
"flags",
"=",
"0",
",",
"name_aquired",
"=",
"None",
",",
"name_lost",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"own_name() is deprecated, use request_name() instead.\"",
",",
"DeprecationWarning",
... | 36.5 | 0.029042 |
def create_redshift(self, **kwargs):
"""
:rtype: Engine
"""
return self._ce(
self._ccs(self.DialectAndDriver.redshift_psycopg2), **kwargs
) | [
"def",
"create_redshift",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_ce",
"(",
"self",
".",
"_ccs",
"(",
"self",
".",
"DialectAndDriver",
".",
"redshift_psycopg2",
")",
",",
"*",
"*",
"kwargs",
")"
] | 26.428571 | 0.010471 |
def run(command, parser, cl_args, unknown_args):
'''
runs parser
'''
action = cl_args["action"]
if action == Action.SET:
call_editor(get_inventory_file(cl_args))
update_config_files(cl_args)
elif action == Action.CLUSTER:
action_type = cl_args["type"]
if action_type == Cluster.START:
s... | [
"def",
"run",
"(",
"command",
",",
"parser",
",",
"cl_args",
",",
"unknown_args",
")",
":",
"action",
"=",
"cl_args",
"[",
"\"action\"",
"]",
"if",
"action",
"==",
"Action",
".",
"SET",
":",
"call_editor",
"(",
"get_inventory_file",
"(",
"cl_args",
")",
... | 33.631579 | 0.012928 |
def update_components(self, forcereload=False, forcerebuild=False,
forcecopy=True, install=False):
"""Check all known entry points for components. If necessary,
manage configuration updates"""
# TODO: See if we can pull out major parts of the component handling.
... | [
"def",
"update_components",
"(",
"self",
",",
"forcereload",
"=",
"False",
",",
"forcerebuild",
"=",
"False",
",",
"forcecopy",
"=",
"True",
",",
"install",
"=",
"False",
")",
":",
"# TODO: See if we can pull out major parts of the component handling.",
"# They are also... | 42.797753 | 0.00077 |
def setCovariance(self,cov):
""" set hyperparameters from given covariance """
chol = LA.cholesky(cov,lower=True)
params = chol[sp.tril_indices(self.dim)]
self.setParams(params) | [
"def",
"setCovariance",
"(",
"self",
",",
"cov",
")",
":",
"chol",
"=",
"LA",
".",
"cholesky",
"(",
"cov",
",",
"lower",
"=",
"True",
")",
"params",
"=",
"chol",
"[",
"sp",
".",
"tril_indices",
"(",
"self",
".",
"dim",
")",
"]",
"self",
".",
"set... | 41 | 0.019139 |
def RestoreServer(server,group,alias,location):
"""Restores an archived server.
https://www.centurylinkcloud.com/api-docs/v1/#restoreserver
:param server: archived server to restore
:param group: name of group or group ID for server to belong to
:param alias: short code for a particular account. If None wi... | [
"def",
"RestoreServer",
"(",
"server",
",",
"group",
",",
"alias",
",",
"location",
")",
":",
"if",
"alias",
"is",
"None",
":",
"alias",
"=",
"clc",
".",
"v1",
".",
"Account",
".",
"GetAlias",
"(",
")",
"if",
"location",
"is",
"None",
":",
"location"... | 50.055556 | 0.040305 |
def CopyToPath(self):
"""Copies the shell items to a path.
Returns:
str: converted shell item list path or None.
"""
number_of_path_segments = len(self._path_segments)
if number_of_path_segments == 0:
return None
strings = [self._path_segments[0]]
number_of_path_segments -= 1
... | [
"def",
"CopyToPath",
"(",
"self",
")",
":",
"number_of_path_segments",
"=",
"len",
"(",
"self",
".",
"_path_segments",
")",
"if",
"number_of_path_segments",
"==",
"0",
":",
"return",
"None",
"strings",
"=",
"[",
"self",
".",
"_path_segments",
"[",
"0",
"]",
... | 33.333333 | 0.009719 |
def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t):
pt = zeros((range_x, range_y, 3))
"omp parallel for private(i,j,k,tmp)"
for i in xrange(range_x):
for j in xrange(range_y):
pt[i,j,0], pt[i,j,1] = (xmin+step*i)*180/math.pi, (ymin+step*j)*180/math.pi
for k in... | [
"def",
"run",
"(",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
",",
"step",
",",
"range_",
",",
"range_x",
",",
"range_y",
",",
"t",
")",
":",
"pt",
"=",
"zeros",
"(",
"(",
"range_x",
",",
"range_y",
",",
"3",
")",
")",
"for",
"i",
"in",
"... | 52.909091 | 0.033784 |
def parse_ouput(self, data, context, response):
'''
Parse the output from Invoke-BloodHound
'''
parsedData = data.split("!-!")
nameList = ['user_sessions', 'group_membership.csv', 'acls.csv', 'local_admins.csv', 'trusts.csv']
for x in range(0, len(parsedData)):
... | [
"def",
"parse_ouput",
"(",
"self",
",",
"data",
",",
"context",
",",
"response",
")",
":",
"parsedData",
"=",
"data",
".",
"split",
"(",
"\"!-!\"",
")",
"nameList",
"=",
"[",
"'user_sessions'",
",",
"'group_membership.csv'",
",",
"'acls.csv'",
",",
"'local_a... | 79.107143 | 0.010259 |
async def rollback(self):
"""Roll back this transaction."""
if not self._parent._is_active:
return
await self._do_rollback()
self._is_active = False | [
"async",
"def",
"rollback",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_parent",
".",
"_is_active",
":",
"return",
"await",
"self",
".",
"_do_rollback",
"(",
")",
"self",
".",
"_is_active",
"=",
"False"
] | 31.166667 | 0.010417 |
def _numba_linalg_solve(a, b):
"""
Solve the linear equation ax = b directly calling a Numba internal
function. The data in `a` and `b` are interpreted in Fortran order,
and dtype of `a` and `b` must be the same, one of {float32, float64,
complex64, complex128}. `a` and `b` are modified in place, an... | [
"def",
"_numba_linalg_solve",
"(",
"a",
",",
"b",
")",
":",
"numba_xgesv",
"=",
"_LAPACK",
"(",
")",
".",
"numba_xgesv",
"(",
"a",
".",
"dtype",
")",
"kind",
"=",
"ord",
"(",
"_blas_kinds",
"[",
"a",
".",
"dtype",
"]",
")",
"def",
"_numba_linalg_solve_... | 27.788462 | 0.000668 |
def wait(self, timeout=-1):
"""Wait until the result is available or until `timeout` seconds pass.
This method always returns None.
"""
if self._ready:
return
self._ready = self._client.wait(self.msg_ids, timeout)
if self._ready:
try:
... | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"_ready",
":",
"return",
"self",
".",
"_ready",
"=",
"self",
".",
"_client",
".",
"wait",
"(",
"self",
".",
"msg_ids",
",",
"timeout",
")",
"if",
"self",
".",... | 37.555556 | 0.001923 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self,
'customization_id') and self.customization_id is not None:
_dict['customization_id'] = self.customization_id
if hasattr(self, 'created') and self.created... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'customization_id'",
")",
"and",
"self",
".",
"customization_id",
"is",
"not",
"None",
":",
"_dict",
"[",
"'customization_id'",
"]",
"=",
"self",
".",
... | 50.714286 | 0.001382 |
def restore(self):
"""
Restore the application config files.
Algorithm:
if exists mackup/file
if exists home/file
are you sure ?
if sure
rm home/file
link mackup/file home/file
else
... | [
"def",
"restore",
"(",
"self",
")",
":",
"# For each file used by the application",
"for",
"filename",
"in",
"self",
".",
"files",
":",
"(",
"home_filepath",
",",
"mackup_filepath",
")",
"=",
"self",
".",
"getFilepaths",
"(",
"filename",
")",
"# If the file exists... | 45.56338 | 0.000605 |
def _format_conditions_and_actions(self, raw_data):
"""
This function gets a set of actions and conditionswith the following
format:
{'action-0': 'repeat',
'action-1': 'repeat',
'analysisservice-0': '30cd952b0bb04a05ac27b70ada7feab2',
'analysisservice-1': ... | [
"def",
"_format_conditions_and_actions",
"(",
"self",
",",
"raw_data",
")",
":",
"keys",
"=",
"raw_data",
".",
"keys",
"(",
")",
"# 'formatted_action_row' is the dict which will be added in the",
"# 'value' list",
"formatted_set",
"=",
"{",
"}",
"# Filling the dict with the... | 37.596774 | 0.000836 |
def store_reg(self, value, reg_type, reg_name, name=''):
"""
Store an LLVM value inside a register
Example: store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax")
"""
ftype = types.FunctionType(types.VoidType(), [reg_type])
return self.asm(ftype, "", "{%s}" % ... | [
"def",
"store_reg",
"(",
"self",
",",
"value",
",",
"reg_type",
",",
"reg_name",
",",
"name",
"=",
"''",
")",
":",
"ftype",
"=",
"types",
".",
"FunctionType",
"(",
"types",
".",
"VoidType",
"(",
")",
",",
"[",
"reg_type",
"]",
")",
"return",
"self",
... | 49.142857 | 0.008571 |
def get_allowed_permissions_for(brain_or_object, user=None):
"""Get the allowed permissions for the given object
Code extracted from `IRoleManager.manage_getUserRolesAndPermissions`
:param brain_or_object: Catalog brain or object
:param user: A user ID, user object or None (for the current user)
:... | [
"def",
"get_allowed_permissions_for",
"(",
"brain_or_object",
",",
"user",
"=",
"None",
")",
":",
"allowed",
"=",
"[",
"]",
"user",
"=",
"get_user",
"(",
"user",
")",
"obj",
"=",
"api",
".",
"get_object",
"(",
"brain_or_object",
")",
"for",
"permission",
"... | 38 | 0.001605 |
def fn_getdatetime_list(fn):
"""Extract all datetime strings from input filename
"""
#Want to split last component
fn = os.path.split(os.path.splitext(fn)[0])[-1]
import re
#WV01_12JUN152223255-P1BS_R1C1-102001001B3B9800__WV01_12JUN152224050-P1BS_R1C1-102001001C555C00-DEM_4x.tif
#Need to par... | [
"def",
"fn_getdatetime_list",
"(",
"fn",
")",
":",
"#Want to split last component",
"fn",
"=",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"fn",
")",
"[",
"0",
"]",
")",
"[",
"-",
"1",
"]",
"import",
"re",
"#WV01_12... | 47.175439 | 0.014208 |
def __get_last_update_time():
'''Returns last FTP site update time'''
now = datetime.datetime.utcnow()
# Get the first Tuesday of the month
first_tuesday = __get_first_tuesday(now)
if first_tuesday < now:
return first_tuesday
else:
first_of_month = datetime.datetime(now.year, n... | [
"def",
"__get_last_update_time",
"(",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"# Get the first Tuesday of the month",
"first_tuesday",
"=",
"__get_first_tuesday",
"(",
"now",
")",
"if",
"first_tuesday",
"<",
"now",
":",
"return"... | 33.307692 | 0.002247 |
def as_dtype(self):
"""
represent the heading as a numpy dtype
"""
return np.dtype(dict(
names=self.names,
formats=[v.dtype for v in self.attributes.values()])) | [
"def",
"as_dtype",
"(",
"self",
")",
":",
"return",
"np",
".",
"dtype",
"(",
"dict",
"(",
"names",
"=",
"self",
".",
"names",
",",
"formats",
"=",
"[",
"v",
".",
"dtype",
"for",
"v",
"in",
"self",
".",
"attributes",
".",
"values",
"(",
")",
"]",
... | 30 | 0.009259 |
def create_deeper(self,
new_t1,
new_t2,
child_relationship_class,
child_relationship_param=None,
report_type=None):
"""
Start a new comparison level and correctly link it to this one.
:r... | [
"def",
"create_deeper",
"(",
"self",
",",
"new_t1",
",",
"new_t2",
",",
"child_relationship_class",
",",
"child_relationship_param",
"=",
"None",
",",
"report_type",
"=",
"None",
")",
":",
"level",
"=",
"self",
".",
"all_down",
"result",
"=",
"DiffLevel",
"(",... | 36.333333 | 0.010432 |
def package(self):
"""str: Package `name-version-release` string."""
return u'{0}-{1}-{2}'.format(self.name,
self.version,
self.release) | [
"def",
"package",
"(",
"self",
")",
":",
"return",
"u'{0}-{1}-{2}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"version",
",",
"self",
".",
"release",
")"
] | 44.4 | 0.00885 |
def GetVersion():
"""Gets the version from googleads/common.py.
We can't import this directly because new users would get ImportErrors on our
third party dependencies.
Returns:
The version of the library.
"""
with open(os.path.join('googleads', 'common.py')) as versions_file:
source = versions_fil... | [
"def",
"GetVersion",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'googleads'",
",",
"'common.py'",
")",
")",
"as",
"versions_file",
":",
"source",
"=",
"versions_file",
".",
"read",
"(",
")",
"return",
"re",
".",
"search",... | 31.583333 | 0.010256 |
def get_dtype_kinds(l):
"""
Parameters
----------
l : list of arrays
Returns
-------
a set of kinds that exist in this list of arrays
"""
typs = set()
for arr in l:
dtype = arr.dtype
if is_categorical_dtype(dtype):
typ = 'category'
elif is_s... | [
"def",
"get_dtype_kinds",
"(",
"l",
")",
":",
"typs",
"=",
"set",
"(",
")",
"for",
"arr",
"in",
"l",
":",
"dtype",
"=",
"arr",
".",
"dtype",
"if",
"is_categorical_dtype",
"(",
"dtype",
")",
":",
"typ",
"=",
"'category'",
"elif",
"is_sparse",
"(",
"ar... | 25.307692 | 0.001951 |
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: he... | [
"def",
"best_match",
"(",
"supported",
",",
"header",
")",
":",
"split_header",
"=",
"_filter_blank",
"(",
"header",
".",
"split",
"(",
"','",
")",
")",
"parsed_header",
"=",
"[",
"parse_media_range",
"(",
"r",
")",
"for",
"r",
"in",
"split_header",
"]",
... | 36.3 | 0.000894 |
def check_version(self, check, timeout=None, metadata=None,
credentials=None):
"""Returns the version of the Dgraph instance."""
return self.stub.CheckVersion(check, timeout=timeout,
metadata=metadata,
cred... | [
"def",
"check_version",
"(",
"self",
",",
"check",
",",
"timeout",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"credentials",
"=",
"None",
")",
":",
"return",
"self",
".",
"stub",
".",
"CheckVersion",
"(",
"check",
",",
"timeout",
"=",
"timeout",
"... | 55.833333 | 0.008824 |
def _patch_tf(tf):
"""Patch TF to maintain compatibility across versions."""
global TF_PATCH
if TF_PATCH:
return
v_1_12 = distutils.version.LooseVersion("1.12.0")
v_1_13 = distutils.version.LooseVersion("1.13.0")
v_2 = distutils.version.LooseVersion("2.0.0")
tf_version = distutils.version.LooseVersio... | [
"def",
"_patch_tf",
"(",
"tf",
")",
":",
"global",
"TF_PATCH",
"if",
"TF_PATCH",
":",
"return",
"v_1_12",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"\"1.12.0\"",
")",
"v_1_13",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"... | 29.7 | 0.017945 |
def get_ocv_old(self, cycle_number=None, ocv_type='ocv', dataset_number=None):
"""Find ocv data in DataSet (voltage vs time).
Args:
cycle_number (int): find for all cycles if None.
ocv_type ("ocv", "ocvrlx_up", "ocvrlx_down"):
ocv - get up and down (default)... | [
"def",
"get_ocv_old",
"(",
"self",
",",
"cycle_number",
"=",
"None",
",",
"ocv_type",
"=",
"'ocv'",
",",
"dataset_number",
"=",
"None",
")",
":",
"# function for getting ocv curves",
"dataset_number",
"=",
"self",
".",
"_validate_dataset_number",
"(",
"dataset_numbe... | 45.705882 | 0.00084 |
def modify_colorpoint(self, n, position=0.5, color1=[1.0,1.0,1.0], color2=[1.0,1.0,1.0]):
"""
Changes the values of an existing colorpoint, then updates the colormap.
"""
if n==0.0 : position = 0.0
elif n==len(self._colorpoint_list)-1: position = 1.0
... | [
"def",
"modify_colorpoint",
"(",
"self",
",",
"n",
",",
"position",
"=",
"0.5",
",",
"color1",
"=",
"[",
"1.0",
",",
"1.0",
",",
"1.0",
"]",
",",
"color2",
"=",
"[",
"1.0",
",",
"1.0",
",",
"1.0",
"]",
")",
":",
"if",
"n",
"==",
"0.0",
":",
"... | 46.272727 | 0.030829 |
def getLayout(kind=None,theme=None,title='',xTitle='',yTitle='',zTitle='',barmode='',bargap=None,bargroupgap=None,
margin=None, dimensions=None, width=None, height=None,
annotations=None,is3d=False,**kwargs):
"""
Generates a plotly Layout
Parameters:
-----------
theme : string
Layout Theme
solar... | [
"def",
"getLayout",
"(",
"kind",
"=",
"None",
",",
"theme",
"=",
"None",
",",
"title",
"=",
"''",
",",
"xTitle",
"=",
"''",
",",
"yTitle",
"=",
"''",
",",
"zTitle",
"=",
"''",
",",
"barmode",
"=",
"''",
",",
"bargap",
"=",
"None",
",",
"bargroupg... | 25.857143 | 0.052174 |
def delete_organization_course(organization, course_key):
"""
Removes an existing organization-course relationship from app/local state
No response currently defined for this operation
"""
try:
relationship = internal.OrganizationCourse.objects.get(
organization=organization['id'... | [
"def",
"delete_organization_course",
"(",
"organization",
",",
"course_key",
")",
":",
"try",
":",
"relationship",
"=",
"internal",
".",
"OrganizationCourse",
".",
"objects",
".",
"get",
"(",
"organization",
"=",
"organization",
"[",
"'id'",
"]",
",",
"course_id... | 41.0625 | 0.001488 |
def connection_made(self, transport: asyncio.BaseTransport) -> None:
"""
Configure write buffer limits.
The high-water limit is defined by ``self.write_limit``.
The low-water limit currently defaults to ``self.write_limit // 4`` in
:meth:`~asyncio.WriteTransport.set_write_buffe... | [
"def",
"connection_made",
"(",
"self",
",",
"transport",
":",
"asyncio",
".",
"BaseTransport",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"%s - event = connection_made(%s)\"",
",",
"self",
".",
"side",
",",
"transport",
")",
"# mypy thinks transport is... | 44.722222 | 0.002433 |
def on_graphs_menu_close(self, update):
"""Return to main screen and update sensor that
are active in the view"""
logging.info("closing sensor menu, update=%s", update)
if update:
for sensor, visible_sensors in \
self.graphs_menu.active_sensors.items():
... | [
"def",
"on_graphs_menu_close",
"(",
"self",
",",
"update",
")",
":",
"logging",
".",
"info",
"(",
"\"closing sensor menu, update=%s\"",
",",
"update",
")",
"if",
"update",
":",
"for",
"sensor",
",",
"visible_sensors",
"in",
"self",
".",
"graphs_menu",
".",
"ac... | 46.473684 | 0.00222 |
async def _wait(self):
'''
Wait on the other editatoms who are constructing nodes my new nodes refer to
'''
for buid in self.otherbldgbuids:
nodeevnt = self.allbldgbuids.get(buid)
if nodeevnt is None:
continue
await nodeevnt[1].wait() | [
"async",
"def",
"_wait",
"(",
"self",
")",
":",
"for",
"buid",
"in",
"self",
".",
"otherbldgbuids",
":",
"nodeevnt",
"=",
"self",
".",
"allbldgbuids",
".",
"get",
"(",
"buid",
")",
"if",
"nodeevnt",
"is",
"None",
":",
"continue",
"await",
"nodeevnt",
"... | 34.444444 | 0.009434 |
def validate_token_request(self, request):
"""Check the token request for normal and fatal errors.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
This method is very similar to validate_authorization_request in
the AuthorizationCodeGrant but differ in ... | [
"def",
"validate_token_request",
"(",
"self",
",",
"request",
")",
":",
"# First check for fatal errors",
"# If the request fails due to a missing, invalid, or mismatching",
"# redirection URI, or if the client identifier is missing or invalid,",
"# the authorization server SHOULD inform the r... | 45.98 | 0.002342 |
async def info(self, session, *, dc=None, watch=None, consistency=None):
"""Queries a given session
Parameters:
session (ObjectID): Session ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Block... | [
"async",
"def",
"info",
"(",
"self",
",",
"session",
",",
"*",
",",
"dc",
"=",
"None",
",",
"watch",
"=",
"None",
",",
"consistency",
"=",
"None",
")",
":",
"session_id",
"=",
"extract_attr",
"(",
"session",
",",
"keys",
"=",
"[",
"\"ID\"",
"]",
")... | 38.358974 | 0.001304 |
def generate_context(force_overwrite=False, drop_secret_key=False):
"""
Generates context.json
"""
print('... generating context')
context_fp = '%s/context.json' % os.environ['PRODUCT_DIR']
context = {}
if os.path.isfile(context_fp):
print('... augment existing context.json')
... | [
"def",
"generate_context",
"(",
"force_overwrite",
"=",
"False",
",",
"drop_secret_key",
"=",
"False",
")",
":",
"print",
"(",
"'... generating context'",
")",
"context_fp",
"=",
"'%s/context.json'",
"%",
"os",
".",
"environ",
"[",
"'PRODUCT_DIR'",
"]",
"context",... | 33.972222 | 0.00159 |
def get_edge_annotation_layers(docgraph):
"""
WARNING: this is higly inefficient!
Fix this via Issue #36.
Returns
-------
all_layers : set or dict
the set of all annotation layers used for annotating edges in the given
graph
"""
all_layers = set()
for source_id, targ... | [
"def",
"get_edge_annotation_layers",
"(",
"docgraph",
")",
":",
"all_layers",
"=",
"set",
"(",
")",
"for",
"source_id",
",",
"target_id",
",",
"edge_attribs",
"in",
"docgraph",
".",
"edges_iter",
"(",
"data",
"=",
"True",
")",
":",
"for",
"layer",
"in",
"e... | 28.75 | 0.002105 |
def add_snippet_client(self, name, package):
"""Adds a snippet client to the management.
Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, th... | [
"def",
"add_snippet_client",
"(",
"self",
",",
"name",
",",
"package",
")",
":",
"# Should not load snippet with the same name more than once.",
"if",
"name",
"in",
"self",
".",
"_snippet_clients",
":",
"raise",
"Error",
"(",
"self",
",",
"'Name \"%s\" is already regist... | 44.965517 | 0.001502 |
def _extend_with_api(test_dict, api_def_dict):
""" extend test with api definition, test will merge and override api definition.
Args:
test_dict (dict): test block, this will override api_def_dict
api_def_dict (dict): api definition
Examples:
>>> api_def_dict = {
"n... | [
"def",
"_extend_with_api",
"(",
"test_dict",
",",
"api_def_dict",
")",
":",
"# override api name",
"test_dict",
".",
"setdefault",
"(",
"\"name\"",
",",
"api_def_dict",
".",
"pop",
"(",
"\"name\"",
",",
"\"api name undefined\"",
")",
")",
"# override variables",
"de... | 35.646341 | 0.001997 |
def walk(self, top, file_list={}):
"""Walks the walk. nah, seriously: reads the file and stores a hashkey
corresponding to its content."""
for root, dirs, files in os.walk(top, topdown=False):
if os.path.basename(root) in self.ignore_dirs:
# Do not dig in ignored dirs... | [
"def",
"walk",
"(",
"self",
",",
"top",
",",
"file_list",
"=",
"{",
"}",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"top",
",",
"topdown",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"basename",
... | 46.15 | 0.002123 |
def get_components_for_species( alignment, species ):
"""Return the component for each species in the list `species` or None"""
# If the number of components in the alignment is less that the requested number
# of species we can immediately fail
if len( alignment.components ) < len( species ): return No... | [
"def",
"get_components_for_species",
"(",
"alignment",
",",
"species",
")",
":",
"# If the number of components in the alignment is less that the requested number",
"# of species we can immediately fail",
"if",
"len",
"(",
"alignment",
".",
"components",
")",
"<",
"len",
"(",
... | 59.777778 | 0.043956 |
def get_item_es(self, **kwargs):
""" Get ES collection item taking into account generated queryset
of parent view.
This method allows working with nested resources properly. Thus an item
returned by this method will belong to its parent view's queryset, thus
filtering out object... | [
"def",
"get_item_es",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"item_id",
"=",
"self",
".",
"_get_context_key",
"(",
"*",
"*",
"kwargs",
")",
"objects_ids",
"=",
"self",
".",
"_parent_queryset_es",
"(",
")",
"if",
"objects_ids",
"is",
"not",
"None... | 41.041667 | 0.001984 |
def init( self, lang='en', css=None, metainfo=None, title=None, header=None,
footer=None, charset=None, encoding=None, doctype=None, bodyattrs=None, script=None, base=None ):
"""This method is used for complete documents with appropriate
doctype, encoding, title, etc information. For an HT... | [
"def",
"init",
"(",
"self",
",",
"lang",
"=",
"'en'",
",",
"css",
"=",
"None",
",",
"metainfo",
"=",
"None",
",",
"title",
"=",
"None",
",",
"header",
"=",
"None",
",",
"footer",
"=",
"None",
",",
"charset",
"=",
"None",
",",
"encoding",
"=",
"No... | 45.542169 | 0.012688 |
def emergency_cast(colx, value):
"""ugly: this is a huge hack. get serious about where this belongs in the architecture.
For now, most types rely on being fed in as SubbedLiteral.
"""
if colx.coltp.type.lower()=='boolean':
if isinstance(value,sqparse2.NameX): value = value.name
if isinstance(value,bool)... | [
"def",
"emergency_cast",
"(",
"colx",
",",
"value",
")",
":",
"if",
"colx",
".",
"coltp",
".",
"type",
".",
"lower",
"(",
")",
"==",
"'boolean'",
":",
"if",
"isinstance",
"(",
"value",
",",
"sqparse2",
".",
"NameX",
")",
":",
"value",
"=",
"value",
... | 42.5 | 0.025346 |
def autoload_static(model, resources, script_path):
''' Return JavaScript code and a script tag that can be used to embed
Bokeh Plots.
The data for the plot is stored directly in the returned JavaScript code.
Args:
model (Model or Document) :
resources (Resources) :
script_pa... | [
"def",
"autoload_static",
"(",
"model",
",",
"resources",
",",
"script_path",
")",
":",
"# TODO: maybe warn that it's not exactly useful, but technically possible",
"# if resources.mode == 'inline':",
"# raise ValueError(\"autoload_static() requires non-inline resources\")",
"if",
"i... | 28.454545 | 0.0105 |
def transform(self, data):
"""
:param data:
:type data: dict
:return:
:rtype:
"""
out=[]
keys = sorted(data.keys())
for k in keys:
out.append("%s=%s" % (k, data[k]))
return "\n".join(out) | [
"def",
"transform",
"(",
"self",
",",
"data",
")",
":",
"out",
"=",
"[",
"]",
"keys",
"=",
"sorted",
"(",
"data",
".",
"keys",
"(",
")",
")",
"for",
"k",
"in",
"keys",
":",
"out",
".",
"append",
"(",
"\"%s=%s\"",
"%",
"(",
"k",
",",
"data",
"... | 22.333333 | 0.010753 |
def scan(self, scan_filter=None,
attributes_to_get=None, request_limit=None, max_results=None,
count=False, exclusive_start_key=None, item_class=Item):
"""
Scan through this table, this is a very long
and expensive operation, and should be avoided if
at all poss... | [
"def",
"scan",
"(",
"self",
",",
"scan_filter",
"=",
"None",
",",
"attributes_to_get",
"=",
"None",
",",
"request_limit",
"=",
"None",
",",
"max_results",
"=",
"None",
",",
"count",
"=",
"False",
",",
"exclusive_start_key",
"=",
"None",
",",
"item_class",
... | 47.014493 | 0.001208 |
def infer_gaps_in_tree(df_seq, tree, id_col='id', sequence_col='sequence'):
"""Adds a character matrix to DendroPy tree and infers gaps using
Fitch's algorithm.
Infer gaps in sequences at ancestral nodes.
"""
taxa = tree.taxon_namespace
# Get alignment as fasta
alignment = df_seq.phylo.to_... | [
"def",
"infer_gaps_in_tree",
"(",
"df_seq",
",",
"tree",
",",
"id_col",
"=",
"'id'",
",",
"sequence_col",
"=",
"'sequence'",
")",
":",
"taxa",
"=",
"tree",
".",
"taxon_namespace",
"# Get alignment as fasta",
"alignment",
"=",
"df_seq",
".",
"phylo",
".",
"to_f... | 37.730769 | 0.001988 |
def _pv_params(cls, session, pvswf, pv, **request_params):
"""Returns any parameters needed for Akamai HD player verification.
Algorithm originally documented by KSV, source:
http://stream-recorder.com/forum/showpost.php?p=43761&postcount=13
"""
try:
data, hdntl = p... | [
"def",
"_pv_params",
"(",
"cls",
",",
"session",
",",
"pvswf",
",",
"pv",
",",
"*",
"*",
"request_params",
")",
":",
"try",
":",
"data",
",",
"hdntl",
"=",
"pv",
".",
"split",
"(",
"\";\"",
")",
"except",
"ValueError",
":",
"data",
"=",
"pv",
"hdnt... | 38.104167 | 0.001066 |
def append_translated(model, fields):
"If translated field is encountered, add also all its translation fields."
fields = set(fields)
from modeltranslation.translator import translator
opts = translator.get_options_for_model(model)
for key, translated in opts.fields.items():
if key in fields... | [
"def",
"append_translated",
"(",
"model",
",",
"fields",
")",
":",
"fields",
"=",
"set",
"(",
"fields",
")",
"from",
"modeltranslation",
".",
"translator",
"import",
"translator",
"opts",
"=",
"translator",
".",
"get_options_for_model",
"(",
"model",
")",
"for... | 43.666667 | 0.002494 |
def compress(self):
"""Main function of compression."""
for ast_token in self.ast_tokens:
if type(ast_token) in self.dispatcher: # pylint: disable=unidiomatic-typecheck
self.dispatcher[type(ast_token)](ast_token)
else:
self.dispatcher['default'](a... | [
"def",
"compress",
"(",
"self",
")",
":",
"for",
"ast_token",
"in",
"self",
".",
"ast_tokens",
":",
"if",
"type",
"(",
"ast_token",
")",
"in",
"self",
".",
"dispatcher",
":",
"# pylint: disable=unidiomatic-typecheck",
"self",
".",
"dispatcher",
"[",
"type",
... | 46.142857 | 0.009119 |
def minimize(self, element: Expression[z3.ExprRef]) -> None:
"""In solving this solver will try to minimize the passed expression.
:param element:
"""
self.raw.minimize(element.raw) | [
"def",
"minimize",
"(",
"self",
",",
"element",
":",
"Expression",
"[",
"z3",
".",
"ExprRef",
"]",
")",
"->",
"None",
":",
"self",
".",
"raw",
".",
"minimize",
"(",
"element",
".",
"raw",
")"
] | 34.833333 | 0.009346 |
def img2img_transformer2d_base():
"""Base params for img2img 2d attention."""
hparams = image_transformer2d_base()
# learning related flags
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
# This version seems to benefit from a higher learning rate.
hparams.learning_rate =... | [
"def",
"img2img_transformer2d_base",
"(",
")",
":",
"hparams",
"=",
"image_transformer2d_base",
"(",
")",
"# learning related flags",
"hparams",
".",
"layer_preprocess_sequence",
"=",
"\"n\"",
"hparams",
".",
"layer_postprocess_sequence",
"=",
"\"da\"",
"# This version seem... | 39.705882 | 0.024602 |
def patch_namespaced_job_status(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_job_status # noqa: E501
partially update status of the specified Job # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, pl... | [
"def",
"patch_namespaced_job_status",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")"... | 60.72 | 0.001297 |
def grouped_command(commands):
"""
Given a list of commands (which are assumed groupable), return
a new command which is a batch (multi) command.
For ``set`` commands the outcome will be::
set_multi({key: value}, **kwargs)
For ``get`` and ``delete`` commands, the outcome will be::
... | [
"def",
"grouped_command",
"(",
"commands",
")",
":",
"base",
"=",
"commands",
"[",
"0",
"]",
"name",
"=",
"base",
".",
"get_name",
"(",
")",
"multi_command",
"=",
"EventualCommand",
"(",
"'%s_multi'",
"%",
"name",
")",
"if",
"name",
"in",
"(",
"'get'",
... | 30.285714 | 0.001143 |
def extract_id(*object_types):
"""
Decorator for extracting id from passed parameters for specific types.
"""
def outer(func):
def inner(*args, **kwargs):
def id_of(x):
return x.id if type(x) in object_types else x
new_args = [id_of(arg) for arg in args]... | [
"def",
"extract_id",
"(",
"*",
"object_types",
")",
":",
"def",
"outer",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"id_of",
"(",
"x",
")",
":",
"return",
"x",
".",
"id",
"if",
"type",
"("... | 27 | 0.002105 |
def get_positions(self, copy=True):
'''
Get a dictionary of measurement positions.
'''
if copy:
return self._positions.copy()
else:
return self._positions | [
"def",
"get_positions",
"(",
"self",
",",
"copy",
"=",
"True",
")",
":",
"if",
"copy",
":",
"return",
"self",
".",
"_positions",
".",
"copy",
"(",
")",
"else",
":",
"return",
"self",
".",
"_positions"
] | 26.375 | 0.009174 |
def users_list(self, *args):
"""Display a list of connected users"""
if len(self._users) == 0:
self.log('No users connected')
else:
self.log(self._users, pretty=True) | [
"def",
"users_list",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"self",
".",
"_users",
")",
"==",
"0",
":",
"self",
".",
"log",
"(",
"'No users connected'",
")",
"else",
":",
"self",
".",
"log",
"(",
"self",
".",
"_users",
",",
"p... | 34.833333 | 0.009346 |
def load_hgnc_genes(adapter, genes = None, ensembl_lines=None, hgnc_lines=None, exac_lines=None, mim2gene_lines=None,
genemap_lines=None, hpo_lines=None, build='37', omim_api_key=''):
"""Load genes into the database
link_genes will collect information from all the different sources ... | [
"def",
"load_hgnc_genes",
"(",
"adapter",
",",
"genes",
"=",
"None",
",",
"ensembl_lines",
"=",
"None",
",",
"hgnc_lines",
"=",
"None",
",",
"exac_lines",
"=",
"None",
",",
"mim2gene_lines",
"=",
"None",
",",
"genemap_lines",
"=",
"None",
",",
"hpo_lines",
... | 41.771429 | 0.008019 |
def calc_qiga1_v1(self):
"""Perform the runoff concentration calculation for the first
interflow component.
The working equation is the analytical solution of the linear storage
equation under the assumption of constant change in inflow during
the simulation time step.
Required derived paramet... | [
"def",
"calc_qiga1_v1",
"(",
"self",
")",
":",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"old",
"=",
"self",
".",
"sequences",
".",
"states",
".",
"fastaccess_old",
"new",
"=",
"self",
".",
"sequences",
".",
"states",
".",... | 28 | 0.000556 |
def finalize(self):
# type: () -> None
"""
Finalizes the bundle, preparing it to be attached to the Tangle.
"""
if self.hash:
raise RuntimeError('Bundle is already finalized.')
if not self:
raise ValueError('Bundle has no transactions.')
... | [
"def",
"finalize",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"hash",
":",
"raise",
"RuntimeError",
"(",
"'Bundle is already finalized.'",
")",
"if",
"not",
"self",
":",
"raise",
"ValueError",
"(",
"'Bundle has no transactions.'",
")",
"# Quic... | 33.328571 | 0.001249 |
def add_scalar_summary(self, x, tag=None):
"""Adds a scalar summary for x."""
if not self.summary_collections:
return
with self.g.as_default():
tag = tag or _tag_for(x.name)
summary = (tf.summary.scalar(
tag, x, collections=self.summary_collections))
return summary | [
"def",
"add_scalar_summary",
"(",
"self",
",",
"x",
",",
"tag",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"summary_collections",
":",
"return",
"with",
"self",
".",
"g",
".",
"as_default",
"(",
")",
":",
"tag",
"=",
"tag",
"or",
"_tag_for",
"(... | 33.666667 | 0.016077 |
def spin_thread(self, interval=1):
"""call Client.spin() in a background thread on some regular interval
This helps ensure that messages don't pile up too much in the zmq queue
while you are working on other things, or just leaving an idle terminal.
It also helps limit ... | [
"def",
"spin_thread",
"(",
"self",
",",
"interval",
"=",
"1",
")",
":",
"if",
"self",
".",
"_spin_thread",
"is",
"not",
"None",
":",
"self",
".",
"stop_spin_thread",
"(",
")",
"self",
".",
"_stop_spinning",
".",
"clear",
"(",
")",
"self",
".",
"_spin_t... | 36.9 | 0.008803 |
def select_paths(cls, dataset, selection):
"""
Allows selecting paths with usual NumPy slicing index.
"""
return [s[0] for s in np.array([{0: p} for p in dataset.data])[selection]] | [
"def",
"select_paths",
"(",
"cls",
",",
"dataset",
",",
"selection",
")",
":",
"return",
"[",
"s",
"[",
"0",
"]",
"for",
"s",
"in",
"np",
".",
"array",
"(",
"[",
"{",
"0",
":",
"p",
"}",
"for",
"p",
"in",
"dataset",
".",
"data",
"]",
")",
"["... | 41.6 | 0.014151 |
def _infer_map(node, context):
"""Infer all values based on Dict.items"""
values = {}
for name, value in node.items:
if isinstance(name, nodes.DictUnpack):
double_starred = helpers.safe_infer(value, context)
if not double_starred:
raise exceptions.InferenceErr... | [
"def",
"_infer_map",
"(",
"node",
",",
"context",
")",
":",
"values",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"node",
".",
"items",
":",
"if",
"isinstance",
"(",
"name",
",",
"nodes",
".",
"DictUnpack",
")",
":",
"double_starred",
"=",
"hel... | 48.631579 | 0.001062 |
def Popen_nonblocking(*args, **kwargs):
"""
Open a subprocess without blocking. Return a process handle with any
output streams replaced by queues of lines from that stream.
Usage::
proc = Popen_nonblocking(..., stdout=subprocess.PIPE)
try:
out_line = proc.stdout.get_nowait()
except queue.Empty:
"no o... | [
"def",
"Popen_nonblocking",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'close_fds'",
",",
"'posix'",
"in",
"sys",
".",
"builtin_module_names",
")",
"kwargs",
".",
"setdefault",
"(",
"'bufsize'",
",",
"1",
")",
... | 23.611111 | 0.038418 |
def setup_logging():
""" Setup logging configuration """
# Console formatter, mention name
cfmt = logging.Formatter(('%(name)s - %(levelname)s - %(message)s'))
# File formatter, mention time
ffmt = logging.Formatter(('%(asctime)s - %(levelname)s - %(message)s'))
# Console handler
ch = log... | [
"def",
"setup_logging",
"(",
")",
":",
"# Console formatter, mention name",
"cfmt",
"=",
"logging",
".",
"Formatter",
"(",
"(",
"'%(name)s - %(levelname)s - %(message)s'",
")",
")",
"# File formatter, mention time",
"ffmt",
"=",
"logging",
".",
"Formatter",
"(",
"(",
... | 28.714286 | 0.001925 |
def get_es_action_item(data_item, action_settings, es_type, id_field=None):
''' This method will return an item formated and ready to append
to the action list '''
action_item = dict.copy(action_settings)
if id_field is not None:
id_val = first(list(get_dict_key(data_item, id_field)))
... | [
"def",
"get_es_action_item",
"(",
"data_item",
",",
"action_settings",
",",
"es_type",
",",
"id_field",
"=",
"None",
")",
":",
"action_item",
"=",
"dict",
".",
"copy",
"(",
"action_settings",
")",
"if",
"id_field",
"is",
"not",
"None",
":",
"id_val",
"=",
... | 39.95 | 0.001222 |
def _get_or_update_or_create_related_instance(
self, ModelClass, fieldname, field_data
):
"""
Handle lookup, update, or creation of related instances based on the
field data provided and the field's `writable_related_fields` settings
as defined on the serializer's `Meta`.... | [
"def",
"_get_or_update_or_create_related_instance",
"(",
"self",
",",
"ModelClass",
",",
"fieldname",
",",
"field_data",
")",
":",
"writable_related_fields",
"=",
"getattr",
"(",
"self",
".",
"Meta",
",",
"'writable_related_fields'",
",",
"{",
"}",
")",
"# Get setti... | 45.234848 | 0.000492 |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = Chronometer(self.get_context(), None, d.style) | [
"def",
"create_widget",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"self",
".",
"widget",
"=",
"Chronometer",
"(",
"self",
".",
"get_context",
"(",
")",
",",
"None",
",",
"d",
".",
"style",
")"
] | 28.666667 | 0.011299 |
def sel(selN,selK,selarr=[]):
"""
Automatically create QUBO which select K qubits from N qubits
.. code-block:: python
print(wq.sel(5,2))
#=>
[[-3 2 2 2 2]
[ 0 -3 2 2 2]
[ 0 0 -3 2 2]
[ 0 0 0 -3 2]
[ 0 0 0 0 -3]]
if you set array on the 3rd params, the result likely to choose the nt... | [
"def",
"sel",
"(",
"selN",
",",
"selK",
",",
"selarr",
"=",
"[",
"]",
")",
":",
"selres",
"=",
"np",
".",
"diag",
"(",
"[",
"1",
"-",
"2",
"*",
"selK",
"]",
"*",
"selN",
")",
"+",
"np",
".",
"triu",
"(",
"[",
"[",
"2",
"]",
"*",
"selN",
... | 26.785714 | 0.043758 |
def genestats(args):
"""
%prog genestats gffile
Print summary stats, including:
- Number of genes
- Number of single-exon genes
- Number of multi-exon genes
- Number of distinct exons
- Number of genes with alternative transcript variants
- Number of predicted transcripts
- Mean... | [
"def",
"genestats",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"genestats",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--groupby\"",
",",
"default",
"=",
"\"conf_class\"",
",",
"help",
"=",
"\"Print separate stats groupby\"",
")",
"p",
"... | 39.752294 | 0.001576 |
def psyplot_fname(env_key='PSYPLOTRC', fname='psyplotrc.yml',
if_exists=True):
"""
Get the location of the config file.
The file location is determined in the following order
- `$PWD/psyplotrc.yml`
- environment variable `PSYPLOTRC` (pointing to the file location or a
dire... | [
"def",
"psyplot_fname",
"(",
"env_key",
"=",
"'PSYPLOTRC'",
",",
"fname",
"=",
"'psyplotrc.yml'",
",",
"if_exists",
"=",
"True",
")",
":",
"cwd",
"=",
"getcwd",
"(",
")",
"full_fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"fname",
")",... | 26.880597 | 0.000536 |
def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs):
""" Deprecated see make_data_classif """
return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs) | [
"def",
"get_data_classif",
"(",
"dataset",
",",
"n",
",",
"nz",
"=",
".5",
",",
"theta",
"=",
"0",
",",
"random_state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"make_data_classif",
"(",
"dataset",
",",
"n",
",",
"nz",
"=",
".5",
"... | 70 | 0.009434 |
def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None,
sort='asc', target_string=None,
legend=None, bar_labels=True, title=None):
"""Plot a histogram of data.
Args:
data (list or dict): This is either a list of dictionaries or a single
... | [
"def",
"plot_histogram",
"(",
"data",
",",
"figsize",
"=",
"(",
"7",
",",
"5",
")",
",",
"color",
"=",
"None",
",",
"number_to_keep",
"=",
"None",
",",
"sort",
"=",
"'asc'",
",",
"target_string",
"=",
"None",
",",
"legend",
"=",
"None",
",",
"bar_lab... | 40.15 | 0.000868 |
def encode(self, word, max_length=-1):
"""Return the PhoneticSpanish coding of word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to unlimited)
Returns
-------
s... | [
"def",
"encode",
"(",
"self",
",",
"word",
",",
"max_length",
"=",
"-",
"1",
")",
":",
"# uppercase, normalize, and decompose, filter to A-Z minus vowels & W",
"word",
"=",
"unicode_normalize",
"(",
"'NFKD'",
",",
"text_type",
"(",
"word",
".",
"upper",
"(",
")",
... | 25.422222 | 0.001684 |
def run(self):
""" Runs the given OPF task against the given Model instance """
self._logger.debug("Starting Dummy Model: modelID=%s;" % (self._modelID))
# =========================================================================
# Initialize periodic activities (e.g., for model result updates)
# ... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Starting Dummy Model: modelID=%s;\"",
"%",
"(",
"self",
".",
"_modelID",
")",
")",
"# =========================================================================",
"# Initialize periodic activi... | 37 | 0.012694 |
def update_max_progress(self):
"""
Compute progress of tree and max progress of sub-trees (not recursive).
"""
self.update_progress()
if self.leafnode:
self.max_leaf_progress = self.progress
else:
self.max_leaf_progress = max(self.lower.ma... | [
"def",
"update_max_progress",
"(",
"self",
")",
":",
"self",
".",
"update_progress",
"(",
")",
"if",
"self",
".",
"leafnode",
":",
"self",
".",
"max_leaf_progress",
"=",
"self",
".",
"progress",
"else",
":",
"self",
".",
"max_leaf_progress",
"=",
"max",
"(... | 35.9 | 0.01087 |
def init(self, fle=None):
"""
Executes the preprocessing steps at the instantiation stage to read in
the tables from hdf5 and hold them in memory.
"""
if fle is None:
fname = self.kwargs.get('gmpe_table', self.GMPE_TABLE)
if fname is None:
... | [
"def",
"init",
"(",
"self",
",",
"fle",
"=",
"None",
")",
":",
"if",
"fle",
"is",
"None",
":",
"fname",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"'gmpe_table'",
",",
"self",
".",
"GMPE_TABLE",
")",
"if",
"fname",
"is",
"None",
":",
"raise",
"... | 44.810811 | 0.001181 |
def get_device_by_id(self, device_id):
"""Search the list of connected devices by ID.
device_id param is the integer ID of the device
"""
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if... | [
"def",
"get_device_by_id",
"(",
"self",
",",
"device_id",
")",
":",
"# Find the device for the vera device name we are interested in",
"found_device",
"=",
"None",
"for",
"device",
"in",
"self",
".",
"get_devices",
"(",
")",
":",
"if",
"device",
".",
"device_id",
"=... | 33.444444 | 0.008078 |
def fields(self):
'''A dictionary of fields constructed by this pump'''
out = dict()
for operator in self.ops:
out.update(**operator.fields)
return out | [
"def",
"fields",
"(",
"self",
")",
":",
"out",
"=",
"dict",
"(",
")",
"for",
"operator",
"in",
"self",
".",
"ops",
":",
"out",
".",
"update",
"(",
"*",
"*",
"operator",
".",
"fields",
")",
"return",
"out"
] | 27.142857 | 0.010204 |
def bleu_wrapper(ref_filename, hyp_filename, case_sensitive=False):
"""Compute BLEU for two files (reference and hypothesis translation)."""
ref_lines = text_encoder.native_to_unicode(
tf.gfile.Open(ref_filename, "r").read()).split("\n")
hyp_lines = text_encoder.native_to_unicode(
tf.gfile.Open(hyp_fi... | [
"def",
"bleu_wrapper",
"(",
"ref_filename",
",",
"hyp_filename",
",",
"case_sensitive",
"=",
"False",
")",
":",
"ref_lines",
"=",
"text_encoder",
".",
"native_to_unicode",
"(",
"tf",
".",
"gfile",
".",
"Open",
"(",
"ref_filename",
",",
"\"r\"",
")",
".",
"re... | 50.857143 | 0.012414 |
def make_data():
"""creates example data set"""
n = 30 # number of stages
z = 1.65 # for 95% service level
sigma = 100 # demand's standard deviation
h = {} # inventory cost
T = {} # production lead time
h[n] = 1
for i in range(n-1,0,-1):
h[i] = h[i+1] + random.r... | [
"def",
"make_data",
"(",
")",
":",
"n",
"=",
"30",
"# number of stages",
"z",
"=",
"1.65",
"# for 95% service level",
"sigma",
"=",
"100",
"# demand's standard deviation",
"h",
"=",
"{",
"}",
"# inventory cost",
"T",
"=",
"{",
"}",
"# production lead time",
"h",... | 34.866667 | 0.024209 |
def _build_autoload_details(self, autoload_data, relative_path=""):
""" Build autoload details
:param autoload_data: dict:
:param relative_path: str: full relative path of current autoload resource
"""
self._autoload_details.attributes.extend([AutoLoadAttribute(relative_address... | [
"def",
"_build_autoload_details",
"(",
"self",
",",
"autoload_data",
",",
"relative_path",
"=",
"\"\"",
")",
":",
"self",
".",
"_autoload_details",
".",
"attributes",
".",
"extend",
"(",
"[",
"AutoLoadAttribute",
"(",
"relative_address",
"=",
"relative_path",
",",... | 67.857143 | 0.010381 |
def BIC(self,data=None):
'''
BIC on the passed data.
If passed data is None (default), calculates BIC on the model's assigned data.
'''
# NOTE: in principle this method computes the BIC only after finding the
# maximum likelihood parameters (or, of course, an EM fixed-poi... | [
"def",
"BIC",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"# NOTE: in principle this method computes the BIC only after finding the",
"# maximum likelihood parameters (or, of course, an EM fixed-point as an",
"# approximation!)",
"if",
"data",
"is",
"None",
":",
"assert",
... | 54.066667 | 0.014545 |
def copy(self):
""" Prepare and paste self templates. """
templates = self.prepare_templates()
if self.params.interactive:
keys = list(self.parser.default)
for key in keys:
if key.startswith('_'):
continue
prompt = "{0} ... | [
"def",
"copy",
"(",
"self",
")",
":",
"templates",
"=",
"self",
".",
"prepare_templates",
"(",
")",
"if",
"self",
".",
"params",
".",
"interactive",
":",
"keys",
"=",
"list",
"(",
"self",
".",
"parser",
".",
"default",
")",
"for",
"key",
"in",
"keys"... | 36.875 | 0.001652 |
def set_problem_result(result, problem_id):
""" Set problem specific result value """
rdict = load_feedback()
if not 'problems' in rdict:
rdict['problems'] = {}
cur_val = rdict['problems'].get(problem_id, '')
rdict['problems'][problem_id] = [result, cur_val] if type(cur_val) == str else [res... | [
"def",
"set_problem_result",
"(",
"result",
",",
"problem_id",
")",
":",
"rdict",
"=",
"load_feedback",
"(",
")",
"if",
"not",
"'problems'",
"in",
"rdict",
":",
"rdict",
"[",
"'problems'",
"]",
"=",
"{",
"}",
"cur_val",
"=",
"rdict",
"[",
"'problems'",
"... | 44.25 | 0.00831 |
def variant_dir_target_climb(self, orig, dir, tail):
"""Create targets in corresponding variant directories
Climb the directory tree, and look up path names
relative to any linked variant directories we find.
Even though this loops and walks up the tree, we don't memoize
the re... | [
"def",
"variant_dir_target_climb",
"(",
"self",
",",
"orig",
",",
"dir",
",",
"tail",
")",
":",
"targets",
"=",
"[",
"]",
"message",
"=",
"None",
"fmt",
"=",
"\"building associated VariantDir targets: %s\"",
"start_dir",
"=",
"dir",
"while",
"dir",
":",
"for",... | 39.115385 | 0.001919 |
def solve(
solver, mzn, *dzn_files, data=None, include=None, stdlib_dir=None,
globals_dir=None, allow_multiple_assignments=False, output_mode='item',
timeout=None, two_pass=None, pre_passes=None, output_objective=False,
non_unique=False, all_solutions=False, num_solutions=None,
free_search=False, pa... | [
"def",
"solve",
"(",
"solver",
",",
"mzn",
",",
"*",
"dzn_files",
",",
"data",
"=",
"None",
",",
"include",
"=",
"None",
",",
"stdlib_dir",
"=",
"None",
",",
"globals_dir",
"=",
"None",
",",
"allow_multiple_assignments",
"=",
"False",
",",
"output_mode",
... | 41.456311 | 0.000229 |
def get_parser():
"""Return the parser object for this script."""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-n",
d... | [
"def",
"get_parser",
"(",
")",
":",
"from",
"argparse",
"import",
"ArgumentParser",
",",
"ArgumentDefaultsHelpFormatter",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
... | 47.611111 | 0.001144 |
def configure_audit_decorator(graph):
"""
Configure the audit decorator.
Example Usage:
@graph.audit
def login(username, password):
...
"""
include_request_body = int(graph.config.audit.include_request_body)
include_response_body = int(graph.config.audit.include_res... | [
"def",
"configure_audit_decorator",
"(",
"graph",
")",
":",
"include_request_body",
"=",
"int",
"(",
"graph",
".",
"config",
".",
"audit",
".",
"include_request_body",
")",
"include_response_body",
"=",
"int",
"(",
"graph",
".",
"config",
".",
"audit",
".",
"i... | 34.407407 | 0.002094 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.