text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get(vm, key='uuid'):
'''
Output the JSON object describing a VM
vm : string
vm to be targeted
key : string [uuid|alias|hostname]
value type of 'vm' parameter
CLI Example:
.. code-block:: bash
salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543
salt '*'... | [
"def",
"get",
"(",
"vm",
",",
"key",
"=",
"'uuid'",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"key",
"not",
"in",
"[",
"'uuid'",
",",
"'alias'",
",",
"'hostname'",
"]",
":",
"ret",
"[",
"'Error'",
"]",
"=",
"'Key must be either uuid, alias or hostname'",
"... | 27.870968 | 20 |
def parse_label(module = None, function = None, offset = None):
"""
Creates a label from a module and a function name, plus an offset.
@warning: This method only creates the label, it doesn't make sure the
label actually points to a valid memory location.
@type module: Non... | [
"def",
"parse_label",
"(",
"module",
"=",
"None",
",",
"function",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"# TODO",
"# Invalid characters should be escaped or filtered.",
"# Convert ordinals to strings.",
"try",
":",
"function",
"=",
"\"#0x%x\"",
"%",
"f... | 31.985507 | 21.550725 |
def create_knowledge_base(self,
parent,
knowledge_base,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
... | [
"def",
"create_knowledge_base",
"(",
"self",
",",
"parent",
",",
"knowledge_base",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
... | 47.609375 | 24.828125 |
def uint(self, length, name, value=None, align=None):
"""Add an unsigned integer to template.
`length` is given in bytes and `value` is optional. `align` can be used
to align the field to longer byte length.
Examples:
| uint | 2 | foo |
| uint | 2 | foo | 42 |
|... | [
"def",
"uint",
"(",
"self",
",",
"length",
",",
"name",
",",
"value",
"=",
"None",
",",
"align",
"=",
"None",
")",
":",
"self",
".",
"_add_field",
"(",
"UInt",
"(",
"length",
",",
"name",
",",
"value",
",",
"align",
"=",
"align",
")",
")"
] | 35.416667 | 18.25 |
def search_with_retry(self, sleeptime=3.0, retrycount=3, **params):
"""
This function performs a search given a dictionary of search(..)
parameters. It accounts for server timeouts as necessary and
will retry some number of times.
@param sleeptime: number of seconds to sleep bet... | [
"def",
"search_with_retry",
"(",
"self",
",",
"sleeptime",
"=",
"3.0",
",",
"retrycount",
"=",
"3",
",",
"*",
"*",
"params",
")",
":",
"results",
"=",
"[",
"]",
"count",
"=",
"0",
"while",
"count",
"<",
"retrycount",
":",
"try",
":",
"results",
"=",
... | 33.548387 | 19.419355 |
def add_edge(self, u, v):
"""
O(log(n))
"""
# print('add_edge u, v = %r, %r' % (u, v,))
if self.graph.has_edge(u, v):
return
for node in (u, v):
if not self.graph.has_node(node):
self.graph.add_node(node)
for Fi in self.... | [
"def",
"add_edge",
"(",
"self",
",",
"u",
",",
"v",
")",
":",
"# print('add_edge u, v = %r, %r' % (u, v,))",
"if",
"self",
".",
"graph",
".",
"has_edge",
"(",
"u",
",",
"v",
")",
":",
"return",
"for",
"node",
"in",
"(",
"u",
",",
"v",
")",
":",
"if",... | 36 | 9.636364 |
def get_ext(self, obj=None):
"""Return the file extension
:param obj: the fileinfo with information. If None, this will use the stored object of JB_File
:type obj: :class:`FileInfo`
:returns: the file extension
:rtype: str
:raises: None
"""
if obj is None... | [
"def",
"get_ext",
"(",
"self",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"obj",
"=",
"self",
".",
"_obj",
"return",
"self",
".",
"_extel",
".",
"get_ext",
"(",
"obj",
")"
] | 31.5 | 16.083333 |
def interpolate_to_netcdf(self, in_lon, in_lat, out_path, date_unit="seconds since 1970-01-01T00:00",
interp_type="spline"):
"""
Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create
separate directories for each variab... | [
"def",
"interpolate_to_netcdf",
"(",
"self",
",",
"in_lon",
",",
"in_lat",
",",
"out_path",
",",
"date_unit",
"=",
"\"seconds since 1970-01-01T00:00\"",
",",
"interp_type",
"=",
"\"spline\"",
")",
":",
"if",
"interp_type",
"==",
"\"spline\"",
":",
"out_data",
"=",... | 51.510204 | 21.714286 |
def get_port_profile_status_input_port_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_status = ET.Element("get_port_profile_status")
config = get_port_profile_status
input = ET.SubElement(get_port_profile_status, "i... | [
"def",
"get_port_profile_status_input_port_profile_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_port_profile_status",
"=",
"ET",
".",
"Element",
"(",
"\"get_port_profile_status\"",
")",
"c... | 45.083333 | 17 |
def Uninitialize(
self,
Channel):
"""
Uninitializes one or all PCAN Channels initialized by CAN_Initialize
Remarks:
Giving the TPCANHandle value "PCAN_NONEBUS", uninitialize all initialized channels
Parameters:
Channel : A TPCANHandle representin... | [
"def",
"Uninitialize",
"(",
"self",
",",
"Channel",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"__m_dllBasic",
".",
"CAN_Uninitialize",
"(",
"Channel",
")",
"return",
"TPCANStatus",
"(",
"res",
")",
"except",
":",
"logger",
".",
"error",
"(",
"\"Exce... | 26.772727 | 24.772727 |
def pmag_angle(D1,D2): # use this
"""
finds the angle between lists of two directions D1,D2
"""
D1 = numpy.array(D1)
if len(D1.shape) > 1:
D1 = D1[:,0:2] # strip off intensity
else: D1 = D1[:2]
D2 = numpy.array(D2)
if len(D2.shape) > 1:
D2 = D2[:,0:2] # strip o... | [
"def",
"pmag_angle",
"(",
"D1",
",",
"D2",
")",
":",
"# use this ",
"D1",
"=",
"numpy",
".",
"array",
"(",
"D1",
")",
"if",
"len",
"(",
"D1",
".",
"shape",
")",
">",
"1",
":",
"D1",
"=",
"D1",
"[",
":",
",",
"0",
":",
"2",
"]",
"# strip off i... | 34.1 | 13 |
def filter_genes(
data: AnnData,
min_counts: Optional[int] = None,
min_cells: Optional[int] = None,
max_counts: Optional[int] = None,
max_cells: Optional[int] = None,
inplace: bool = True,
copy: bool = False,
) -> Union[AnnData, None, Tuple[np.ndarray, np.ndarray]]:
"""Filter genes bas... | [
"def",
"filter_genes",
"(",
"data",
":",
"AnnData",
",",
"min_counts",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"min_cells",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"max_counts",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
"... | 40.063158 | 19.705263 |
def _handle_status(self, key, value):
"""Parse a status code from the attached GnuPG process.
:raises ValueError: if the status message is unknown.
"""
informational_keys = ["KEY_CONSIDERED"]
if key in ("EXPORTED"):
self.fingerprints.append(value)
elif key ==... | [
"def",
"_handle_status",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"informational_keys",
"=",
"[",
"\"KEY_CONSIDERED\"",
"]",
"if",
"key",
"in",
"(",
"\"EXPORTED\"",
")",
":",
"self",
".",
"fingerprints",
".",
"append",
"(",
"value",
")",
"elif",
... | 40.5 | 9.642857 |
def _read_gaf_nts(self, fin_gaf, hdr_only, allow_missing_symbol):
"""Read GAF file. Store annotation data in a list of namedtuples."""
nts = []
ver = None
hdrobj = GafHdr()
datobj = None
# pylint: disable=not-callable
ntobj_make = None
get_gafvals = None
... | [
"def",
"_read_gaf_nts",
"(",
"self",
",",
"fin_gaf",
",",
"hdr_only",
",",
"allow_missing_symbol",
")",
":",
"nts",
"=",
"[",
"]",
"ver",
"=",
"None",
"hdrobj",
"=",
"GafHdr",
"(",
")",
"datobj",
"=",
"None",
"# pylint: disable=not-callable",
"ntobj_make",
"... | 42.044444 | 15.288889 |
def rollback(using=None):
"""
This function does the rollback itself and resets the dirty flag.
"""
if using is None:
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
connection.rollback()
return
connection = tldap.backend.... | [
"def",
"rollback",
"(",
"using",
"=",
"None",
")",
":",
"if",
"using",
"is",
"None",
":",
"for",
"using",
"in",
"tldap",
".",
"backend",
".",
"connections",
":",
"connection",
"=",
"tldap",
".",
"backend",
".",
"connections",
"[",
"using",
"]",
"connec... | 32.181818 | 13.090909 |
def get_unique_groups(input_list):
"""Function to get a unique list of groups."""
out_list = []
for item in input_list:
if item not in out_list:
out_list.append(item)
return out_list | [
"def",
"get_unique_groups",
"(",
"input_list",
")",
":",
"out_list",
"=",
"[",
"]",
"for",
"item",
"in",
"input_list",
":",
"if",
"item",
"not",
"in",
"out_list",
":",
"out_list",
".",
"append",
"(",
"item",
")",
"return",
"out_list"
] | 30.285714 | 11.142857 |
def rbac_policy_list(request, **kwargs):
"""List of RBAC Policies."""
policies = neutronclient(request).list_rbac_policies(
**kwargs).get('rbac_policies')
return [RBACPolicy(p) for p in policies] | [
"def",
"rbac_policy_list",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"policies",
"=",
"neutronclient",
"(",
"request",
")",
".",
"list_rbac_policies",
"(",
"*",
"*",
"kwargs",
")",
".",
"get",
"(",
"'rbac_policies'",
")",
"return",
"[",
"RBACPolic... | 42.2 | 4.6 |
def _queue_models(self, models, context):
"""
Work an an appropriate ordering for the models.
This isn't essential, but makes the script look nicer because
more instances can be defined on their first try.
"""
model_queue = []
number_remaining_models = len(models)... | [
"def",
"_queue_models",
"(",
"self",
",",
"models",
",",
"context",
")",
":",
"model_queue",
"=",
"[",
"]",
"number_remaining_models",
"=",
"len",
"(",
"models",
")",
"# Max number of cycles allowed before we call it an infinite loop.",
"MAX_CYCLES",
"=",
"number_remain... | 45.318182 | 22.727273 |
def aStockQoutation(self,code):
'''
订阅一只股票的实时行情数据,接收推送
:param code: 股票代码
:return:
'''
#设置监听-->订阅-->调用接口
# 分时
self.quote_ctx.set_handler(RTDataTest())
self.quote_ctx.subscribe(code, SubType.RT_DATA)
ret_code_rt_data, ret_data_rt_data = sel... | [
"def",
"aStockQoutation",
"(",
"self",
",",
"code",
")",
":",
"#设置监听-->订阅-->调用接口",
"# 分时",
"self",
".",
"quote_ctx",
".",
"set_handler",
"(",
"RTDataTest",
"(",
")",
")",
"self",
".",
"quote_ctx",
".",
"subscribe",
"(",
"code",
",",
"SubType",
".",
"RT_DAT... | 44.454545 | 25.636364 |
def InitFromGrrMessage(self, message):
"""Init from GrrMessage rdfvalue."""
if message.source:
self.client_id = message.source.Basename()
self.payload_type = compatibility.GetName(message.payload.__class__)
self.payload = message.payload
self.timestamp = message.age
return self | [
"def",
"InitFromGrrMessage",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"source",
":",
"self",
".",
"client_id",
"=",
"message",
".",
"source",
".",
"Basename",
"(",
")",
"self",
".",
"payload_type",
"=",
"compatibility",
".",
"GetName",
... | 30.1 | 17.9 |
def time_to_jump( self ):
"""
The timestep until the next jump.
Args:
None
Returns:
(Float): The timestep until the next jump.
"""
k_tot = rate_prefactor * np.sum( self.p )
return -( 1.0 / k_tot ) * math.log( random.random() ) | [
"def",
"time_to_jump",
"(",
"self",
")",
":",
"k_tot",
"=",
"rate_prefactor",
"*",
"np",
".",
"sum",
"(",
"self",
".",
"p",
")",
"return",
"-",
"(",
"1.0",
"/",
"k_tot",
")",
"*",
"math",
".",
"log",
"(",
"random",
".",
"random",
"(",
")",
")"
] | 24.833333 | 17.916667 |
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params={}):
"""Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
best_tree: best_tree suppport is currently not implemented
pa... | [
"def",
"build_tree_from_alignment",
"(",
"aln",
",",
"moltype",
"=",
"DNA",
",",
"best_tree",
"=",
"False",
",",
"params",
"=",
"{",
"}",
")",
":",
"if",
"best_tree",
":",
"raise",
"NotImplementedError",
"if",
"'-m'",
"not",
"in",
"params",
":",
"if",
"m... | 30.803571 | 20.321429 |
def _attempt_set_timeout(self, timeout):
"""Sets a timeout on the inner watchman client's socket."""
try:
self.client.setTimeout(timeout)
except Exception:
self._logger.debug('failed to set post-startup watchman timeout to %s', self._timeout)
else:
self._logger.debug('set post-startup ... | [
"def",
"_attempt_set_timeout",
"(",
"self",
",",
"timeout",
")",
":",
"try",
":",
"self",
".",
"client",
".",
"setTimeout",
"(",
"timeout",
")",
"except",
"Exception",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'failed to set post-startup watchman timeout ... | 44 | 22.375 |
def GetHist(tag_name, start_time, end_time, period=5, mode="raw",
desc_as_label=False, label=None, high_speed=False, utc=False):
"""
Retrieves data from eDNA history for a given tag.
:param tag_name: fully-qualified (site.service.tag) eDNA tag
:param start_time: must be in format mm/d... | [
"def",
"GetHist",
"(",
"tag_name",
",",
"start_time",
",",
"end_time",
",",
"period",
"=",
"5",
",",
"mode",
"=",
"\"raw\"",
",",
"desc_as_label",
"=",
"False",
",",
"label",
"=",
"None",
",",
"high_speed",
"=",
"False",
",",
"utc",
"=",
"False",
")",
... | 47.285714 | 23.214286 |
def get_plaintext_to_sign(self):
"""
Get back the plaintext that will be signed.
It is derived from the serialized zone file strings,
but encoded as a single string (omitting the signature field,
if already given)
"""
as_strings = self.pack_subdomain()
if ... | [
"def",
"get_plaintext_to_sign",
"(",
"self",
")",
":",
"as_strings",
"=",
"self",
".",
"pack_subdomain",
"(",
")",
"if",
"self",
".",
"sig",
"is",
"not",
"None",
":",
"# don't sign the signature",
"as_strings",
"=",
"as_strings",
"[",
":",
"-",
"1",
"]",
"... | 34.307692 | 10.769231 |
def _parse_command_line():
"""Configure and parse our command line flags."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--portserver_static_pool',
type=str,
default='15000-24999',
help='Comma separated N-P Range(s) of ports to manage (inclusive).')
parser.ad... | [
"def",
"_parse_command_line",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--portserver_static_pool'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'15000-24999'",
",",
"help",
"=",
"'Comma ... | 40.590909 | 11.272727 |
async def send(self, request):
"""
Sends and receives the result for the given request.
"""
body = bytes(request)
msg_id = self._state._get_new_msg_id()
await self._connection.send(
struct.pack('<qqi', 0, msg_id, len(body)) + body
)
body = awa... | [
"async",
"def",
"send",
"(",
"self",
",",
"request",
")",
":",
"body",
"=",
"bytes",
"(",
"request",
")",
"msg_id",
"=",
"self",
".",
"_state",
".",
"_get_new_msg_id",
"(",
")",
"await",
"self",
".",
"_connection",
".",
"send",
"(",
"struct",
".",
"p... | 40.935484 | 17.903226 |
def fromMarkdown(md, *args, **kwargs):
"""
Creates abstraction using path to file
:param str path: path to markdown file
:return: TreeOfContents object
"""
return TOC.fromHTML(markdown(md, *args, **kwargs)) | [
"def",
"fromMarkdown",
"(",
"md",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"TOC",
".",
"fromHTML",
"(",
"markdown",
"(",
"md",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | 31 | 9.25 |
def dfa_to_json(dfa: dict, name: str, path: str = './'):
""" Exports a DFA to a JSON file.
If *path* do not exists, it will be created.
:param dict dfa: DFA to export;
:param str name: name of the output file;
:param str path: path where to save the JSON file (default:
working... | [
"def",
"dfa_to_json",
"(",
"dfa",
":",
"dict",
",",
"name",
":",
"str",
",",
"path",
":",
"str",
"=",
"'./'",
")",
":",
"out",
"=",
"{",
"'alphabet'",
":",
"list",
"(",
"dfa",
"[",
"'alphabet'",
"]",
")",
",",
"'states'",
":",
"list",
"(",
"dfa",... | 31.555556 | 15.407407 |
def _router_numbers(self):
"""A tuple of the numbers of all "routing" basins."""
return tuple(up for up in self._up2down.keys()
if up in self._up2down.values()) | [
"def",
"_router_numbers",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"up",
"for",
"up",
"in",
"self",
".",
"_up2down",
".",
"keys",
"(",
")",
"if",
"up",
"in",
"self",
".",
"_up2down",
".",
"values",
"(",
")",
")"
] | 48.5 | 10.25 |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
This method contains a workaround for `Bugzilla #1202917`_.
Most entities are uniquely identified by an ID. ``System`` is a bit
different: it has both an ID and a UUID, and the UUID is used to
uniquely... | [
"def",
"path",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"==",
"'subscriptions'",
":",
"return",
"'{0}/{1}/{2}'",
".",
"format",
"(",
"super",
"(",
"System",
",",
"self",
")",
".",
"path",
"(",
"'base'",
")",
",",
"self",
".",
... | 35.114286 | 20.457143 |
def find_fixtures(fixtures_base_dir: str) -> Iterable[Tuple[str, str]]:
"""
Finds all of the (fixture_path, fixture_key) pairs for a given path under
the JSON test fixtures directory.
"""
all_fixture_paths = find_fixture_files(fixtures_base_dir)
for fixture_path in sorted(all_fixture_paths):
... | [
"def",
"find_fixtures",
"(",
"fixtures_base_dir",
":",
"str",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"all_fixture_paths",
"=",
"find_fixture_files",
"(",
"fixtures_base_dir",
")",
"for",
"fixture_path",
"in",
"sorted",
"(",... | 38.461538 | 16.307692 |
def feature_selection(df, labels, n_features, method='chi2'):
"""
Reduces the number of features in the imput dataframe.
Ex: labels = gs.meta['biospecimen_sample__sample_type_id'].apply(int).apply(lambda x: 0 if x < 10 else 1)
chi2_fs(gs.data, labels, 50)
:param df: The inpu... | [
"def",
"feature_selection",
"(",
"df",
",",
"labels",
",",
"n_features",
",",
"method",
"=",
"'chi2'",
")",
":",
"fs_obj",
"=",
"None",
"if",
"method",
"==",
"'chi2'",
":",
"fs_obj",
"=",
"chi2",
"elif",
"method",
"==",
"'ANOVA'",
":",
"fs_obj",
"=",
"... | 42.931034 | 21.551724 |
def _loadHandlers(self):
"""
creates a dictionary of named handler instances
:return: the dictionary
"""
return {handler.name: handler for handler in map(self.createHandler, self.config['handlers'])} | [
"def",
"_loadHandlers",
"(",
"self",
")",
":",
"return",
"{",
"handler",
".",
"name",
":",
"handler",
"for",
"handler",
"in",
"map",
"(",
"self",
".",
"createHandler",
",",
"self",
".",
"config",
"[",
"'handlers'",
"]",
")",
"}"
] | 39 | 17 |
def _get_file_version(self, infile):
"""Returns infile version string."""
# Determine file version
for line1 in infile:
if line1.strip() != "[Pyspread save file version]":
raise ValueError(_("File format unsupported."))
break
for line2 in infile:... | [
"def",
"_get_file_version",
"(",
"self",
",",
"infile",
")",
":",
"# Determine file version",
"for",
"line1",
"in",
"infile",
":",
"if",
"line1",
".",
"strip",
"(",
")",
"!=",
"\"[Pyspread save file version]\"",
":",
"raise",
"ValueError",
"(",
"_",
"(",
"\"Fi... | 31.181818 | 17.545455 |
def _node_is_match(qualified_name, package_names, fqn):
"""Determine if a qualfied name matches an fqn, given the set of package
names in the graph.
:param List[str] qualified_name: The components of the selector or node
name, split on '.'.
:param Set[str] package_names: The set of pacakge name... | [
"def",
"_node_is_match",
"(",
"qualified_name",
",",
"package_names",
",",
"fqn",
")",
":",
"if",
"len",
"(",
"qualified_name",
")",
"==",
"1",
"and",
"fqn",
"[",
"-",
"1",
"]",
"==",
"qualified_name",
"[",
"0",
"]",
":",
"return",
"True",
"if",
"quali... | 36.772727 | 21.272727 |
def get_job_statuses(github_token, api_url, build_id,
polling_interval, job_number):
"""Wait for all the travis jobs to complete.
Once the other jobs are complete, return a list of booleans,
indicating whether or not the job was successful. Ignore jobs
marked "allow_failure".
"... | [
"def",
"get_job_statuses",
"(",
"github_token",
",",
"api_url",
",",
"build_id",
",",
"polling_interval",
",",
"job_number",
")",
":",
"auth",
"=",
"get_json",
"(",
"'{api_url}/auth/github'",
".",
"format",
"(",
"api_url",
"=",
"api_url",
")",
",",
"data",
"="... | 44.034483 | 18.827586 |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._notification_delivery_method is not None:
return False
if self._notification_target is not None:
return False
if self._category is not None:
return False
return True | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_notification_delivery_method",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_notification_target",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_c... | 20.4 | 19.333333 |
def reset(self, **kwargs):
""" Reset the triplestore with all of the data
"""
self.drop_all(**kwargs)
file_locations = self.__file_locations__
self.__file_locations__ = []
self.load(file_locations, **kwargs) | [
"def",
"reset",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"drop_all",
"(",
"*",
"*",
"kwargs",
")",
"file_locations",
"=",
"self",
".",
"__file_locations__",
"self",
".",
"__file_locations__",
"=",
"[",
"]",
"self",
".",
"load",
"(",... | 35.571429 | 5.428571 |
def json_post(methodname, rtype, key):
"""decorator factory for json POST queries"""
return compose(
reusable,
map_return(registry(rtype), itemgetter(key)),
basic_interaction,
map_yield(partial(_json_as_post, methodname)),
oneyield,
) | [
"def",
"json_post",
"(",
"methodname",
",",
"rtype",
",",
"key",
")",
":",
"return",
"compose",
"(",
"reusable",
",",
"map_return",
"(",
"registry",
"(",
"rtype",
")",
",",
"itemgetter",
"(",
"key",
")",
")",
",",
"basic_interaction",
",",
"map_yield",
"... | 30.888889 | 16.111111 |
def _accept(self):
"""
Work loop runs forever (or until running is False)
:return:
"""
logger.warning("Reactor " + self._name + " is starting")
while self.running:
try:
self._completeTask()
except:
logger.exception("... | [
"def",
"_accept",
"(",
"self",
")",
":",
"logger",
".",
"warning",
"(",
"\"Reactor \"",
"+",
"self",
".",
"_name",
"+",
"\" is starting\"",
")",
"while",
"self",
".",
"running",
":",
"try",
":",
"self",
".",
"_completeTask",
"(",
")",
"except",
":",
"l... | 35.416667 | 18.25 |
def on_done(self):
"""
Reimplemented from :meth:`~AsyncViewBase.on_done`
"""
if self._d:
self._d.callback(self)
self._d = None | [
"def",
"on_done",
"(",
"self",
")",
":",
"if",
"self",
".",
"_d",
":",
"self",
".",
"_d",
".",
"callback",
"(",
"self",
")",
"self",
".",
"_d",
"=",
"None"
] | 25.142857 | 11.428571 |
def createSensorToClassifierLinks(network, sensorRegionName,
classifierRegionName):
"""Create required links from a sensor region to a classifier region."""
network.link(sensorRegionName, classifierRegionName, "UniformLink", "",
srcOutput="bucketIdxOut", destInput="b... | [
"def",
"createSensorToClassifierLinks",
"(",
"network",
",",
"sensorRegionName",
",",
"classifierRegionName",
")",
":",
"network",
".",
"link",
"(",
"sensorRegionName",
",",
"classifierRegionName",
",",
"\"UniformLink\"",
",",
"\"\"",
",",
"srcOutput",
"=",
"\"bucketI... | 66.666667 | 22.888889 |
def height(self) -> int:
"""Determines how many entry rows are in the diagram."""
max_y = -1.0
for _, y in self.entries.keys():
max_y = max(max_y, y)
for h in self.horizontal_lines:
max_y = max(max_y, h.y)
for v in self.vertical_lines:
max_y = ... | [
"def",
"height",
"(",
"self",
")",
"->",
"int",
":",
"max_y",
"=",
"-",
"1.0",
"for",
"_",
",",
"y",
"in",
"self",
".",
"entries",
".",
"keys",
"(",
")",
":",
"max_y",
"=",
"max",
"(",
"max_y",
",",
"y",
")",
"for",
"h",
"in",
"self",
".",
... | 36.3 | 6.5 |
def append(self, state, symbol, action, destinationstate, production = None):
"""Appends a new rule"""
if action not in (None, "Accept", "Shift", "Reduce"):
raise TypeError
rule = {"action":action, "dest":destinationstate}
if action == "Reduce":
if rule is None:
... | [
"def",
"append",
"(",
"self",
",",
"state",
",",
"symbol",
",",
"action",
",",
"destinationstate",
",",
"production",
"=",
"None",
")",
":",
"if",
"action",
"not",
"in",
"(",
"None",
",",
"\"Accept\"",
",",
"\"Shift\"",
",",
"\"Reduce\"",
")",
":",
"ra... | 58.571429 | 25.428571 |
def validateOneNamespace(self, ctxt, elem, prefix, ns, value):
"""Try to validate a single namespace declaration for an
element basically it does the following checks as described
by the XML-1.0 recommendation: - [ VC: Attribute Value Type
] - [ VC: Fixed Attribute Default ] - [ VC... | [
"def",
"validateOneNamespace",
"(",
"self",
",",
"ctxt",
",",
"elem",
",",
"prefix",
",",
"ns",
",",
"value",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"if",
"elem",
"is",
"No... | 52.5 | 17.375 |
def subject_key_identifier(self):
"""The :py:class:`~django_ca.extensions.SubjectKeyIdentifier` extension, or ``None`` if it doesn't
exist."""
try:
ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER)
except x509.ExtensionNotFound:
... | [
"def",
"subject_key_identifier",
"(",
"self",
")",
":",
"try",
":",
"ext",
"=",
"self",
".",
"x509",
".",
"extensions",
".",
"get_extension_for_oid",
"(",
"ExtensionOID",
".",
"SUBJECT_KEY_IDENTIFIER",
")",
"except",
"x509",
".",
"ExtensionNotFound",
":",
"retur... | 45.75 | 13.875 |
def parse_xml(self, key_xml):
'''
Parse a VocabularyKey from an Xml as per Healthvault
schema.
:param key_xml: lxml.etree.Element representing a single VocabularyKey
'''
xmlutils = XmlUtils(key_xml)
self.name = xmlutils.get_string_by_xpath('name')
... | [
"def",
"parse_xml",
"(",
"self",
",",
"key_xml",
")",
":",
"xmlutils",
"=",
"XmlUtils",
"(",
"key_xml",
")",
"self",
".",
"name",
"=",
"xmlutils",
".",
"get_string_by_xpath",
"(",
"'name'",
")",
"self",
".",
"family",
"=",
"xmlutils",
".",
"get_string_by_x... | 38.785714 | 23.642857 |
def delete(self, project_status, params={}, **options):
"""Deletes a specific, existing project status update.
Returns an empty data record.
Parameters
----------
project-status : {Id} The project status update to delete.
"""
path = "/project_statuses/%... | [
"def",
"delete",
"(",
"self",
",",
"project_status",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/project_statuses/%s\"",
"%",
"(",
"project_status",
")",
"return",
"self",
".",
"client",
".",
"delete",
"(",
"path",
... | 35.454545 | 17.727273 |
def call_functions_parallel(*worker_defs):
"""Call specified functions in parallel.
:param *worker_defs: Each positional argument can be either of
a function to be called or a tuple which consists of a function,
a list of positional arguments) and keyword arguments (optional).
If you ne... | [
"def",
"call_functions_parallel",
"(",
"*",
"worker_defs",
")",
":",
"# TODO(amotoki): Needs to figure out what max_workers can be specified.",
"# According to e0ne, the apache default configuration in devstack allows",
"# only 10 threads. What happens if max_worker=11 is specified?",
"max_work... | 50.272727 | 18.787879 |
def bounds_at_zoom(self, zoom=None):
"""
Return process bounds for zoom level.
Parameters
----------
zoom : integer or list
Returns
-------
process bounds : tuple
left, bottom, right, top
"""
return () if self.area_at_zoom(zoo... | [
"def",
"bounds_at_zoom",
"(",
"self",
",",
"zoom",
"=",
"None",
")",
":",
"return",
"(",
")",
"if",
"self",
".",
"area_at_zoom",
"(",
"zoom",
")",
".",
"is_empty",
"else",
"Bounds",
"(",
"*",
"self",
".",
"area_at_zoom",
"(",
"zoom",
")",
".",
"bound... | 25 | 15.8 |
def external_incompatibilities(self): # type: () -> Generator[Incompatibility]
"""
Returns all external incompatibilities in this incompatibility's
derivation graph.
"""
if isinstance(self._cause, ConflictCause):
cause = self._cause # type: ConflictCause
... | [
"def",
"external_incompatibilities",
"(",
"self",
")",
":",
"# type: () -> Generator[Incompatibility]",
"if",
"isinstance",
"(",
"self",
".",
"_cause",
",",
"ConflictCause",
")",
":",
"cause",
"=",
"self",
".",
"_cause",
"# type: ConflictCause",
"for",
"incompatibilit... | 40.142857 | 19.428571 |
def find_dependencies(self, dependent_rev, recurse=None):
"""Find all dependencies of the given revision, recursively traversing
the dependency tree if requested.
"""
if recurse is None:
recurse = self.options.recurse
try:
dependent = self.get_commit(depe... | [
"def",
"find_dependencies",
"(",
"self",
",",
"dependent_rev",
",",
"recurse",
"=",
"None",
")",
":",
"if",
"recurse",
"is",
"None",
":",
"recurse",
"=",
"self",
".",
"options",
".",
"recurse",
"try",
":",
"dependent",
"=",
"self",
".",
"get_commit",
"("... | 38.877551 | 17.836735 |
def checkSystemVersion(s, versions=None):
"""
Check if the current version is different from the previously recorded
version. If it is, or if there is no previously recorded version,
create a version matching the current config.
"""
if versions is None:
versions = getSystemVersions()
... | [
"def",
"checkSystemVersion",
"(",
"s",
",",
"versions",
"=",
"None",
")",
":",
"if",
"versions",
"is",
"None",
":",
"versions",
"=",
"getSystemVersions",
"(",
")",
"currentVersionMap",
"=",
"dict",
"(",
"[",
"(",
"v",
".",
"package",
",",
"v",
")",
"fo... | 45.681818 | 21.227273 |
def set_xlabel(self, s, delay_draw=False):
"set plot xlabel"
self.conf.relabel(xlabel=s, delay_draw=delay_draw) | [
"def",
"set_xlabel",
"(",
"self",
",",
"s",
",",
"delay_draw",
"=",
"False",
")",
":",
"self",
".",
"conf",
".",
"relabel",
"(",
"xlabel",
"=",
"s",
",",
"delay_draw",
"=",
"delay_draw",
")"
] | 41.666667 | 11.666667 |
def response(self, status, content_type, content, headers=None):
"""
Send an HTTP response
"""
assert not isinstance(content, (str, bytes)), 'response content cannot be of type str or bytes'
response_headers = [('Content-Type', content_type)]
if headers:
resp... | [
"def",
"response",
"(",
"self",
",",
"status",
",",
"content_type",
",",
"content",
",",
"headers",
"=",
"None",
")",
":",
"assert",
"not",
"isinstance",
"(",
"content",
",",
"(",
"str",
",",
"bytes",
")",
")",
",",
"'response content cannot be of type str o... | 37.727273 | 19.363636 |
def render_template_string(source, **context):
"""Renders a template from the given template source string
with the given context.
:param source: the sourcecode of the template to be
rendered
:param context: the variables that should be available in the
context of... | [
"def",
"render_template_string",
"(",
"source",
",",
"*",
"*",
"context",
")",
":",
"ctx",
"=",
"_app_ctx_stack",
".",
"top",
"ctx",
".",
"app",
".",
"update_template_context",
"(",
"context",
")",
"return",
"_render",
"(",
"ctx",
".",
"app",
".",
"jinja_e... | 38.384615 | 11.769231 |
def inject_request_ids_into_environment(func):
"""Decorator for the Lambda handler to inject request IDs for logging."""
@wraps(func)
def wrapper(event, context):
# This might not always be an API Gateway event, so only log the
# request ID, if it looks like to be coming from there.
... | [
"def",
"inject_request_ids_into_environment",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"event",
",",
"context",
")",
":",
"# This might not always be an API Gateway event, so only log the",
"# request ID, if it looks like to be coming from... | 40.785714 | 19.142857 |
def modify_meta(uid, data_dic, extinfo=None):
'''
update meta of the rec.
'''
if extinfo is None:
extinfo = {}
title = data_dic['title'].strip()
if len(title) < 2:
return False
cur_info = MPost.get_by_uid(uid)
if cur_info:
... | [
"def",
"modify_meta",
"(",
"uid",
",",
"data_dic",
",",
"extinfo",
"=",
"None",
")",
":",
"if",
"extinfo",
"is",
"None",
":",
"extinfo",
"=",
"{",
"}",
"title",
"=",
"data_dic",
"[",
"'title'",
"]",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"title"... | 38.75 | 12.519231 |
def email(self, comment, content_object, request):
"""
Overwritten for a better email notification.
"""
if not self.email_notification:
return
send_comment_posted(comment, request) | [
"def",
"email",
"(",
"self",
",",
"comment",
",",
"content_object",
",",
"request",
")",
":",
"if",
"not",
"self",
".",
"email_notification",
":",
"return",
"send_comment_posted",
"(",
"comment",
",",
"request",
")"
] | 28.25 | 11.25 |
def get_objective_query_session(self, proxy):
"""Gets the ``OsidSession`` associated with the objective query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveQuerySession``
:rtype: ``osid.learning.ObjectiveQuerySession``
:raise: ``... | [
"def",
"get_objective_query_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_objective_query",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError",
":",
"... | 39.884615 | 18.769231 |
def diff(new_dict, old_dict, iter_prefix='__iter__',
np_allclose=False, **kwargs):
""" return the difference between two dict_like objects
Parameters
----------
new_dict: dict
old_dict: dict
iter_prefix: str
prefix to use for list and tuple indexes
np_allclose: bool
... | [
"def",
"diff",
"(",
"new_dict",
",",
"old_dict",
",",
"iter_prefix",
"=",
"'__iter__'",
",",
"np_allclose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"np_allclose",
":",
"try",
":",
"import",
"numpy",
"except",
"ImportError",
":",
"raise",
"... | 28.791209 | 20 |
def declare_base(erroName=True):
"""Create a Exception with default message.
:param errorName: boolean, True if you want the Exception name in the
error message body.
"""
if erroName:
class Base(Exception):
def __str__(self):
if len(self.args):
... | [
"def",
"declare_base",
"(",
"erroName",
"=",
"True",
")",
":",
"if",
"erroName",
":",
"class",
"Base",
"(",
"Exception",
")",
":",
"def",
"__str__",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"args",
")",
":",
"return",
"\"%s: %s\"",
"%",
... | 33.571429 | 16.619048 |
def min_depth_img(self, num_img=1):
"""Collect a series of depth images and return the min of the set.
Parameters
----------
num_img : int
The number of consecutive frames to process.
Returns
-------
:obj:`DepthImage`
The min DepthImage c... | [
"def",
"min_depth_img",
"(",
"self",
",",
"num_img",
"=",
"1",
")",
":",
"depths",
"=",
"self",
".",
"_read_depth_images",
"(",
"num_img",
")",
"return",
"Image",
".",
"min_images",
"(",
"depths",
")"
] | 27.0625 | 18.5 |
def land_surface_temp(self):
"""
Mean values from Allen (2007)
:return:
"""
rp = 0.91
tau = 0.866
rsky = 1.32
epsilon = self.emissivity(approach='tasumi')
radiance = self.radiance(6)
rc = ((radiance - rp) / tau) - ((1 - epsilon) * rsky)
... | [
"def",
"land_surface_temp",
"(",
"self",
")",
":",
"rp",
"=",
"0.91",
"tau",
"=",
"0.866",
"rsky",
"=",
"1.32",
"epsilon",
"=",
"self",
".",
"emissivity",
"(",
"approach",
"=",
"'tasumi'",
")",
"radiance",
"=",
"self",
".",
"radiance",
"(",
"6",
")",
... | 29.538462 | 14 |
def TransferDemo(handler, t):
"""
Demonstration of transfering to another number
"""
t.say ("One moment please.")
t.transfer(MY_PHONE)
t.say("Hi. I am a robot")
json = t.RenderJson()
logging.info ("TransferDemo json: %s" % json)
handler.response.out.write(json) | [
"def",
"TransferDemo",
"(",
"handler",
",",
"t",
")",
":",
"t",
".",
"say",
"(",
"\"One moment please.\"",
")",
"t",
".",
"transfer",
"(",
"MY_PHONE",
")",
"t",
".",
"say",
"(",
"\"Hi. I am a robot\"",
")",
"json",
"=",
"t",
".",
"RenderJson",
"(",
")"... | 28.8 | 8.4 |
def _strip_metachars(val):
"""
When a filter uses a / or - in the search, only the elements
name and comment field is searched. This can cause issues if
searching a network element, i.e. 1.1.1.0/24 where the /24 portion
is not present in the name and only the elements ipv4_network
attribute. If ... | [
"def",
"_strip_metachars",
"(",
"val",
")",
":",
"ignore_metachar",
"=",
"r'(.+)([/-].+)'",
"match",
"=",
"re",
".",
"search",
"(",
"ignore_metachar",
",",
"str",
"(",
"val",
")",
")",
"if",
"match",
":",
"left_half",
"=",
"match",
".",
"group",
"(",
"1"... | 39.875 | 16.25 |
def bank_identifier(self):
"""Return the IBAN's Bank Identifier."""
end = get_iban_spec(self.country_code).bban_split_pos + 4
return self._id[4:end] | [
"def",
"bank_identifier",
"(",
"self",
")",
":",
"end",
"=",
"get_iban_spec",
"(",
"self",
".",
"country_code",
")",
".",
"bban_split_pos",
"+",
"4",
"return",
"self",
".",
"_id",
"[",
"4",
":",
"end",
"]"
] | 42.25 | 12.25 |
def passphrase_file(passphrase=None):
"""Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords."""
cmd = []
pass_file = None
if not passphrase and 'CRYPTORITO_PASS... | [
"def",
"passphrase_file",
"(",
"passphrase",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"]",
"pass_file",
"=",
"None",
"if",
"not",
"passphrase",
"and",
"'CRYPTORITO_PASSPHRASE_FILE'",
"in",
"os",
".",
"environ",
":",
"pass_file",
"=",
"os",
".",
"environ",
"... | 35.346154 | 17.038462 |
def _last_in_direction(starting_pos, direction):
"""
move in the tree in given direction and return the last position.
:param starting_pos: position to start at
:param direction: callable that transforms a position into a position.
"""
cur_pos = None
next_pos = s... | [
"def",
"_last_in_direction",
"(",
"starting_pos",
",",
"direction",
")",
":",
"cur_pos",
"=",
"None",
"next_pos",
"=",
"starting_pos",
"while",
"next_pos",
"is",
"not",
"None",
":",
"cur_pos",
"=",
"next_pos",
"next_pos",
"=",
"direction",
"(",
"cur_pos",
")",... | 34.692308 | 14.538462 |
def parse(self, argument):
"""Determine validity of argument and return the correct element of enum.
If self.enum_values is empty, then all arguments are valid and argument
will be returned.
Otherwise, if argument matches an element in enum, then the first
matching element will be returned.
A... | [
"def",
"parse",
"(",
"self",
",",
"argument",
")",
":",
"if",
"not",
"self",
".",
"enum_values",
":",
"return",
"argument",
"elif",
"self",
".",
"case_sensitive",
":",
"if",
"argument",
"not",
"in",
"self",
".",
"enum_values",
":",
"raise",
"ValueError",
... | 32.628571 | 21.885714 |
def current_state(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> FSMContext:
"""
Get current state for user in chat as context
.. code-block:: python3
with dp.current_state(chat=message.c... | [
"def",
"current_state",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
")"... | 31.923077 | 20.461538 |
def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True):
"""Set the stepdown window for this instance.
Date times are assumed to be UTC, so use UTC date times.
:param datetime.datetime start: The datetime which the stepdown window is to open.
:param datetim... | [
"def",
"set_stepdown_window",
"(",
"self",
",",
"start",
",",
"end",
",",
"enabled",
"=",
"True",
",",
"scheduled",
"=",
"True",
",",
"weekly",
"=",
"True",
")",
":",
"# Ensure a logical start and endtime is requested.",
"if",
"not",
"start",
"<",
"end",
":",
... | 43.171429 | 24.828571 |
def generate_key(self, email):
"""
Generate a new email confirmation key and return it.
"""
salt = sha1(str(random())).hexdigest()[:5]
return sha1(salt + email).hexdigest() | [
"def",
"generate_key",
"(",
"self",
",",
"email",
")",
":",
"salt",
"=",
"sha1",
"(",
"str",
"(",
"random",
"(",
")",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
":",
"5",
"]",
"return",
"sha1",
"(",
"salt",
"+",
"email",
")",
".",
"hexdigest",
... | 34.5 | 7.5 |
def unique(series: pd.Series) -> pd.Series:
"""Test that the data items do not repeat."""
return ~series.duplicated(keep=False) | [
"def",
"unique",
"(",
"series",
":",
"pd",
".",
"Series",
")",
"->",
"pd",
".",
"Series",
":",
"return",
"~",
"series",
".",
"duplicated",
"(",
"keep",
"=",
"False",
")"
] | 44.333333 | 1.333333 |
def _ParseContainerConfigJSON(self, parser_mediator, file_object):
"""Extracts events from a Docker container configuration file.
The path of each container config file is:
DOCKER_DIR/containers/<container_id>/config.json
Args:
parser_mediator (ParserMediator): mediates interactions between pars... | [
"def",
"_ParseContainerConfigJSON",
"(",
"self",
",",
"parser_mediator",
",",
"file_object",
")",
":",
"file_content",
"=",
"file_object",
".",
"read",
"(",
")",
"file_content",
"=",
"codecs",
".",
"decode",
"(",
"file_content",
",",
"self",
".",
"_ENCODING",
... | 40.961538 | 20.589744 |
def add_tgs(self, tgs_rep, enc_tgs_rep_part, override_pp = False): #from AS_REP
"""
Creates credential object from the TGS and adds to the ccache file
The TGS is the native representation of the asn1 encoded TGS_REP data when the user requests a tgs to a specific service principal with a valid TGT
This funct... | [
"def",
"add_tgs",
"(",
"self",
",",
"tgs_rep",
",",
"enc_tgs_rep_part",
",",
"override_pp",
"=",
"False",
")",
":",
"#from AS_REP",
"c",
"=",
"Credential",
"(",
")",
"c",
".",
"client",
"=",
"CCACHEPrincipal",
".",
"from_asn1",
"(",
"tgs_rep",
"[",
"'cname... | 48.84 | 32.44 |
def preprocess_images(raw_color_im,
raw_depth_im,
camera_intr,
T_camera_world,
workspace_box,
workspace_im,
image_proc_config):
""" Preprocess a set of color and depth images. """
... | [
"def",
"preprocess_images",
"(",
"raw_color_im",
",",
"raw_depth_im",
",",
"camera_intr",
",",
"T_camera_world",
",",
"workspace_box",
",",
"workspace_im",
",",
"image_proc_config",
")",
":",
"# read params",
"inpaint_rescale_factor",
"=",
"image_proc_config",
"[",
"'in... | 42.565217 | 20.945652 |
def read_inquiry_mode(sock):
"""returns the current mode, or -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# read_inquiry_mode command
flt = bluez.hci_filter_new()
opcode ... | [
"def",
"read_inquiry_mode",
"(",
"sock",
")",
":",
"# save current filter",
"old_filter",
"=",
"sock",
".",
"getsockopt",
"(",
"bluez",
".",
"SOL_HCI",
",",
"bluez",
".",
"HCI_FILTER",
",",
"14",
")",
"# Setup socket filter to receive only events related to the",
"# r... | 35.296296 | 17.962963 |
def _add_raster_layer(self, raster_layer, layer_name, save_style=False):
"""Add a raster layer to the folder.
:param raster_layer: The layer to add.
:type raster_layer: QgsRasterLayer
:param layer_name: The name of the layer in the datastore.
:type layer_name: str
:par... | [
"def",
"_add_raster_layer",
"(",
"self",
",",
"raster_layer",
",",
"layer_name",
",",
"save_style",
"=",
"False",
")",
":",
"source",
"=",
"gdal",
".",
"Open",
"(",
"raster_layer",
".",
"source",
"(",
")",
")",
"array",
"=",
"source",
".",
"GetRasterBand",... | 32.136364 | 20.704545 |
def delete_password(self, service, username):
"""Delete the password for the username of the service.
"""
if not self.connected(service):
# the user pressed "cancel" when prompted to unlock their keyring.
raise PasswordDeleteError("Cancelled by user")
if not self.... | [
"def",
"delete_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"if",
"not",
"self",
".",
"connected",
"(",
"service",
")",
":",
"# the user pressed \"cancel\" when prompted to unlock their keyring.",
"raise",
"PasswordDeleteError",
"(",
"\"Cancelled b... | 56.222222 | 17.111111 |
def encodeAllRecords(self, records=None, toBeAdded=True):
"""Encodes a list of records.
Parameters:
--------------------------------------------------------------------
records: One or more records. (i,j)th element of this 2D array
specifies the value at field j of record i.
... | [
"def",
"encodeAllRecords",
"(",
"self",
",",
"records",
"=",
"None",
",",
"toBeAdded",
"=",
"True",
")",
":",
"if",
"records",
"is",
"None",
":",
"records",
"=",
"self",
".",
"getAllRecords",
"(",
")",
"if",
"self",
".",
"verbosity",
">",
"0",
":",
"... | 44.705882 | 21.529412 |
def flatten(lst):
"""flatten([["a","btr"],"b", [],["c",["d",["e"], []]]]) will return ['a', 'btr', 'b', 'c', 'd', 'e']"""
def flatten_aux(item, accumulated):
if type(item) != list:
accumulated.append(item)
else:
for l in item:
flatten_aux(l, accumulated)
... | [
"def",
"flatten",
"(",
"lst",
")",
":",
"def",
"flatten_aux",
"(",
"item",
",",
"accumulated",
")",
":",
"if",
"type",
"(",
"item",
")",
"!=",
"list",
":",
"accumulated",
".",
"append",
"(",
"item",
")",
"else",
":",
"for",
"l",
"in",
"item",
":",
... | 35 | 11.636364 |
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):
"""Roll this dataset by an offset along one or more dimensions.
Unlike shift, roll may rotate all variables, including coordinates
if specified. The direction of rotation is consistent with
:py:func:`numpy.roll`.
P... | [
"def",
"roll",
"(",
"self",
",",
"shifts",
"=",
"None",
",",
"roll_coords",
"=",
"None",
",",
"*",
"*",
"shifts_kwargs",
")",
":",
"shifts",
"=",
"either_dict_or_kwargs",
"(",
"shifts",
",",
"shifts_kwargs",
",",
"'roll'",
")",
"invalid",
"=",
"[",
"k",
... | 36.893939 | 22.5 |
def add_scroller_widget(self, ref, left=1, top=1, right=20, bottom=1, direction="h", speed=1, text="Message"):
""" Add Scroller Widget """
if ref not in self.widgets:
widget = ScrollerWidget(screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, direc... | [
"def",
"add_scroller_widget",
"(",
"self",
",",
"ref",
",",
"left",
"=",
"1",
",",
"top",
"=",
"1",
",",
"right",
"=",
"20",
",",
"bottom",
"=",
"1",
",",
"direction",
"=",
"\"h\"",
",",
"speed",
"=",
"1",
",",
"text",
"=",
"\"Message\"",
")",
":... | 53.5 | 32.125 |
def encode_dict(values_dict):
"""Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``Value`` protobufs as dictionary
... | [
"def",
"encode_dict",
"(",
"values_dict",
")",
":",
"return",
"{",
"key",
":",
"encode_value",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"values_dict",
")",
"}"
] | 34.583333 | 25.416667 |
def tree_csp_solver(csp):
"[Fig. 6.11]"
n = len(csp.vars)
assignment = {}
root = csp.vars[0]
X, parent = topological_sort(csp.vars, root)
for Xj in reversed(X):
if not make_arc_consistent(parent[Xj], Xj, csp):
return None
for Xi in X:
if not csp.curr_domains[Xi]:
... | [
"def",
"tree_csp_solver",
"(",
"csp",
")",
":",
"n",
"=",
"len",
"(",
"csp",
".",
"vars",
")",
"assignment",
"=",
"{",
"}",
"root",
"=",
"csp",
".",
"vars",
"[",
"0",
"]",
"X",
",",
"parent",
"=",
"topological_sort",
"(",
"csp",
".",
"vars",
",",... | 28.642857 | 15.928571 |
def get_image_dimensions(request):
"""
Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str)
"""
if... | [
"def",
"get_image_dimensions",
"(",
"request",
")",
":",
"if",
"request",
".",
"service_type",
"is",
"ServiceType",
".",
"WCS",
"or",
"(",
"isinstance",
"(",
"request",
".",
"size_x",
",",
"int",
")",
"and",
"isinstance",
"(",
"request",
".",
"size_y",
","... | 54.15 | 22.85 |
def convert_constant(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert constant layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionar... | [
"def",
"convert_constant",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting constant ...'",
")",
"params_list",
"=",
"params",
"[",
"'value'",
"]",
".",
"numpy",... | 33.73913 | 15.73913 |
def union_q(token):
"""
Appends all the Q() objects.
"""
query = Q()
operation = 'and'
negation = False
for t in token:
if type(t) is ParseResults: # See tokens recursively
query &= union_q(t)
else:
if t in ('or', 'and'): # Set the new op and go to ... | [
"def",
"union_q",
"(",
"token",
")",
":",
"query",
"=",
"Q",
"(",
")",
"operation",
"=",
"'and'",
"negation",
"=",
"False",
"for",
"t",
"in",
"token",
":",
"if",
"type",
"(",
"t",
")",
"is",
"ParseResults",
":",
"# See tokens recursively",
"query",
"&=... | 28.041667 | 15.958333 |
def wrsamp(self, expanded=False, write_dir=''):
"""
Write a wfdb header file and any associated dat files from this
object.
Parameters
----------
expanded : bool, optional
Whether to write the expanded signal (e_d_signal) instead
of the uniform si... | [
"def",
"wrsamp",
"(",
"self",
",",
"expanded",
"=",
"False",
",",
"write_dir",
"=",
"''",
")",
":",
"# Perform field validity and cohesion checks, and write the",
"# header file.",
"self",
".",
"wrheader",
"(",
"write_dir",
"=",
"write_dir",
")",
"if",
"self",
"."... | 35.857143 | 17.666667 |
def project_delete_event(self, proj_info):
"""Process project delete event."""
LOG.debug("Processing project_delete_event...")
proj_id = proj_info.get('resource_info')
proj_name = self.get_project_name(proj_id)
if proj_name:
try:
self.dcnm_client.dele... | [
"def",
"project_delete_event",
"(",
"self",
",",
"proj_info",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Processing project_delete_event...\"",
")",
"proj_id",
"=",
"proj_info",
".",
"get",
"(",
"'resource_info'",
")",
"proj_name",
"=",
"self",
".",
"get_project_name"... | 50.130435 | 19.565217 |
def convert_ensembl_to_entrez(self, ensembl):
"""Convert Ensembl Id to Entrez Gene Id"""
if 'ENST' in ensembl:
pass
else:
raise (IndexError)
# Submit resquest to NCBI eutils/Gene database
server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?... | [
"def",
"convert_ensembl_to_entrez",
"(",
"self",
",",
"ensembl",
")",
":",
"if",
"'ENST'",
"in",
"ensembl",
":",
"pass",
"else",
":",
"raise",
"(",
"IndexError",
")",
"# Submit resquest to NCBI eutils/Gene database",
"server",
"=",
"\"http://eutils.ncbi.nlm.nih.gov/entr... | 36.095238 | 18.571429 |
def options(self, session=None):
"""Get the options set on this collection.
Returns a dictionary of options and their values - see
:meth:`~pymongo.database.Database.create_collection` for more
information on the possible options. Returns an empty
dictionary if the collection has... | [
"def",
"options",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"dbo",
"=",
"self",
".",
"__database",
".",
"client",
".",
"get_database",
"(",
"self",
".",
"__database",
".",
"name",
",",
"self",
".",
"codec_options",
",",
"self",
".",
"read_pre... | 29.594595 | 17.675676 |
def as_list(self, key):
"""
A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]... | [
"def",
"as_list",
"(",
"self",
",",
"key",
")",
":",
"result",
"=",
"self",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"result",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"list",
"(",
"result",
")",
"return",
"[",
"result",
"]"
] | 24.05 | 17.15 |
def call_receivers(self, client, clients_list, message):
"""
Calls receivers callbacks
"""
# Try to parse JSON
try:
json_message = json.loads(message)
except ValueError:
json_message = None
for func, to_json in self.receivers:
... | [
"def",
"call_receivers",
"(",
"self",
",",
"client",
",",
"clients_list",
",",
"message",
")",
":",
"# Try to parse JSON",
"try",
":",
"json_message",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"except",
"ValueError",
":",
"json_message",
"=",
"None",
"... | 26.636364 | 14.090909 |
def addBorrowers(self, *borrowers):
"""Add more transformed MIBs repositories to borrow MIBs from.
Whenever MibCompiler.compile encounters MIB module which neither of
the *searchers* can find or fetched ASN.1 MIB module can not be
parsed (due to syntax errors), these *borrowers* objects... | [
"def",
"addBorrowers",
"(",
"self",
",",
"*",
"borrowers",
")",
":",
"self",
".",
"_borrowers",
".",
"extend",
"(",
"borrowers",
")",
"debug",
".",
"logger",
"&",
"debug",
".",
"flagCompiler",
"and",
"debug",
".",
"logger",
"(",
"'current MIB borrower(s): %s... | 35.909091 | 24.863636 |
def filtered_cls_slots(self, cn: ClassDefinitionName, all_slots: bool=True) \
-> List[SlotDefinitionName]:
""" Return the set of slots associated with the class that meet the filter criteria. Slots will be returned
in defining order, with class slots returned last
@param cn: name o... | [
"def",
"filtered_cls_slots",
"(",
"self",
",",
"cn",
":",
"ClassDefinitionName",
",",
"all_slots",
":",
"bool",
"=",
"True",
")",
"->",
"List",
"[",
"SlotDefinitionName",
"]",
":",
"rval",
"=",
"[",
"]",
"cls",
"=",
"self",
".",
"schema",
".",
"classes",... | 41.352941 | 14.941176 |
def Add(self, request, callback=None):
"""Add a new request.
Args:
request: A http_wrapper.Request to add to the batch.
callback: A callback to be called for this response, of the
form callback(response, exception). The first parameter is the
deserialized... | [
"def",
"Add",
"(",
"self",
",",
"request",
",",
"callback",
"=",
"None",
")",
":",
"handler",
"=",
"RequestResponseAndHandler",
"(",
"request",
",",
"None",
",",
"callback",
")",
"self",
".",
"__request_response_handlers",
"[",
"self",
".",
"_NewId",
"(",
... | 40.647059 | 23.705882 |
def check(self, file):
"""
Checks a given file against all available yara rules
:param file: Path to file
:type file:str
:returns: Python dictionary containing the results
:rtype: list
"""
result = []
for rule in self.ruleset:
matches ... | [
"def",
"check",
"(",
"self",
",",
"file",
")",
":",
"result",
"=",
"[",
"]",
"for",
"rule",
"in",
"self",
".",
"ruleset",
":",
"matches",
"=",
"rule",
".",
"match",
"(",
"file",
")",
"for",
"match",
"in",
"matches",
":",
"result",
".",
"append",
... | 26.375 | 14.875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.