text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def ext_pillar(minion_id, pillar, repo, branch='default', root=None):
'''
Extract pillar from an hg repository
'''
with Repo(repo) as repo:
repo.update(branch)
envname = 'base' if branch == 'default' else branch
if root:
path = os.path.normpath(os.path.join(repo.working_dir, root... | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"repo",
",",
"branch",
"=",
"'default'",
",",
"root",
"=",
"None",
")",
":",
"with",
"Repo",
"(",
"repo",
")",
"as",
"repo",
":",
"repo",
".",
"update",
"(",
"branch",
")",
"envname",
"=",
... | 33.5 | 19.125 |
def clean(self, is_table=False):
"""
Remove reserved keywords from the header.
These are keywords that the fits writer must write in order
to maintain consistency between header and data.
keywords
--------
is_table: bool, optional
Set True if this is... | [
"def",
"clean",
"(",
"self",
",",
"is_table",
"=",
"False",
")",
":",
"rmnames",
"=",
"[",
"'SIMPLE'",
",",
"'EXTEND'",
",",
"'XTENSION'",
",",
"'BITPIX'",
",",
"'PCOUNT'",
",",
"'GCOUNT'",
",",
"'THEAP'",
",",
"'EXTNAME'",
",",
"'BLANK'",
",",
"'ZQUANTI... | 31.816901 | 19.169014 |
def _set_config_defaults(self, request, form, obj=None):
"""
Cycle through app_config_values and sets the form value according to the
options in the current apphook config.
self.app_config_values is a dictionary containing config options as keys, form fields as
values::
... | [
"def",
"_set_config_defaults",
"(",
"self",
",",
"request",
",",
"form",
",",
"obj",
"=",
"None",
")",
":",
"for",
"config_option",
",",
"field",
"in",
"self",
".",
"app_config_values",
".",
"items",
"(",
")",
":",
"if",
"field",
"in",
"form",
".",
"ba... | 37.181818 | 20.636364 |
def find_xml_generator(name="castxml"):
"""
Try to find a c++ parser (xml generator)
Args:
name (str): name of the c++ parser (e.g. castxml)
Returns:
path (str), name (str): path to the xml generator and it's name
If no c++ parser is found the function raises an exception.
py... | [
"def",
"find_xml_generator",
"(",
"name",
"=",
"\"castxml\"",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
">=",
"(",
"3",
",",
"3",
")",
":",
"path",
"=",
"_find_xml_generator_for_python_greater_equals_33",
"(",
"name",
")",
"else",
":"... | 28.375 | 23.541667 |
def add_checkpoint_file(self, filename):
"""
Add filename as a checkpoint file for this DAG job.
"""
if filename not in self.__checkpoint_files:
self.__checkpoint_files.append(filename) | [
"def",
"add_checkpoint_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"__checkpoint_files",
":",
"self",
".",
"__checkpoint_files",
".",
"append",
"(",
"filename",
")"
] | 34 | 5 |
def fileage_handle(self):
"""Get the number of file in the folder."""
self.file_list = []
self.ok_file = []
self.warn_file = []
self.crit_file = []
status = self.ok
if self.args.recursion:
self.__file_list = self.__get_folder(self.args.path)
e... | [
"def",
"fileage_handle",
"(",
"self",
")",
":",
"self",
".",
"file_list",
"=",
"[",
"]",
"self",
".",
"ok_file",
"=",
"[",
"]",
"self",
".",
"warn_file",
"=",
"[",
"]",
"self",
".",
"crit_file",
"=",
"[",
"]",
"status",
"=",
"self",
".",
"ok",
"i... | 42.516854 | 17.516854 |
def transform(self, df):
"""
Transforms a DataFrame in place. Computes all outputs of the DataFrame.
Args:
df (pandas.DataFrame): DataFrame to transform.
"""
for name, function in self.outputs:
df[name] = function(df) | [
"def",
"transform",
"(",
"self",
",",
"df",
")",
":",
"for",
"name",
",",
"function",
"in",
"self",
".",
"outputs",
":",
"df",
"[",
"name",
"]",
"=",
"function",
"(",
"df",
")"
] | 30.444444 | 16.444444 |
def handle(dispatcher, *accept_args, **accept_kwargs):
"""
:param dispatcher: dispatcher to recieve events from
:param accept_args: args to match on
:param accept_kwargs: kwargs to match on
Creates an MNDFunction instance which containing the
argspec and adds the function to the dispatcher.
... | [
"def",
"handle",
"(",
"dispatcher",
",",
"*",
"accept_args",
",",
"*",
"*",
"accept_kwargs",
")",
":",
"def",
"bind_function_later",
"(",
"f",
")",
":",
"bind_function",
"(",
"f",
",",
"dispatcher",
",",
"*",
"accept_args",
",",
"*",
"*",
"accept_kwargs",
... | 35.538462 | 13.384615 |
def ylim(self, low, high):
"""Set yaxis limits
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
"""
self.chart['yAxis'][0]['min'] = low
self.chart['yAxis'][0]['max'] = high
... | [
"def",
"ylim",
"(",
"self",
",",
"low",
",",
"high",
")",
":",
"self",
".",
"chart",
"[",
"'yAxis'",
"]",
"[",
"0",
"]",
"[",
"'min'",
"]",
"=",
"low",
"self",
".",
"chart",
"[",
"'yAxis'",
"]",
"[",
"0",
"]",
"[",
"'max'",
"]",
"=",
"high",
... | 18.764706 | 19.588235 |
def get_datetime(self, tz=None):
"""
Returns the current simulation datetime.
Parameters
----------
tz : tzinfo or str, optional
The timezone to return the datetime in. This defaults to utc.
Returns
-------
dt : datetime
The curre... | [
"def",
"get_datetime",
"(",
"self",
",",
"tz",
"=",
"None",
")",
":",
"dt",
"=",
"self",
".",
"datetime",
"assert",
"dt",
".",
"tzinfo",
"==",
"pytz",
".",
"utc",
",",
"\"Algorithm should have a utc datetime\"",
"if",
"tz",
"is",
"not",
"None",
":",
"dt"... | 28.473684 | 19.105263 |
def signal_terminate(on_terminate):
"""a common case program termination signal"""
for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]:
signal.signal(i, on_terminate) | [
"def",
"signal_terminate",
"(",
"on_terminate",
")",
":",
"for",
"i",
"in",
"[",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIGQUIT",
",",
"signal",
".",
"SIGUSR1",
",",
"signal",
".",
"SIGUSR2",
",",
"signal",
".",
"SIGTERM",
"]",
":",
"signal",
".... | 54 | 15 |
def autolight(scene):
"""
Generate a list of lights for a scene that looks decent.
Parameters
--------------
scene : trimesh.Scene
Scene with geometry
Returns
--------------
lights : [Light]
List of light objects
transforms : (len(lights), 4, 4) float
Transformati... | [
"def",
"autolight",
"(",
"scene",
")",
":",
"# create two default point lights",
"lights",
"=",
"[",
"PointLight",
"(",
")",
",",
"PointLight",
"(",
")",
"]",
"# create two translation matrices for bounds corners",
"transforms",
"=",
"[",
"transformations",
".",
"tran... | 24.12 | 18.36 |
def save(self, outpath):
"""Save this command file as an ascii file.
Agrs:
outpath (str): The output path to save.
"""
with open(outpath, "w") as outfile:
outfile.write(self.dump()) | [
"def",
"save",
"(",
"self",
",",
"outpath",
")",
":",
"with",
"open",
"(",
"outpath",
",",
"\"w\"",
")",
"as",
"outfile",
":",
"outfile",
".",
"write",
"(",
"self",
".",
"dump",
"(",
")",
")"
] | 25.666667 | 15.444444 |
def _fix_toc(pdf_base, pageref_remap, log):
"""Repair the table of contents
Whenever we replace a page wholesale, it gets assigned a new objgen number
and other references to it within the PDF become invalid, most notably in
the table of contents (/Outlines in PDF-speak). In weave_layers we collect
... | [
"def",
"_fix_toc",
"(",
"pdf_base",
",",
"pageref_remap",
",",
"log",
")",
":",
"if",
"not",
"pageref_remap",
":",
"return",
"def",
"remap_dest",
"(",
"dest_node",
")",
":",
"\"\"\"\n Inner helper function: change the objgen for any page from the old we\n inva... | 38.021277 | 21.510638 |
def read_creds_from_csv(filename):
"""
Read credentials from a CSV file
:param filename:
:return:
"""
key_id = None
secret = None
mfa_serial = None
secret_next = False
with open(filename, 'rt') as csvfile:
for i, line in enumerate(csvfile):
values = line.spli... | [
"def",
"read_creds_from_csv",
"(",
"filename",
")",
":",
"key_id",
"=",
"None",
"secret",
"=",
"None",
"mfa_serial",
"=",
"None",
"secret_next",
"=",
"False",
"with",
"open",
"(",
"filename",
",",
"'rt'",
")",
"as",
"csvfile",
":",
"for",
"i",
",",
"line... | 29.041667 | 9.541667 |
def read_nodes(fname, filter_elem, nodefactory=Node, remove_comments=True):
"""
Convert an XML file into a lazy iterator over Node objects
satifying the given specification, i.e. a function element -> boolean.
:param fname: file name of file object
:param filter_elem: element specification
In ... | [
"def",
"read_nodes",
"(",
"fname",
",",
"filter_elem",
",",
"nodefactory",
"=",
"Node",
",",
"remove_comments",
"=",
"True",
")",
":",
"try",
":",
"for",
"_",
",",
"el",
"in",
"iterparse",
"(",
"fname",
",",
"remove_comments",
"=",
"remove_comments",
")",
... | 36.47619 | 16.380952 |
def count_sources_in_cluster(n_src, cdict, rev_dict):
""" Make a vector of sources in each cluster
Parameters
----------
n_src : number of sources
cdict : dict(int:[int,])
A dictionary of clusters. Each cluster is a source index and
the list of other source in the cluster.
... | [
"def",
"count_sources_in_cluster",
"(",
"n_src",
",",
"cdict",
",",
"rev_dict",
")",
":",
"ret_val",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_src",
")",
",",
"int",
")",
"for",
"i",
"in",
"range",
"(",
"n_src",
")",
":",
"try",
":",
"key",
"=",
"rev_d... | 26.176471 | 21.294118 |
def verify_master(self, payload, master_pub=True):
'''
Verify that the master is the same one that was previously accepted.
:param dict payload: The incoming payload. This is a dictionary which may have the following keys:
'aes': The shared AES key
'enc': The format of t... | [
"def",
"verify_master",
"(",
"self",
",",
"payload",
",",
"master_pub",
"=",
"True",
")",
":",
"m_pub_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"opts",
"[",
"'pki_dir'",
"]",
",",
"self",
".",
"mpub",
")",
"m_pub_exists",
"=",
"os",... | 46.766234 | 24.220779 |
def separator_color(self, value):
"""
Setter for **self.__separator_color** attribute.
:param value: Attribute value.
:type value: QColor
"""
if value is not None:
assert type(value) is QColor, "'{0}' attribute: '{1}' type is not 'QColor'!".format(
... | [
"def",
"separator_color",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"QColor",
",",
"\"'{0}' attribute: '{1}' type is not 'QColor'!\"",
".",
"format",
"(",
"\"separator_color\"",
",",
... | 31.666667 | 15.666667 |
def compare_dicts(i):
"""
Input: {
dict1 - dictionary 1
dict2 - dictionary 2
(ignore_case) - ignore case of letters
Note that if dict1 and dict2 has lists, the results will be as follows:
* dict1={"key":['a','b','c']}
... | [
"def",
"compare_dicts",
"(",
"i",
")",
":",
"d1",
"=",
"i",
".",
"get",
"(",
"'dict1'",
",",
"{",
"}",
")",
"d2",
"=",
"i",
".",
"get",
"(",
"'dict2'",
",",
"{",
"}",
")",
"equal",
"=",
"'yes'",
"bic",
"=",
"False",
"ic",
"=",
"i",
".",
"ge... | 22.488636 | 21.556818 |
def validate(collection, onerror: Callable[[str, List], None] = None):
"""Validate BioC data structure."""
BioCValidator(onerror).validate(collection) | [
"def",
"validate",
"(",
"collection",
",",
"onerror",
":",
"Callable",
"[",
"[",
"str",
",",
"List",
"]",
",",
"None",
"]",
"=",
"None",
")",
":",
"BioCValidator",
"(",
"onerror",
")",
".",
"validate",
"(",
"collection",
")"
] | 52 | 12.333333 |
def send_at(self, value):
"""A unix timestamp specifying when your email should
be delivered.
:param value: A unix timestamp specifying when your email should
be delivered.
:type value: SendAt, int
"""
if isinstance(value, SendAt):
if value.personaliz... | [
"def",
"send_at",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"SendAt",
")",
":",
"if",
"value",
".",
"personalization",
"is",
"not",
"None",
":",
"try",
":",
"personalization",
"=",
"self",
".",
"_personalizations",
"[",
... | 37.923077 | 15.461538 |
def _switchTo(self, newProto, clientFactory=None):
""" Switch this Juice instance to a new protocol. You need to do this
'simultaneously' on both ends of a connection; the easiest way to do
this is to use a subclass of ProtocolSwitchCommand.
"""
assert self.innerProtocol is Non... | [
"def",
"_switchTo",
"(",
"self",
",",
"newProto",
",",
"clientFactory",
"=",
"None",
")",
":",
"assert",
"self",
".",
"innerProtocol",
"is",
"None",
",",
"\"Protocol can only be safely switched once.\"",
"self",
".",
"setRawMode",
"(",
")",
"self",
".",
"innerPr... | 47.727273 | 17.454545 |
def extract(self, item):
"""Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results.
:param item: NewscrawlerItem to be processed.
:return: An updated NewscrawlerItem including the results of the extraction
"""
article_candidates = []
... | [
"def",
"extract",
"(",
"self",
",",
"item",
")",
":",
"article_candidates",
"=",
"[",
"]",
"for",
"extractor",
"in",
"self",
".",
"extractor_list",
":",
"article_candidates",
".",
"append",
"(",
"extractor",
".",
"extract",
"(",
"item",
")",
")",
"article_... | 38.333333 | 20.458333 |
def create(cls, sessions=None):
"""
A session manager will be mounted to the SMCRequest class through
this classmethod. If there is already an existing SessionManager,
that is returned instead.
:param list sessions: a list of Session objects
:rtype: SessionManage... | [
"def",
"create",
"(",
"cls",
",",
"sessions",
"=",
"None",
")",
":",
"manager",
"=",
"getattr",
"(",
"SMCRequest",
",",
"'_session_manager'",
")",
"if",
"manager",
"is",
"not",
"None",
":",
"return",
"manager",
"manager",
"=",
"SessionManager",
"(",
"sessi... | 35.066667 | 14.4 |
def field_dict_from_row(row, model,
field_names=None, ignore_fields=('id', 'pk'),
strip=True,
blank_none=True,
ignore_related=True,
ignore_values=(None,),
ignore_errors=Tr... | [
"def",
"field_dict_from_row",
"(",
"row",
",",
"model",
",",
"field_names",
"=",
"None",
",",
"ignore_fields",
"=",
"(",
"'id'",
",",
"'pk'",
")",
",",
"strip",
"=",
"True",
",",
"blank_none",
"=",
"True",
",",
"ignore_related",
"=",
"True",
",",
"ignore... | 52.035714 | 24.732143 |
def match(self, key, creds, salt, **kwargs):
"""Checks whether the user-provided key matches the user's credentials
:param key: User-supplied key
:param creds: User's stored credentials
:param salt: Salt for hashing
:param kwargs: Extra keyword args for compatibility reason with... | [
"def",
"match",
"(",
"self",
",",
"key",
",",
"creds",
",",
"salt",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"encode_w_salt",
"(",
"salt",
",",
"key",
")",
"==",
"creds"
] | 44.727273 | 12.272727 |
def all_providers_cnpj(df):
"""
Return CPF/CNPJ of all providers
in database.
"""
cnpj_list = []
for _, items in df.groupby('PRONAC'):
unique_cnpjs = items['nrCNPJCPF'].unique()
cnpj_list += list(unique_cnpjs)
return pd.DataFrame(cnpj_list) | [
"def",
"all_providers_cnpj",
"(",
"df",
")",
":",
"cnpj_list",
"=",
"[",
"]",
"for",
"_",
",",
"items",
"in",
"df",
".",
"groupby",
"(",
"'PRONAC'",
")",
":",
"unique_cnpjs",
"=",
"items",
"[",
"'nrCNPJCPF'",
"]",
".",
"unique",
"(",
")",
"cnpj_list",
... | 22.916667 | 13.416667 |
def to_ufo_glyph_anchors(self, glyph, anchors):
"""Add .glyphs anchors to a glyph."""
for anchor in anchors:
x, y = anchor.position
anchor_dict = {"name": anchor.name, "x": x, "y": y}
glyph.appendAnchor(anchor_dict) | [
"def",
"to_ufo_glyph_anchors",
"(",
"self",
",",
"glyph",
",",
"anchors",
")",
":",
"for",
"anchor",
"in",
"anchors",
":",
"x",
",",
"y",
"=",
"anchor",
".",
"position",
"anchor_dict",
"=",
"{",
"\"name\"",
":",
"anchor",
".",
"name",
",",
"\"x\"",
":"... | 34.571429 | 13 |
def _read_http_data(self, size, kind, flag):
"""Read HTTP/2 DATA frames.
Structure of HTTP/2 DATA frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
... | [
"def",
"_read_http_data",
"(",
"self",
",",
"size",
",",
"kind",
",",
"flag",
")",
":",
"_plen",
"=",
"0",
"_flag",
"=",
"dict",
"(",
"END_STREAM",
"=",
"False",
",",
"# bit 0",
"PADDED",
"=",
"False",
",",
"# bit 3",
")",
"for",
"index",
",",
"bit",... | 41.057971 | 22.449275 |
def centroid_1dg(data, error=None, mask=None):
"""
Calculate the centroid of a 2D array by fitting 1D Gaussians to the
marginal ``x`` and ``y`` distributions of the array.
Invalid values (e.g. NaNs or infs) in the ``data`` or ``error``
arrays are automatically masked. The mask for invalid values
... | [
"def",
"centroid_1dg",
"(",
"data",
",",
"error",
"=",
"None",
",",
"mask",
"=",
"None",
")",
":",
"data",
"=",
"np",
".",
"ma",
".",
"asanyarray",
"(",
"data",
")",
"if",
"mask",
"is",
"not",
"None",
"and",
"mask",
"is",
"not",
"np",
".",
"ma",
... | 34.808219 | 20.479452 |
def translateDNA(sequence, frame = 'f1', translTable_id='default') :
"""Translates DNA code, frame : fwd1, fwd2, fwd3, rev1, rev2, rev3"""
protein = ""
if frame == 'f1' :
dna = sequence
elif frame == 'f2':
dna = sequence[1:]
elif frame == 'f3' :
dna = sequence[2:]
elif frame == 'r1' :
dna = reverseCompl... | [
"def",
"translateDNA",
"(",
"sequence",
",",
"frame",
"=",
"'f1'",
",",
"translTable_id",
"=",
"'default'",
")",
":",
"protein",
"=",
"\"\"",
"if",
"frame",
"==",
"'f1'",
":",
"dna",
"=",
"sequence",
"elif",
"frame",
"==",
"'f2'",
":",
"dna",
"=",
"seq... | 27.439024 | 22.121951 |
def installed(cls):
"""
Used in ``yacms.pages.views.page`` to ensure
``PageMiddleware`` or a subclass has been installed. We cache
the result on the ``PageMiddleware._installed`` to only run
this once. Short path is to just check for the dotted path to
``PageMiddleware`` ... | [
"def",
"installed",
"(",
"cls",
")",
":",
"try",
":",
"return",
"cls",
".",
"_installed",
"except",
"AttributeError",
":",
"name",
"=",
"\"yacms.pages.middleware.PageMiddleware\"",
"mw_setting",
"=",
"get_middleware_setting",
"(",
")",
"installed",
"=",
"name",
"i... | 42.5 | 14.318182 |
def MultiNotifyQueue(self, notifications, mutation_pool=None):
"""This is the same as NotifyQueue but for several session_ids at once.
Args:
notifications: A list of notifications.
mutation_pool: A MutationPool object to schedule Notifications on.
Raises:
RuntimeError: An invalid session... | [
"def",
"MultiNotifyQueue",
"(",
"self",
",",
"notifications",
",",
"mutation_pool",
"=",
"None",
")",
":",
"extract_queue",
"=",
"lambda",
"notification",
":",
"notification",
".",
"session_id",
".",
"Queue",
"(",
")",
"for",
"queue",
",",
"notifications",
"in... | 41.642857 | 21.5 |
async def vcx_agent_provision(config: str) -> None:
"""
Provision an agent in the agency, populate configuration and wallet for this agent.
Example:
import json
enterprise_config = {
'agency_url': 'http://localhost:8080',
'agency_did': 'VsKV7grR1BUE29mG2Fm2kX',
'agency_verkey... | [
"async",
"def",
"vcx_agent_provision",
"(",
"config",
":",
"str",
")",
"->",
"None",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"not",
"hasattr",
"(",
"vcx_agent_provision",
",",
"\"cb\"",
")",
":",
"logger",
".",
"debug",... | 38.09375 | 18.65625 |
def add(self, num):
"""
Adds num to the current value, jumping up the next
multiple of mfac if the result is not a multiple already
"""
try:
val = self.value() + num
except:
val = num
chunk = self.mfac.value()
if val % chunk > 0:
... | [
"def",
"add",
"(",
"self",
",",
"num",
")",
":",
"try",
":",
"val",
"=",
"self",
".",
"value",
"(",
")",
"+",
"num",
"except",
":",
"val",
"=",
"num",
"chunk",
"=",
"self",
".",
"mfac",
".",
"value",
"(",
")",
"if",
"val",
"%",
"chunk",
">",
... | 27.210526 | 16.368421 |
def _parse_quit(client, command, actor, args):
"""Parse a QUIT and update channel states, then dispatch events.
Note that two events are dispatched here:
- QUIT, because a user quit the server
- MEMBERS, for each channel the user is no longer in
"""
actor = User(actor)
_, _, message... | [
"def",
"_parse_quit",
"(",
"client",
",",
"command",
",",
"actor",
",",
"args",
")",
":",
"actor",
"=",
"User",
"(",
"actor",
")",
"_",
",",
"_",
",",
"message",
"=",
"args",
".",
"partition",
"(",
"':'",
")",
"client",
".",
"dispatch_event",
"(",
... | 39.857143 | 9.5 |
def buildCliString(self):
"""
Collect all of the required information from the config screen and
build a CLI string which can be used to invoke the client program
"""
config = self.navbar.getActiveConfig()
group = self.buildSpec['widgets'][self.navbar.getSelectedGro... | [
"def",
"buildCliString",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"navbar",
".",
"getActiveConfig",
"(",
")",
"group",
"=",
"self",
".",
"buildSpec",
"[",
"'widgets'",
"]",
"[",
"self",
".",
"navbar",
".",
"getSelectedGroup",
"(",
")",
"]",
"... | 34.619048 | 14.333333 |
def monitor(self, target):
""" Start monitoring the online status of a user. Returns whether or not the server supports monitoring. """
if 'monitor-notify' in self._capabilities and not self.is_monitoring(target):
yield from self.rawmsg('MONITOR', '+', target)
self._monitoring.ad... | [
"def",
"monitor",
"(",
"self",
",",
"target",
")",
":",
"if",
"'monitor-notify'",
"in",
"self",
".",
"_capabilities",
"and",
"not",
"self",
".",
"is_monitoring",
"(",
"target",
")",
":",
"yield",
"from",
"self",
".",
"rawmsg",
"(",
"'MONITOR'",
",",
"'+'... | 48.125 | 17.125 |
def SETS(cpu, dest):
"""
Sets byte if sign.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.SF, 1, 0)) | [
"def",
"SETS",
"(",
"cpu",
",",
"dest",
")",
":",
"dest",
".",
"write",
"(",
"Operators",
".",
"ITEBV",
"(",
"dest",
".",
"size",
",",
"cpu",
".",
"SF",
",",
"1",
",",
"0",
")",
")"
] | 25.125 | 12.875 |
def _from_dict(cls, _dict):
"""Initialize a UtteranceAnalysis object from a json dictionary."""
args = {}
if 'utterance_id' in _dict:
args['utterance_id'] = _dict.get('utterance_id')
else:
raise ValueError(
'Required property \'utterance_id\' not p... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'utterance_id'",
"in",
"_dict",
":",
"args",
"[",
"'utterance_id'",
"]",
"=",
"_dict",
".",
"get",
"(",
"'utterance_id'",
")",
"else",
":",
"raise",
"ValueError",
"(... | 38 | 20.884615 |
def _store32(ins):
""" Stores 2nd operand content into address of 1st operand.
store16 a, x => *(&a) = x
"""
op = ins.quad[1]
indirect = op[0] == '*'
if indirect:
op = op[1:]
immediate = op[0] == '#' # Might make no sense here?
if immediate:
op = op[1:]
if is_int... | [
"def",
"_store32",
"(",
"ins",
")",
":",
"op",
"=",
"ins",
".",
"quad",
"[",
"1",
"]",
"indirect",
"=",
"op",
"[",
"0",
"]",
"==",
"'*'",
"if",
"indirect",
":",
"op",
"=",
"op",
"[",
"1",
":",
"]",
"immediate",
"=",
"op",
"[",
"0",
"]",
"==... | 22.6 | 20.466667 |
def head_request(self, container, resource=None):
"""Send a HEAD request."""
url = self.make_url(container, resource)
headers = self._make_headers(None)
try:
rsp = requests.head(url, headers=self._base_headers,
verify=self._verify, timeout=sel... | [
"def",
"head_request",
"(",
"self",
",",
"container",
",",
"resource",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"make_url",
"(",
"container",
",",
"resource",
")",
"headers",
"=",
"self",
".",
"_make_headers",
"(",
"None",
")",
"try",
":",
"rsp"... | 35.866667 | 19.066667 |
def _do_pass(self, pass_, dag, options):
"""Do a pass and its "requires".
Args:
pass_ (BasePass): Pass to do.
dag (DAGCircuit): The dag on which the pass is ran.
options (dict): PassManager options.
Returns:
DAGCircuit: The transformed dag in case... | [
"def",
"_do_pass",
"(",
"self",
",",
"pass_",
",",
"dag",
",",
"options",
")",
":",
"# First, do the requires of pass_",
"if",
"not",
"options",
"[",
"\"ignore_requires\"",
"]",
":",
"for",
"required_pass",
"in",
"pass_",
".",
"requires",
":",
"dag",
"=",
"s... | 43 | 20.769231 |
def chunk_to_matrices(narr, mapcol, nmask):
"""
numba compiled code to get matrix fast.
arr is a 4 x N seq matrix converted to np.int8
I convert the numbers for ATGC into their respective index for the MAT
matrix, and leave all others as high numbers, i.e., -==45, N==78.
"""
## get seq al... | [
"def",
"chunk_to_matrices",
"(",
"narr",
",",
"mapcol",
",",
"nmask",
")",
":",
"## get seq alignment and create an empty array for filling",
"mats",
"=",
"np",
".",
"zeros",
"(",
"(",
"3",
",",
"16",
",",
"16",
")",
",",
"dtype",
"=",
"np",
".",
"uint32",
... | 38.709677 | 19.322581 |
def put(self, item):
"""Put an item into the queue.
True - if item placed in queue.
False - if queue is full and item can not be placed."""
if self.__maxsize and len(self.__data) >= self.__maxsize:
return False
self.__data.append(item)
return True | [
"def",
"put",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
".",
"__maxsize",
"and",
"len",
"(",
"self",
".",
"__data",
")",
">=",
"self",
".",
"__maxsize",
":",
"return",
"False",
"self",
".",
"__data",
".",
"append",
"(",
"item",
")",
"return... | 37.5 | 11.375 |
def filter_matrix_rows(A, theta):
"""Filter each row of A with tol.
i.e., drop all entries in row k where
abs(A[i,k]) < tol max( abs(A[:,k]) )
Parameters
----------
A : sparse_matrix
theta : float
In range [0,1) and defines drop-tolerance used to filter the row of A
Retur... | [
"def",
"filter_matrix_rows",
"(",
"A",
",",
"theta",
")",
":",
"if",
"not",
"isspmatrix",
"(",
"A",
")",
":",
"raise",
"ValueError",
"(",
"\"Sparse matrix input needed\"",
")",
"if",
"isspmatrix_bsr",
"(",
"A",
")",
":",
"blocksize",
"=",
"A",
".",
"blocks... | 31.520548 | 20.205479 |
def poll(
self, lease_seconds=LEASE_SECONDS, tag=None,
verbose=False, execute_args=[], execute_kwargs={},
stop_fn=None, backoff_exceptions=[], min_backoff_window=30,
max_backoff_window=120, log_fn=None
):
"""
Poll a queue until a stop condition is reached (default forever). Note
that th... | [
"def",
"poll",
"(",
"self",
",",
"lease_seconds",
"=",
"LEASE_SECONDS",
",",
"tag",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"execute_args",
"=",
"[",
"]",
",",
"execute_kwargs",
"=",
"{",
"}",
",",
"stop_fn",
"=",
"None",
",",
"backoff_exceptions... | 33.905263 | 22.915789 |
def send_file(self, fp, headers=None, cb=None, num_cb=10,
query_args=None, chunked_transfer=False, size=None):
"""
Upload a file to a key into a bucket on S3.
:type fp: file
:param fp: The file pointer to upload. The file pointer must point
point at ... | [
"def",
"send_file",
"(",
"self",
",",
"fp",
",",
"headers",
"=",
"None",
",",
"cb",
"=",
"None",
",",
"num_cb",
"=",
"10",
",",
"query_args",
"=",
"None",
",",
"chunked_transfer",
"=",
"False",
",",
"size",
"=",
"None",
")",
":",
"provider",
"=",
"... | 44.209756 | 18.736585 |
def ParseGroupEntry(self, line):
"""Extract the members of a group from /etc/group."""
fields = ("name", "passwd", "gid", "members")
if line:
rslt = dict(zip(fields, line.split(":")))
name = rslt["name"]
group = self.entry.setdefault(name, rdf_client.Group(name=name))
group.pw_entry.... | [
"def",
"ParseGroupEntry",
"(",
"self",
",",
"line",
")",
":",
"fields",
"=",
"(",
"\"name\"",
",",
"\"passwd\"",
",",
"\"gid\"",
",",
"\"members\"",
")",
"if",
"line",
":",
"rslt",
"=",
"dict",
"(",
"zip",
"(",
"fields",
",",
"line",
".",
"split",
"(... | 46.071429 | 15.428571 |
def cli_program_names(self):
r"""Developer script program names.
"""
program_names = {}
for cli_class in self.cli_classes:
instance = cli_class()
program_names[instance.program_name] = cli_class
return program_names | [
"def",
"cli_program_names",
"(",
"self",
")",
":",
"program_names",
"=",
"{",
"}",
"for",
"cli_class",
"in",
"self",
".",
"cli_classes",
":",
"instance",
"=",
"cli_class",
"(",
")",
"program_names",
"[",
"instance",
".",
"program_name",
"]",
"=",
"cli_class"... | 34 | 8.25 |
def value(self):
"""
Represents the speed of the motor as a floating point value between -1
(full speed backward) and 1 (full speed forward).
"""
return (
-self.enable_device.value
if self.phase_device.is_active else
self.enable_device.value
... | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"(",
"-",
"self",
".",
"enable_device",
".",
"value",
"if",
"self",
".",
"phase_device",
".",
"is_active",
"else",
"self",
".",
"enable_device",
".",
"value",
")"
] | 31.8 | 14.8 |
def input_file(filename):
"""
Run all checks on a Python source file.
"""
if excluded(filename) or not filename_match(filename):
return {}
if options.verbose:
message('checking ' + filename)
options.counters['files'] = options.counters.get('files', 0) + 1
errors = Checker(fil... | [
"def",
"input_file",
"(",
"filename",
")",
":",
"if",
"excluded",
"(",
"filename",
")",
"or",
"not",
"filename_match",
"(",
"filename",
")",
":",
"return",
"{",
"}",
"if",
"options",
".",
"verbose",
":",
"message",
"(",
"'checking '",
"+",
"filename",
")... | 34.076923 | 11.307692 |
def __change_inferencing_mode(self, inferencing_mode):
'''
Change dropout rate in Encoder/Decoder.
Args:
dropout_rate: The probalibity of dropout.
'''
self.__encoder_decoder_controller.decoder.opt_params.inferencing_mode = inferencing_mode
s... | [
"def",
"__change_inferencing_mode",
"(",
"self",
",",
"inferencing_mode",
")",
":",
"self",
".",
"__encoder_decoder_controller",
".",
"decoder",
".",
"opt_params",
".",
"inferencing_mode",
"=",
"inferencing_mode",
"self",
".",
"__encoder_decoder_controller",
".",
"encod... | 48.3 | 30.9 |
def sort_reverse_chronologically(self):
"""
Sorts the measurements of this buffer in reverse chronological order
"""
self.measurements.sort(key=lambda m: m.timestamp, reverse=True) | [
"def",
"sort_reverse_chronologically",
"(",
"self",
")",
":",
"self",
".",
"measurements",
".",
"sort",
"(",
"key",
"=",
"lambda",
"m",
":",
"m",
".",
"timestamp",
",",
"reverse",
"=",
"True",
")"
] | 34.666667 | 18 |
def create_role(self, name=None, permissions=""):
""" Creates role """
name = name or "autocreated-role"
from qubell.api.private.role import Role
return Role.new(self._router, organization=self, name=name, permissions=permissions) | [
"def",
"create_role",
"(",
"self",
",",
"name",
"=",
"None",
",",
"permissions",
"=",
"\"\"",
")",
":",
"name",
"=",
"name",
"or",
"\"autocreated-role\"",
"from",
"qubell",
".",
"api",
".",
"private",
".",
"role",
"import",
"Role",
"return",
"Role",
".",... | 51.6 | 14 |
def fetch(self):
"""
Fetch a ChallengeInstance
:returns: Fetched ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"Chall... | 27.086957 | 17.608696 |
def from_file(file_path) -> dict:
""" Load JSON file """
with io.open(file_path, 'r', encoding='utf-8') as json_stream:
return Json.parse(json_stream, True) | [
"def",
"from_file",
"(",
"file_path",
")",
"->",
"dict",
":",
"with",
"io",
".",
"open",
"(",
"file_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"json_stream",
":",
"return",
"Json",
".",
"parse",
"(",
"json_stream",
",",
"True",
")"
... | 46 | 11.25 |
def clear(self):
"""Clear sketch"""
self.ranking = []
heapq.heapify(self.ranking)
self.dq = deque(maxlen=self.k)
self.num = 0
return self.clear_method(self) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"ranking",
"=",
"[",
"]",
"heapq",
".",
"heapify",
"(",
"self",
".",
"ranking",
")",
"self",
".",
"dq",
"=",
"deque",
"(",
"maxlen",
"=",
"self",
".",
"k",
")",
"self",
".",
"num",
"=",
"0",
... | 28.285714 | 9.714286 |
def get_task_indicator(self, task_level=None):
"""
Args:
task_level (int or None): task depth level to get the indicator
for, if None, will use the current tasks depth
Returns:
str: char to prepend to the task logs to indicate it's level
"""
... | [
"def",
"get_task_indicator",
"(",
"self",
",",
"task_level",
"=",
"None",
")",
":",
"if",
"task_level",
"is",
"None",
":",
"task_level",
"=",
"len",
"(",
"self",
".",
"tasks",
")",
"return",
"self",
".",
"TASK_INDICATORS",
"[",
"task_level",
"%",
"len",
... | 37.583333 | 19.25 |
def find_partition(graph, partition_type, initial_membership=None, weights=None, n_iterations=2, seed=None, **kwargs):
""" Detect communities using the default settings.
This function detects communities given the specified method in the
``partition_type``. This should be type derived from
:class:`VertexPartit... | [
"def",
"find_partition",
"(",
"graph",
",",
"partition_type",
",",
"initial_membership",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"n_iterations",
"=",
"2",
",",
"seed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"weights",
"is",
... | 31.074627 | 24.970149 |
def producer(self):
"""
:raises: kafka.errors.NoBrokersAvailable if the connection is broken
"""
if self._producer:
return self._producer
self._producer = KafkaProducer(
bootstrap_servers=self.hosts,
value_serializer=lambda v: self._serializer... | [
"def",
"producer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_producer",
":",
"return",
"self",
".",
"_producer",
"self",
".",
"_producer",
"=",
"KafkaProducer",
"(",
"bootstrap_servers",
"=",
"self",
".",
"hosts",
",",
"value_serializer",
"=",
"lambda",
... | 29.214286 | 18.928571 |
def start(self):
"""
Starts this bot in a separate thread. Therefore, this call is non-blocking.
It will listen to all new comments created in the :attr:`~subreddits` list.
"""
super().start()
comments_thread = BotThread(name='{}-comments-stream-thread'.format(self._name... | [
"def",
"start",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"start",
"(",
")",
"comments_thread",
"=",
"BotThread",
"(",
"name",
"=",
"'{}-comments-stream-thread'",
".",
"format",
"(",
"self",
".",
"_name",
")",
",",
"target",
"=",
"self",
".",
"_li... | 42.416667 | 22.25 |
def get_milestone(number=None,
name=None,
repo_name=None,
profile='github',
output='min'):
'''
Return information about a single milestone in a named repository.
.. versionadded:: 2016.11.0
number
The number of the milesto... | [
"def",
"get_milestone",
"(",
"number",
"=",
"None",
",",
"name",
"=",
"None",
",",
"repo_name",
"=",
"None",
",",
"profile",
"=",
"'github'",
",",
"output",
"=",
"'min'",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"any",
"(",
"[",
"number",
",",
... | 30.84507 | 23.577465 |
def add_category(self, category):
'''
Add unicode category to set
Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc.
See `unicodedata.category()`
'''
if category == sre.CATEGORY_DIGIT:
self._categories |= UNICODE_DIGIT_CATEGORIES
elif category... | [
"def",
"add_category",
"(",
"self",
",",
"category",
")",
":",
"if",
"category",
"==",
"sre",
".",
"CATEGORY_DIGIT",
":",
"self",
".",
"_categories",
"|=",
"UNICODE_DIGIT_CATEGORIES",
"elif",
"category",
"==",
"sre",
".",
"CATEGORY_NOT_DIGIT",
":",
"self",
"."... | 48.354839 | 15.709677 |
def load_word_file(filename):
"""Loads a words file as a list of lines"""
words_file = resource_filename(__name__, "words/%s" % filename)
handle = open(words_file, 'r')
words = handle.readlines()
handle.close()
return words | [
"def",
"load_word_file",
"(",
"filename",
")",
":",
"words_file",
"=",
"resource_filename",
"(",
"__name__",
",",
"\"words/%s\"",
"%",
"filename",
")",
"handle",
"=",
"open",
"(",
"words_file",
",",
"'r'",
")",
"words",
"=",
"handle",
".",
"readlines",
"(",
... | 34.428571 | 14.285714 |
def get_label(self):
"""
get label as ndarray from ImageFeature
"""
label = callBigDlFunc(self.bigdl_type, "imageFeatureToLabelTensor", self.value)
return label.to_ndarray() | [
"def",
"get_label",
"(",
"self",
")",
":",
"label",
"=",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"imageFeatureToLabelTensor\"",
",",
"self",
".",
"value",
")",
"return",
"label",
".",
"to_ndarray",
"(",
")"
] | 34.666667 | 13.333333 |
def set_reload_params(
self, min_lifetime=None, max_lifetime=None,
max_requests=None, max_requests_delta=None,
max_addr_space=None, max_rss=None, max_uss=None, max_pss=None,
max_addr_space_forced=None, max_rss_forced=None, watch_interval_forced=None,
mercy=Non... | [
"def",
"set_reload_params",
"(",
"self",
",",
"min_lifetime",
"=",
"None",
",",
"max_lifetime",
"=",
"None",
",",
"max_requests",
"=",
"None",
",",
"max_requests_delta",
"=",
"None",
",",
"max_addr_space",
"=",
"None",
",",
"max_rss",
"=",
"None",
",",
"max_... | 43.064935 | 29.857143 |
def get_csv_rows_for_installed(
old_csv_rows, # type: Iterable[List[str]]
installed, # type: Dict[str, str]
changed, # type: set
generated, # type: List[str]
lib_dir, # type: str
):
# type: (...) -> List[InstalledCSVRow]
"""
:param installed: A map from archive RECORD path to instal... | [
"def",
"get_csv_rows_for_installed",
"(",
"old_csv_rows",
",",
"# type: Iterable[List[str]]",
"installed",
",",
"# type: Dict[str, str]",
"changed",
",",
"# type: set",
"generated",
",",
"# type: List[str]",
"lib_dir",
",",
"# type: str",
")",
":",
"# type: (...) -> List[Inst... | 33.705882 | 14.352941 |
def reload_class(self, verbose=True, reload_module=True):
"""
special class reloading function
This function is often injected as rrr of classes
"""
import utool as ut
verbose = verbose or VERBOSE_CLASS
classname = self.__class__.__name__
try:
modname = self.__class__.__module__
... | [
"def",
"reload_class",
"(",
"self",
",",
"verbose",
"=",
"True",
",",
"reload_module",
"=",
"True",
")",
":",
"import",
"utool",
"as",
"ut",
"verbose",
"=",
"verbose",
"or",
"VERBOSE_CLASS",
"classname",
"=",
"self",
".",
"__class__",
".",
"__name__",
"try... | 42.617284 | 16.888889 |
def query(self, parents=None):
""" Compose the query and generate SPARQL. """
# TODO: benchmark single-query strategy
q = Select([])
q = self.project(q, parent=True)
q = self.filter(q, parents=parents)
if self.parent is None:
subq = Select([self.var])
... | [
"def",
"query",
"(",
"self",
",",
"parents",
"=",
"None",
")",
":",
"# TODO: benchmark single-query strategy",
"q",
"=",
"Select",
"(",
"[",
"]",
")",
"q",
"=",
"self",
".",
"project",
"(",
"q",
",",
"parent",
"=",
"True",
")",
"q",
"=",
"self",
".",... | 36.761905 | 12.571429 |
def format_name(self, format_name):
"""Set the default format name.
:param str format_name: The display format name.
:raises ValueError: if the format is not recognized.
"""
if format_name in self.supported_formats:
self._format_name = format_name
else:
... | [
"def",
"format_name",
"(",
"self",
",",
"format_name",
")",
":",
"if",
"format_name",
"in",
"self",
".",
"supported_formats",
":",
"self",
".",
"_format_name",
"=",
"format_name",
"else",
":",
"raise",
"ValueError",
"(",
"'unrecognized format_name \"{}\"'",
".",
... | 33.583333 | 16.583333 |
def get_qual(fastafile, suffix=QUALSUFFIX, check=True):
"""
Check if current folder contains a qual file associated with the fastafile
"""
qualfile1 = fastafile.rsplit(".", 1)[0] + suffix
qualfile2 = fastafile + suffix
if check:
if op.exists(qualfile1):
logging.debug("qual f... | [
"def",
"get_qual",
"(",
"fastafile",
",",
"suffix",
"=",
"QUALSUFFIX",
",",
"check",
"=",
"True",
")",
":",
"qualfile1",
"=",
"fastafile",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"+",
"suffix",
"qualfile2",
"=",
"fastafile",
"+",
"... | 32.105263 | 18.210526 |
def set_default(self):
"""Set config to default."""
try:
os.makedirs(os.path.dirname(self._configfile))
except:
pass
self._config = configparser.RawConfigParser()
self._config.add_section('Settings')
for key, val in self.DEFAULTS.items():
... | [
"def",
"set_default",
"(",
"self",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"_configfile",
")",
")",
"except",
":",
"pass",
"self",
".",
"_config",
"=",
"configparser",
".",
"RawConfigParser... | 28.733333 | 18.6 |
def get_req(self, start_size, end_size):
'''打开socket'''
logger.debug('DownloadBatch.get_req: %s, %s' % (start_size, end_size))
opener = request.build_opener()
content_range = 'bytes={0}-{1}'.format(start_size, end_size)
opener.addheaders = [
('Range', content_range),
... | [
"def",
"get_req",
"(",
"self",
",",
"start_size",
",",
"end_size",
")",
":",
"logger",
".",
"debug",
"(",
"'DownloadBatch.get_req: %s, %s'",
"%",
"(",
"start_size",
",",
"end_size",
")",
")",
"opener",
"=",
"request",
".",
"build_opener",
"(",
")",
"content_... | 38.545455 | 16.727273 |
def _build_block_element_list(self):
"""Return a list of block elements, ordered from highest priority to lowest.
"""
return sorted(
[e for e in self.block_elements.values() if not e.virtual],
key=lambda e: e.priority,
reverse=True
) | [
"def",
"_build_block_element_list",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"[",
"e",
"for",
"e",
"in",
"self",
".",
"block_elements",
".",
"values",
"(",
")",
"if",
"not",
"e",
".",
"virtual",
"]",
",",
"key",
"=",
"lambda",
"e",
":",
"e",
... | 36.75 | 12.875 |
def decodeSemiOctets(encodedNumber, numberOfOctets=None):
""" Semi-octet decoding algorithm(e.g. for phone numbers)
:param encodedNumber: The semi-octet-encoded telephone number (in bytearray format or hex string)
:type encodedNumber: bytearray, str or iter(bytearray)
:param numberOfOctets: The exp... | [
"def",
"decodeSemiOctets",
"(",
"encodedNumber",
",",
"numberOfOctets",
"=",
"None",
")",
":",
"number",
"=",
"[",
"]",
"if",
"type",
"(",
"encodedNumber",
")",
"in",
"(",
"str",
",",
"bytes",
")",
":",
"encodedNumber",
"=",
"bytearray",
"(",
"codecs",
"... | 35.259259 | 18.296296 |
def get_posterior(self, twig=None, feedback=None, **kwargs):
"""
[NOT IMPLEMENTED]
:raises NotImplementedError: because it isn't
"""
raise NotImplementedError
kwargs['context'] = 'posterior'
return self.filter(twig=twig, **kwargs) | [
"def",
"get_posterior",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"feedback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"kwargs",
"[",
"'context'",
"]",
"=",
"'posterior'",
"return",
"self",
".",
"filter",
"(",
"tw... | 31 | 11.444444 |
def uninstall_hook(ctx):
""" Uninstall gitlint commit-msg hook. """
try:
lint_config = ctx.obj[0]
hooks.GitHookInstaller.uninstall_commit_msg_hook(lint_config)
# declare victory :-)
hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)
click.echo(u"Successf... | [
"def",
"uninstall_hook",
"(",
"ctx",
")",
":",
"try",
":",
"lint_config",
"=",
"ctx",
".",
"obj",
"[",
"0",
"]",
"hooks",
".",
"GitHookInstaller",
".",
"uninstall_commit_msg_hook",
"(",
"lint_config",
")",
"# declare victory :-)",
"hook_path",
"=",
"hooks",
".... | 43.5 | 18.166667 |
def parse(self, data, extent, desc_tag):
# type: (bytes, int, UDFTag) -> None
'''
Parse the passed in data into a UDF File Set Descriptor.
Parameters:
data - The data to parse.
extent - The extent that this descriptor currently lives at.
desc_tag - A UDFTag ob... | [
"def",
"parse",
"(",
"self",
",",
"data",
",",
"extent",
",",
"desc_tag",
")",
":",
"# type: (bytes, int, UDFTag) -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'UDF File Set Descriptor already initializ... | 43.769231 | 26.615385 |
def comment(self, nme, desc):
"""
Adds a comment to the existing program in the list,
logs the reference and TODO - adds core link to processes
"""
if nme != '':
program_exists = False
for i in self.lstPrograms:
print(i)
... | [
"def",
"comment",
"(",
"self",
",",
"nme",
",",
"desc",
")",
":",
"if",
"nme",
"!=",
"''",
":",
"program_exists",
"=",
"False",
"for",
"i",
"in",
"self",
".",
"lstPrograms",
":",
"print",
"(",
"i",
")",
"if",
"nme",
"in",
"i",
"[",
"0",
"]",
":... | 35.055556 | 16.055556 |
def _filter_library_state(self, items):
"""Filters out child elements of library state when they cannot be hovered
Checks if hovered item is within a LibraryState
* if not, the list is returned unfiltered
* if so, STATE_SELECTION_INSIDE_LIBRARY_STATE_ENABLED is checked
* if ... | [
"def",
"_filter_library_state",
"(",
"self",
",",
"items",
")",
":",
"if",
"not",
"items",
":",
"return",
"items",
"top_most_item",
"=",
"items",
"[",
"0",
"]",
"# If the hovered item is e.g. a connection, we need to get the parental state",
"top_most_state_v",
"=",
"to... | 49.289474 | 26.736842 |
def make_moves(game, player=dominoes.players.identity):
'''
For each of a Game object's valid moves, yields
a tuple containing the move and the Game object
obtained by playing the move on the original Game
object. The original Game object will be modified.
:param Game game: the game to make mov... | [
"def",
"make_moves",
"(",
"game",
",",
"player",
"=",
"dominoes",
".",
"players",
".",
"identity",
")",
":",
"# game is over - do not yield anything",
"if",
"game",
".",
"result",
"is",
"not",
"None",
":",
"return",
"# determine the order in which to make moves",
"p... | 33.058824 | 16 |
def init_tf_ops(sess):
"""Initialize TensorFlow operations.
This function initialize the following tensorflow ops:
* init variables ops
* summary ops
* create model saver
Parameters
----------
sess : object
Tensorflow `Session` object
Returns
-------
... | [
"def",
"init_tf_ops",
"(",
"sess",
")",
":",
"summary_merged",
"=",
"tf",
".",
"summary",
".",
"merge_all",
"(",
")",
"init_op",
"=",
"tf",
".",
"global_variables_initializer",
"(",
")",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"sess",
... | 24.571429 | 20.261905 |
def _prompt_changer(attr, val):
"""Change the current prompt theme"""
try:
sys.ps1 = conf.color_theme.prompt(conf.prompt)
except Exception:
pass
try:
apply_ipython_style(get_ipython())
except NameError:
pass | [
"def",
"_prompt_changer",
"(",
"attr",
",",
"val",
")",
":",
"try",
":",
"sys",
".",
"ps1",
"=",
"conf",
".",
"color_theme",
".",
"prompt",
"(",
"conf",
".",
"prompt",
")",
"except",
"Exception",
":",
"pass",
"try",
":",
"apply_ipython_style",
"(",
"ge... | 25 | 18.3 |
def sync_object(src_obj, dest_repo, export_context='migrate',
overwrite=False, show_progress=False,
requires_auth=False, omit_checksums=False,
verify=False):
'''Copy an object from one repository to another using the Fedora
export functionality.
:param src_ob... | [
"def",
"sync_object",
"(",
"src_obj",
",",
"dest_repo",
",",
"export_context",
"=",
"'migrate'",
",",
"overwrite",
"=",
"False",
",",
"show_progress",
"=",
"False",
",",
"requires_auth",
"=",
"False",
",",
"omit_checksums",
"=",
"False",
",",
"verify",
"=",
... | 44.80198 | 23.633663 |
def datacite_to_pif_reference(dc):
"""
Parse a top-level datacite dictionary into a Reference
:param dc: dictionary containing datacite metadata
:return: Reference corresponding to that datacite entry
"""
ref = Reference()
if dc.get('identifier', {}).get('identifierType') == "DOI":
r... | [
"def",
"datacite_to_pif_reference",
"(",
"dc",
")",
":",
"ref",
"=",
"Reference",
"(",
")",
"if",
"dc",
".",
"get",
"(",
"'identifier'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'identifierType'",
")",
"==",
"\"DOI\"",
":",
"ref",
".",
"doi",
"=",
"dc",... | 35.75 | 17.5 |
def round(self, digits=0):
""" Round the elements of the given vector to the given number of digits. """
# Meant as a way to clean up Vector.rotate()
# For example:
# V = Vector(1,0)
# V.rotate(2*pi)
#
# V is now <1.0, -2.4492935982947064e-16>, when it sh... | [
"def",
"round",
"(",
"self",
",",
"digits",
"=",
"0",
")",
":",
"# Meant as a way to clean up Vector.rotate()",
"# For example:",
"# V = Vector(1,0)",
"# V.rotate(2*pi)",
"# ",
"# V is now <1.0, -2.4492935982947064e-16>, when it should be ",
"# <1,0>. V.round(15) will corre... | 39.583333 | 16.333333 |
def _validate(self, val):
"""
Checks that the value is numeric and that it is within the hard
bounds; if not, an exception is raised.
"""
if self.allow_None and val is None:
return
if not isinstance(val, dt_types) and not (self.allow_None and val is None):
... | [
"def",
"_validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"self",
".",
"allow_None",
"and",
"val",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"val",
",",
"dt_types",
")",
"and",
"not",
"(",
"self",
".",
"allow_None",
"and",
"val"... | 38.133333 | 24.266667 |
def build_taxonomy(self, level, namespace, predicate, value):
"""
:param level: info, safe, suspicious or malicious
:param namespace: Name of analyzer
:param predicate: Name of service
:param value: value
:return: dict
"""
return {
'level':... | [
"def",
"build_taxonomy",
"(",
"self",
",",
"level",
",",
"namespace",
",",
"predicate",
",",
"value",
")",
":",
"return",
"{",
"'level'",
":",
"level",
",",
"'namespace'",
":",
"namespace",
",",
"'predicate'",
":",
"predicate",
",",
"'value'",
":",
"value"... | 31.642857 | 10.071429 |
async def _watch_docker_events(self):
""" Get raw docker events and convert them to more readable objects, and then give them to self._docker_events_subscriber """
try:
source = AsyncIteratorWrapper(self._docker.sync.event_stream(filters={"event": ["die", "oom"]}))
async for i in... | [
"async",
"def",
"_watch_docker_events",
"(",
"self",
")",
":",
"try",
":",
"source",
"=",
"AsyncIteratorWrapper",
"(",
"self",
".",
"_docker",
".",
"sync",
".",
"event_stream",
"(",
"filters",
"=",
"{",
"\"event\"",
":",
"[",
"\"die\"",
",",
"\"oom\"",
"]"... | 56.388889 | 25.972222 |
def apply_stats(self, statsUpdates):
""" compute stats and update/apply the new stats to the running average
"""
def updateAccumStats():
if self._full_stats_init:
return tf.cond(tf.greater(self.sgd_step, self._cold_iter), lambda: tf.group(*self._apply_stats(statsUpda... | [
"def",
"apply_stats",
"(",
"self",
",",
"statsUpdates",
")",
":",
"def",
"updateAccumStats",
"(",
")",
":",
"if",
"self",
".",
"_full_stats_init",
":",
"return",
"tf",
".",
"cond",
"(",
"tf",
".",
"greater",
"(",
"self",
".",
"sgd_step",
",",
"self",
"... | 51 | 27.685714 |
def authorized_request(self, method, url, **kwargs):
"""Shortcut for requests.request with proper Authorization header.
Note:
If you put auth keyword argument or Authorization in headers
keyword argument, this will raise an exception.
Decide what you want to do!
... | [
"def",
"authorized_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"kwargs",
".",
"pop",
"(",
"'headers'",
",",
"{",
"}",
")",
"if",
"headers",
".",
"get",
"(",
"'Authorization'",
")",
"or",
"kwarg... | 42.8 | 23.5 |
def ingress(self, envelope, http_headers, operation):
"""Overrides the ingress function for response logging.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation instance.
Returns:
A tuple of the enve... | [
"def",
"ingress",
"(",
"self",
",",
"envelope",
",",
"http_headers",
",",
"operation",
")",
":",
"if",
"self",
".",
"_logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"_RESPONSE_XML_LOG_LINE",... | 33.567568 | 18.162162 |
def _fill_from_h2ocluster(self, other):
"""
Update information in this object from another H2OCluster instance.
:param H2OCluster other: source of the new information for this object.
"""
self._props = other._props
self._retrieved_at = other._retrieved_at
other._... | [
"def",
"_fill_from_h2ocluster",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_props",
"=",
"other",
".",
"_props",
"self",
".",
"_retrieved_at",
"=",
"other",
".",
"_retrieved_at",
"other",
".",
"_props",
"=",
"{",
"}",
"other",
".",
"_retrieved_at",... | 35.6 | 15 |
def transform_single(self, data, center, i=0):
""" Compute entries of `data` in hypercube centered at `center`
Parameters
===========
data: array-like
Data to find in entries in cube. Warning: first column must be index column.
center: array-like
Center ... | [
"def",
"transform_single",
"(",
"self",
",",
"data",
",",
"center",
",",
"i",
"=",
"0",
")",
":",
"lowerbounds",
",",
"upperbounds",
"=",
"center",
"-",
"self",
".",
"radius_",
",",
"center",
"+",
"self",
".",
"radius_",
"# Slice the hypercube",
"entries",... | 33.896552 | 24.655172 |
def setup_metrics(self, metric_names, objects, period, count):
"""Sets parameters of specified base metrics for a set of objects. Returns
an array of :py:class:`IPerformanceMetric` describing the metrics
have been affected.
@c Null or empty metric name array means all metrics. ... | [
"def",
"setup_metrics",
"(",
"self",
",",
"metric_names",
",",
"objects",
",",
"period",
",",
"count",
")",
":",
"if",
"not",
"isinstance",
"(",
"metric_names",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"metric_names can only be an instance of type list\... | 46.48 | 22.26 |
def changelist_view(self, request, extra_context=None, *args, **kwargs):
"""
Handle the changelist view, the django view for the model instances
change list/actions page.
"""
extra_context = extra_context or {}
extra_context['EDITOR_MEDIA_PATH'] = settings.MEDIA_PATH
... | [
"def",
"changelist_view",
"(",
"self",
",",
"request",
",",
"extra_context",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"extra_context",
"=",
"extra_context",
"or",
"{",
"}",
"extra_context",
"[",
"'EDITOR_MEDIA_PATH'",
"]",
"=",
"se... | 42.454545 | 20.818182 |
def _workaround_no_stage_specific_variables(project):
"""Make Stage-specific variables global (move them to Project)."""
for (name, var) in project.stage.variables.items():
yield "variable %s" % name
for (name, _list) in project.stage.lists.items():
yield "list %s" % name
project.variabl... | [
"def",
"_workaround_no_stage_specific_variables",
"(",
"project",
")",
":",
"for",
"(",
"name",
",",
"var",
")",
"in",
"project",
".",
"stage",
".",
"variables",
".",
"items",
"(",
")",
":",
"yield",
"\"variable %s\"",
"%",
"name",
"for",
"(",
"name",
",",... | 45.3 | 9.5 |
def spa_length_in_time(**kwds):
"""
Returns the length in time of the template,
based on the masses, PN order, and low-frequency
cut-off.
"""
m1 = kwds['mass1']
m2 = kwds['mass2']
flow = kwds['f_lower']
porder = int(kwds['phase_order'])
# For now, we call the swig-wrapped functi... | [
"def",
"spa_length_in_time",
"(",
"*",
"*",
"kwds",
")",
":",
"m1",
"=",
"kwds",
"[",
"'mass1'",
"]",
"m2",
"=",
"kwds",
"[",
"'mass2'",
"]",
"flow",
"=",
"kwds",
"[",
"'f_lower'",
"]",
"porder",
"=",
"int",
"(",
"kwds",
"[",
"'phase_order'",
"]",
... | 32.6 | 14.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.