text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def set_up_log(filename, verbose=True):
"""Set up log
This method sets up a basic log.
Parameters
----------
filename : str
Log file name
Returns
-------
logging.Logger instance
"""
# Add file extension.
filename += '.log'
if verbose:
print('Preparin... | [
"def",
"set_up_log",
"(",
"filename",
",",
"verbose",
"=",
"True",
")",
":",
"# Add file extension.",
"filename",
"+=",
"'.log'",
"if",
"verbose",
":",
"print",
"(",
"'Preparing log file:'",
",",
"filename",
")",
"# Capture warnings.",
"logging",
".",
"captureWarn... | 20.116279 | 22.023256 |
def del_spreadsheet(self, file_id):
"""Deletes a spreadsheet.
:param file_id: a spreadsheet ID (aka file ID.)
:type file_id: str
"""
url = '{0}/{1}'.format(
DRIVE_FILES_API_V2_URL,
file_id
)
self.request('delete', url) | [
"def",
"del_spreadsheet",
"(",
"self",
",",
"file_id",
")",
":",
"url",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"DRIVE_FILES_API_V2_URL",
",",
"file_id",
")",
"self",
".",
"request",
"(",
"'delete'",
",",
"url",
")"
] | 24.083333 | 15.416667 |
def save_xml(self, doc, element):
'''Save this participant into an xml.dom.Element object.'''
new_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'Participant')
self.target_component.save_xml(doc, new_element)
element.appendChild(new_element) | [
"def",
"save_xml",
"(",
"self",
",",
"doc",
",",
"element",
")",
":",
"new_element",
"=",
"doc",
".",
"createElementNS",
"(",
"RTS_NS",
",",
"RTS_NS_S",
"+",
"'Participant'",
")",
"self",
".",
"target_component",
".",
"save_xml",
"(",
"doc",
",",
"new_elem... | 54.2 | 17 |
def get_setting(self, name):
notfound = object()
"get configuration from 'constance.config' first "
value = getattr(config, name, notfound)
if name.endswith('_WHITELISTED_DOMAINS'):
if value:
return value.split(',')
else:
return []
... | [
"def",
"get_setting",
"(",
"self",
",",
"name",
")",
":",
"notfound",
"=",
"object",
"(",
")",
"value",
"=",
"getattr",
"(",
"config",
",",
"name",
",",
"notfound",
")",
"if",
"name",
".",
"endswith",
"(",
"'_WHITELISTED_DOMAINS'",
")",
":",
"if",
"val... | 34.888889 | 13 |
def features(self):
"""
lazy fetch and cache features
"""
if self._features is None:
metadata = self.metadata()
if "features" in metadata:
self._features = metadata["features"]
else:
self._features = []
return se... | [
"def",
"features",
"(",
"self",
")",
":",
"if",
"self",
".",
"_features",
"is",
"None",
":",
"metadata",
"=",
"self",
".",
"metadata",
"(",
")",
"if",
"\"features\"",
"in",
"metadata",
":",
"self",
".",
"_features",
"=",
"metadata",
"[",
"\"features\"",
... | 29.272727 | 7.818182 |
def parse_token(self, token, tags=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):
""" Returns the arguments for Sentence.append() from a tagged token representation.
The order in which token tags appear can be specified.
The default order is (separated by slashes):
- word,
... | [
"def",
"parse_token",
"(",
"self",
",",
"token",
",",
"tags",
"=",
"[",
"WORD",
",",
"POS",
",",
"CHUNK",
",",
"PNP",
",",
"REL",
",",
"ANCHOR",
",",
"LEMMA",
"]",
")",
":",
"p",
"=",
"{",
"WORD",
":",
"\"\"",
",",
"POS",
":",
"None",
",",
"I... | 46.761194 | 18.641791 |
def _set_mac_address_table(self, v, load=False):
"""
Setter method for mac_address_table, mapped from YANG variable /mac_address_table (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_address_table is considered as a private
method. Backends looking to... | [
"def",
"_set_mac_address_table",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",... | 84.227273 | 39.045455 |
def isModule(self, dotted_name, extrapath=None):
"""Is ``dotted_name`` the name of a module?"""
try:
return self._module_cache[(dotted_name, extrapath)]
except KeyError:
pass
if dotted_name in sys.modules or dotted_name in self.builtin_modules:
return ... | [
"def",
"isModule",
"(",
"self",
",",
"dotted_name",
",",
"extrapath",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_module_cache",
"[",
"(",
"dotted_name",
",",
"extrapath",
")",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"dotted_name",
... | 44.916667 | 16.791667 |
def exchange_code_and_store_config(auth_client, auth_code):
"""
Finishes auth flow after code is gotten from command line or local server.
Exchanges code for tokens and gets user info from auth.
Stores tokens and user info in config.
"""
# do a token exchange with the given code
tkn = auth_c... | [
"def",
"exchange_code_and_store_config",
"(",
"auth_client",
",",
"auth_code",
")",
":",
"# do a token exchange with the given code",
"tkn",
"=",
"auth_client",
".",
"oauth2_exchange_code_for_tokens",
"(",
"auth_code",
")",
"tkn",
"=",
"tkn",
".",
"by_resource_server",
"#... | 39.694444 | 16.805556 |
def rooms_upload(self, rid, file, **kwargs):
"""Post a message with attached file to a dedicated room."""
files = {
'file': (os.path.basename(file), open(file, 'rb'), mimetypes.guess_type(file)[0]),
}
return self.__call_api_post('rooms.upload/' + rid, kwargs=kwargs, use_json=... | [
"def",
"rooms_upload",
"(",
"self",
",",
"rid",
",",
"file",
",",
"*",
"*",
"kwargs",
")",
":",
"files",
"=",
"{",
"'file'",
":",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"file",
")",
",",
"open",
"(",
"file",
",",
"'rb'",
")",
",",
"mimet... | 55.666667 | 29 |
def _bashcomplete(cmd, prog_name, complete_var=None):
"""Internal handler for the bash completion support."""
if complete_var is None:
complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
complete_instr = os.environ.get(complete_var)
if not complete_instr:
return
fr... | [
"def",
"_bashcomplete",
"(",
"cmd",
",",
"prog_name",
",",
"complete_var",
"=",
"None",
")",
":",
"if",
"complete_var",
"is",
"None",
":",
"complete_var",
"=",
"'_%s_COMPLETE'",
"%",
"(",
"prog_name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
"."... | 39.545455 | 18.181818 |
def get_json_response(self, content, **kwargs):
"""Returns a json response object."""
# Don't care to return a django form or view in the response here.
# Remove those from the context.
if isinstance(content, dict):
response_content = {k: deepcopy(v) for k, v in content.item... | [
"def",
"get_json_response",
"(",
"self",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"# Don't care to return a django form or view in the response here.",
"# Remove those from the context.",
"if",
"isinstance",
"(",
"content",
",",
"dict",
")",
":",
"response_conte... | 46.533333 | 21.533333 |
def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in self.errors_by_category.iteritems():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stderr.write('Total errors found: %d\n' % self.error... | [
"def",
"PrintErrorCounts",
"(",
"self",
")",
":",
"for",
"category",
",",
"count",
"in",
"self",
".",
"errors_by_category",
".",
"iteritems",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Category \\'%s\\' errors found: %d\\n'",
"%",
"(",
"category... | 53.666667 | 14.166667 |
def _transition(self, duration, brightness,
hue=None, saturation=None, temperature=None):
""" Transition.
:param duration: Time to transition.
:param brightness: Transition to this brightness.
:param hue: Transition to this hue.
:param saturation: Transition ... | [
"def",
"_transition",
"(",
"self",
",",
"duration",
",",
"brightness",
",",
"hue",
"=",
"None",
",",
"saturation",
"=",
"None",
",",
"temperature",
"=",
"None",
")",
":",
"# Calculate brightness steps.",
"b_steps",
"=",
"0",
"if",
"brightness",
"is",
"not",
... | 44.954545 | 17.19697 |
def pull_file(self, relativePath, pull=None, update=True, ntrials=3):
"""
Pull a file's data from the Repository.
:Parameters:
#. relativePath (string): The relative to the repository path from
where to pull the file.
#. pull (None, string): The pulling me... | [
"def",
"pull_file",
"(",
"self",
",",
"relativePath",
",",
"pull",
"=",
"None",
",",
"update",
"=",
"True",
",",
"ntrials",
"=",
"3",
")",
":",
"assert",
"isinstance",
"(",
"ntrials",
",",
"int",
")",
",",
"\"ntrials must be integer\"",
"assert",
"ntrials"... | 56.64557 | 28.721519 |
def parse_server_addr(str_addr, default_port=26000):
"""Parse address and returns host and port
Args:
str_addr --- string that contains server ip or hostname and optionaly
port
Returns: tuple (host, port)
Examples:
>>> parse_server_addr('127.0.0.1:26006')
('127.0.0.1', 26006)... | [
"def",
"parse_server_addr",
"(",
"str_addr",
",",
"default_port",
"=",
"26000",
")",
":",
"m",
"=",
"ADDR_STR_RE",
".",
"match",
"(",
"str_addr",
")",
"if",
"m",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Bad address string \"{0}\"'",
".",
"format",
"(... | 30 | 20.925 |
def _format_coord(self, x, limits):
"""
Handles display-range-specific formatting for the x and y coords.
Parameters
----------
x : number
The number to be formatted
limits : 2-item sequence
The min and max of the current display limits for the ax... | [
"def",
"_format_coord",
"(",
"self",
",",
"x",
",",
"limits",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"None",
"formatter",
"=",
"self",
".",
"_mplformatter",
"# Trick the formatter into thinking we have an axes",
"# The 7 tick locations is arbitrary but gives ... | 35.380952 | 17.47619 |
def run(self):
"""
consume message from channel on the consuming thread.
"""
LOGGER.debug("rabbitmq.Service.run")
try:
self.channel.start_consuming()
except Exception as e:
LOGGER.warn("rabbitmq.Service.run - Exception raised while consuming") | [
"def",
"run",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"rabbitmq.Service.run\"",
")",
"try",
":",
"self",
".",
"channel",
".",
"start_consuming",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"warn",
"(",
"\"rabbitmq.Service.... | 34.111111 | 14.777778 |
def get_tags(self, rev=None):
"""
Get the tags for the given revision specifier (or the
current revision if not specified).
"""
rev_num = self._get_rev_num(rev)
# rev_num might end with '+', indicating local modifications.
return (
set(self._read_tags_for_rev(rev_num))
if not rev_num.endswith('+')
... | [
"def",
"get_tags",
"(",
"self",
",",
"rev",
"=",
"None",
")",
":",
"rev_num",
"=",
"self",
".",
"_get_rev_num",
"(",
"rev",
")",
"# rev_num might end with '+', indicating local modifications.",
"return",
"(",
"set",
"(",
"self",
".",
"_read_tags_for_rev",
"(",
"... | 27.25 | 13.25 |
def update(self, species_set, generation):
"""
Required interface method. Updates species fitness history information,
checking for ones that have not improved in max_stagnation generations,
and - unless it would result in the number of species dropping below the configured
speci... | [
"def",
"update",
"(",
"self",
",",
"species_set",
",",
"generation",
")",
":",
"species_data",
"=",
"[",
"]",
"for",
"sid",
",",
"s",
"in",
"iteritems",
"(",
"species_set",
".",
"species",
")",
":",
"if",
"s",
".",
"fitness_history",
":",
"prev_fitness",... | 41.8 | 20.88 |
def use_cli(self, config, prefix=None, name="--config", front=True):
"""
Args:
config: Multi-value option, typically tuple from click CLI flag such as --config
prefix (str | unicode | None): Prefix to add to all parsed keys
name (str | unicode): Name of cli flag
... | [
"def",
"use_cli",
"(",
"self",
",",
"config",
",",
"prefix",
"=",
"None",
",",
"name",
"=",
"\"--config\"",
",",
"front",
"=",
"True",
")",
":",
"if",
"config",
":",
"provider",
"=",
"DictProvider",
"(",
"to_dict",
"(",
"config",
",",
"prefix",
"=",
... | 47.545455 | 21.727273 |
def query_to_mdf_records(query=None, dataset_id=None, mdf_acl=None):
"""Evaluate a query and return a list of MDF records
If a datasetID is specified by there is no query, a simple
whole dataset query is formed for the user
"""
if not query and not dataset_id:
raise ValueError("Either query... | [
"def",
"query_to_mdf_records",
"(",
"query",
"=",
"None",
",",
"dataset_id",
"=",
"None",
",",
"mdf_acl",
"=",
"None",
")",
":",
"if",
"not",
"query",
"and",
"not",
"dataset_id",
":",
"raise",
"ValueError",
"(",
"\"Either query or dataset_id must be specified\"",
... | 31.869565 | 22.195652 |
def stats(args):
"""
cldf stats <DATASET>
Print basic stats for CLDF dataset <DATASET>, where <DATASET> may be the path to
- a CLDF metadata file
- a CLDF core data file
"""
ds = _get_dataset(args)
print(ds)
md = Table('key', 'value')
md.extend(ds.properties.items())
print(m... | [
"def",
"stats",
"(",
"args",
")",
":",
"ds",
"=",
"_get_dataset",
"(",
"args",
")",
"print",
"(",
"ds",
")",
"md",
"=",
"Table",
"(",
"'key'",
",",
"'value'",
")",
"md",
".",
"extend",
"(",
"ds",
".",
"properties",
".",
"items",
"(",
")",
")",
... | 28.5 | 15.277778 |
def dump_config(self):
"""
Make clone of current config.
"""
conf = copy_config(self.config, self.mutable_config_keys)
conf['state'] = {
'cookiejar_cookies': list(self.cookies.cookiejar),
}
return conf | [
"def",
"dump_config",
"(",
"self",
")",
":",
"conf",
"=",
"copy_config",
"(",
"self",
".",
"config",
",",
"self",
".",
"mutable_config_keys",
")",
"conf",
"[",
"'state'",
"]",
"=",
"{",
"'cookiejar_cookies'",
":",
"list",
"(",
"self",
".",
"cookies",
"."... | 26.1 | 17.5 |
def jhk_to_bmag(jmag, hmag, kmag):
'''Converts given J, H, Ks mags to a B magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted B band magnitude.
'''
return convert_constants(jmag,hma... | [
"def",
"jhk_to_bmag",
"(",
"jmag",
",",
"hmag",
",",
"kmag",
")",
":",
"return",
"convert_constants",
"(",
"jmag",
",",
"hmag",
",",
"kmag",
",",
"BJHK",
",",
"BJH",
",",
"BJK",
",",
"BHK",
",",
"BJ",
",",
"BH",
",",
"BK",
")"
] | 20.333333 | 22.333333 |
def load(self):
""" Loads in resources needed for this environment, including loading a
new or existing task, establishing directory structures, and
importing plugin modules.
"""
self._setup_directories()
self._load_plugins()
self._setup_task(load=Tru... | [
"def",
"load",
"(",
"self",
")",
":",
"self",
".",
"_setup_directories",
"(",
")",
"self",
".",
"_load_plugins",
"(",
")",
"self",
".",
"_setup_task",
"(",
"load",
"=",
"True",
")",
"self",
".",
"_loaded",
"=",
"True"
] | 34.1 | 13.7 |
def export_translations(request, language):
"""
Export translations view.
"""
FieldTranslation.delete_orphan_translations()
translations = FieldTranslation.objects.filter(lang=language)
for trans in translations:
trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
trans.translation = ... | [
"def",
"export_translations",
"(",
"request",
",",
"language",
")",
":",
"FieldTranslation",
".",
"delete_orphan_translations",
"(",
")",
"translations",
"=",
"FieldTranslation",
".",
"objects",
".",
"filter",
"(",
"lang",
"=",
"language",
")",
"for",
"trans",
"... | 53.555556 | 26.222222 |
def set3d(self,cam):
"""
Configures OpenGL to draw in 3D.
This method also applies the correct rotation and translation as set in the supplied camera ``cam``\ .
It is discouraged to use :py:func:`glTranslatef()` or :py:func:`glRotatef()` directly as this may cause visual glitche... | [
"def",
"set3d",
"(",
"self",
",",
"cam",
")",
":",
"if",
"not",
"isinstance",
"(",
"cam",
",",
"camera",
".",
"Camera",
")",
":",
"raise",
"TypeError",
"(",
"\"cam is not of type Camera!\"",
")",
"# Light",
"#glEnable(GL_LIGHTING)",
"if",
"self",
".",
"cfg",... | 41.823529 | 26.176471 |
def feed_forward_gaussian_fun(action_space, config, observations):
"""Feed-forward Gaussian."""
if not isinstance(action_space, gym.spaces.box.Box):
raise ValueError("Expecting continuous action space.")
mean_weights_initializer = tf.initializers.variance_scaling(
scale=config.init_mean_factor)
logst... | [
"def",
"feed_forward_gaussian_fun",
"(",
"action_space",
",",
"config",
",",
"observations",
")",
":",
"if",
"not",
"isinstance",
"(",
"action_space",
",",
"gym",
".",
"spaces",
".",
"box",
".",
"Box",
")",
":",
"raise",
"ValueError",
"(",
"\"Expecting continu... | 42.736842 | 18.157895 |
def asset(self, asset_id, asset_type, action='GET'):
"""
Gets a asset of a Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset_type:
asset_id:
action:
Returns:
"""
... | [
"def",
"asset",
"(",
"self",
",",
"asset_id",
",",
"asset_type",
",",
"action",
"=",
"'GET'",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]"... | 32.108696 | 23.413043 |
def run(self):
'''Execute a single step and return results. The result for batch mode is the
input, output etc returned as alias, and for interactive mode is the return value
of the last expression. '''
# return value of the last executed statement
self.last_res = None
se... | [
"def",
"run",
"(",
"self",
")",
":",
"# return value of the last executed statement",
"self",
".",
"last_res",
"=",
"None",
"self",
".",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"completed",
"=",
"defaultdict",
"(",
"int",
")",
"#",
"... | 52.415873 | 21.186243 |
def _calc_odds(self):
'''Calculates the absolute probability of all posible rolls.'''
def recur(val, h, dice, combinations):
for pip in dice[0]:
tot = val + pip
if len(dice) > 1:
combinations = recur(tot, h, dice[1:], combinations)
... | [
"def",
"_calc_odds",
"(",
"self",
")",
":",
"def",
"recur",
"(",
"val",
",",
"h",
",",
"dice",
",",
"combinations",
")",
":",
"for",
"pip",
"in",
"dice",
"[",
"0",
"]",
":",
"tot",
"=",
"val",
"+",
"pip",
"if",
"len",
"(",
"dice",
")",
">",
"... | 37.809524 | 16 |
def clear_dcnm_in_part(self, tenant_id, fw_dict, is_fw_virt=False):
"""Clear the DCNM in partition service information.
Clear the In partition service node IP address in DCNM and update the
result.
"""
res = fw_const.DCNM_IN_PART_UPDDEL_SUCCESS
tenant_name = fw_dict.get(... | [
"def",
"clear_dcnm_in_part",
"(",
"self",
",",
"tenant_id",
",",
"fw_dict",
",",
"is_fw_virt",
"=",
"False",
")",
":",
"res",
"=",
"fw_const",
".",
"DCNM_IN_PART_UPDDEL_SUCCESS",
"tenant_name",
"=",
"fw_dict",
".",
"get",
"(",
"'tenant_name'",
")",
"ret",
"=",... | 41.9 | 18.6 |
def write_label_list(path, label_list):
"""
Writes the given `label_list` to an audacity label file.
Args:
path (str): Path to write the file to.
label_list (audiomate.annotations.LabelList): Label list
"""
entries = []
for label in label_list:
entries.append([label.star... | [
"def",
"write_label_list",
"(",
"path",
",",
"label_list",
")",
":",
"entries",
"=",
"[",
"]",
"for",
"label",
"in",
"label_list",
":",
"entries",
".",
"append",
"(",
"[",
"label",
".",
"start",
",",
"label",
".",
"end",
",",
"label",
".",
"value",
"... | 30.923077 | 18.769231 |
def is_highlink_density(self, e):
"""\
checks the density of links within a node,
is there not much text and most of it contains linky shit?
if so it's no good
"""
links = self.parser.getElementsByTag(e, tag='a')
if links is None or len(links) == 0:
re... | [
"def",
"is_highlink_density",
"(",
"self",
",",
"e",
")",
":",
"links",
"=",
"self",
".",
"parser",
".",
"getElementsByTag",
"(",
"e",
",",
"tag",
"=",
"'a'",
")",
"if",
"links",
"is",
"None",
"or",
"len",
"(",
"links",
")",
"==",
"0",
":",
"return... | 32.923077 | 12.961538 |
def get_factory_context(cls):
# type: (type) -> FactoryContext
"""
Retrieves the factory context object associated to a factory. Creates it
if needed
:param cls: The factory class
:return: The factory class context
"""
context = getattr(cls, constants.IPOPO_FACTORY_CONTEXT, None)
i... | [
"def",
"get_factory_context",
"(",
"cls",
")",
":",
"# type: (type) -> FactoryContext",
"context",
"=",
"getattr",
"(",
"cls",
",",
"constants",
".",
"IPOPO_FACTORY_CONTEXT",
",",
"None",
")",
"if",
"context",
"is",
"None",
":",
"# Class not yet manipulated",
"conte... | 31.153846 | 16.384615 |
def close(self, force=False):
"""
close opened file
:param force: force closing of externally opened file or buffer
"""
if self.__write:
self.write = self.__write_adhoc
self.__write = False
if not self._is_buffer or force:
self._file.... | [
"def",
"close",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"__write",
":",
"self",
".",
"write",
"=",
"self",
".",
"__write_adhoc",
"self",
".",
"__write",
"=",
"False",
"if",
"not",
"self",
".",
"_is_buffer",
"or",
"force"... | 26.333333 | 14.5 |
def update_namespace(self, id, namespace):
""" Update namespace
https://www.nomadproject.io/api/namespaces.html
arguments:
- id
- namespace (dict)
returns: requests.Response
raises:
- nomad.api.exceptions.BaseNomadExcepti... | [
"def",
"update_namespace",
"(",
"self",
",",
"id",
",",
"namespace",
")",
":",
"return",
"self",
".",
"request",
"(",
"id",
",",
"json",
"=",
"namespace",
",",
"method",
"=",
"\"post\"",
")"
] | 31.928571 | 16.428571 |
def agent_texts_with_grounding(stmts):
"""Return agent text groundings in a list of statements with their counts
Parameters
----------
stmts: list of :py:class:`indra.statements.Statement`
Returns
-------
list of tuple
List of tuples of the form
(text: str, ((name_space: st... | [
"def",
"agent_texts_with_grounding",
"(",
"stmts",
")",
":",
"allag",
"=",
"all_agents",
"(",
"stmts",
")",
"# Convert PFAM-DEF lists into tuples so that they are hashable and can",
"# be tabulated with a Counter",
"for",
"ag",
"in",
"allag",
":",
"pfam_def",
"=",
"ag",
"... | 39.95082 | 18.04918 |
def add_keyword(self, word, or_operator=False):
""" Adds a given string or list to the current keyword list
:param word: String or list of at least 2 character long keyword(s)
:param or_operator: Boolean. Concatenates all elements of parameter \
word with ``OR``. Is ignored is word is n... | [
"def",
"add_keyword",
"(",
"self",
",",
"word",
",",
"or_operator",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"word",
",",
"str",
"if",
"py3k",
"else",
"basestring",
")",
"and",
"len",
"(",
"word",
")",
">=",
"2",
":",
"self",
".",
"searchterm... | 51.277778 | 23.388889 |
def plot_connectivity_spectrum(a, fs=2, freq_range=(-np.inf, np.inf), diagonal=0, border=False, fig=None):
"""Draw connectivity plots.
Parameters
----------
a : array, shape (n_channels, n_channels, n_fft) or (1 or 3, n_channels, n_channels, n_fft)
If a.ndim == 3, normal plots are created,
... | [
"def",
"plot_connectivity_spectrum",
"(",
"a",
",",
"fs",
"=",
"2",
",",
"freq_range",
"=",
"(",
"-",
"np",
".",
"inf",
",",
"np",
".",
"inf",
")",
",",
"diagonal",
"=",
"0",
",",
"border",
"=",
"False",
",",
"fig",
"=",
"None",
")",
":",
"a",
... | 36.107527 | 23.634409 |
def _diffrsp_app(self,xmlfile=None, **kwargs):
"""
Compute the diffuse response
"""
loglevel = kwargs.get('loglevel', self.loglevel)
self.logger.log(loglevel, 'Computing diffuse repsonce for component %s.',
self.name)
# set the srcmdl
sr... | [
"def",
"_diffrsp_app",
"(",
"self",
",",
"xmlfile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"loglevel",
"=",
"kwargs",
".",
"get",
"(",
"'loglevel'",
",",
"self",
".",
"loglevel",
")",
"self",
".",
"logger",
".",
"log",
"(",
"loglevel",
",",
... | 33.318182 | 16.590909 |
def update(self, ns, docid, raw, **kw):
""" Perform a single update operation.
{'docid': ObjectId('4e95ae3616692111bb000001'),
'ns': u'mydb.tweets',
'raw': {u'h': -5295451122737468990L,
u'ns': u'mydb.tweets',
u'o': {u'$set': {u'con... | [
"def",
"update",
"(",
"self",
",",
"ns",
",",
"docid",
",",
"raw",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_dest_coll",
"(",
"ns",
")",
".",
"update",
"(",
"raw",
"[",
"'o2'",
"]",
",",
"raw",
"[",
"'o'",
"]",
",",
"safe",
"=",
"True",
... | 44.307692 | 14.384615 |
def all(iterable = None, *, name = None, metric = call_default):
"""Measure total time and item count for consuming an iterable
:arg iterable: any iterable
:arg function metric: f(name, count, total_time)
:arg str name: name for the metric
"""
if iterable is None:
return _iter_decorator... | [
"def",
"all",
"(",
"iterable",
"=",
"None",
",",
"*",
",",
"name",
"=",
"None",
",",
"metric",
"=",
"call_default",
")",
":",
"if",
"iterable",
"is",
"None",
":",
"return",
"_iter_decorator",
"(",
"name",
",",
"metric",
")",
"else",
":",
"return",
"_... | 34.636364 | 13.090909 |
def has_textonly_pdf():
"""Does Tesseract have textonly_pdf capability?
Available in v4.00.00alpha since January 2017. Best to
parse the parameter list
"""
args_tess = ['tesseract', '--print-parameters', 'pdf']
params = ''
try:
params = check_output(args_tess, universal_newlines=Tru... | [
"def",
"has_textonly_pdf",
"(",
")",
":",
"args_tess",
"=",
"[",
"'tesseract'",
",",
"'--print-parameters'",
",",
"'pdf'",
"]",
"params",
"=",
"''",
"try",
":",
"params",
"=",
"check_output",
"(",
"args_tess",
",",
"universal_newlines",
"=",
"True",
",",
"st... | 34.375 | 18.75 |
def get_package_dir(nb_path):
"""Return the package directory for a Notebook that has an embeded Metatab doc, *not* for
notebooks that are part of a package """
doc = get_metatab_doc(nb_path)
doc.update_name(force=True, create_term=True)
pkg_name = doc['Root'].get_value('Root.Name')
assert pkg_n... | [
"def",
"get_package_dir",
"(",
"nb_path",
")",
":",
"doc",
"=",
"get_metatab_doc",
"(",
"nb_path",
")",
"doc",
".",
"update_name",
"(",
"force",
"=",
"True",
",",
"create_term",
"=",
"True",
")",
"pkg_name",
"=",
"doc",
"[",
"'Root'",
"]",
".",
"get_valu... | 42.444444 | 13.444444 |
def _makepass(password, hasher='sha256'):
'''
Create a znc compatible hashed password
'''
# Setup the hasher
if hasher == 'sha256':
h = hashlib.sha256(password)
elif hasher == 'md5':
h = hashlib.md5(password)
else:
return NotImplemented
c = "abcdefghijklmnopqrstu... | [
"def",
"_makepass",
"(",
"password",
",",
"hasher",
"=",
"'sha256'",
")",
":",
"# Setup the hasher",
"if",
"hasher",
"==",
"'sha256'",
":",
"h",
"=",
"hashlib",
".",
"sha256",
"(",
"password",
")",
"elif",
"hasher",
"==",
"'md5'",
":",
"h",
"=",
"hashlib... | 23.76 | 19.44 |
def _read_stream_as_string(stream, encoding):
"""Read stream as string
Originally in azure-batch-samples.Python.Batch.common.helpers
:param stream: input stream generator
:param str encoding: The encoding of the file. The default is utf-8.
:return: The file content.
:rtype: str
"""
outp... | [
"def",
"_read_stream_as_string",
"(",
"stream",
",",
"encoding",
")",
":",
"output",
"=",
"io",
".",
"BytesIO",
"(",
")",
"try",
":",
"for",
"data",
"in",
"stream",
":",
"output",
".",
"write",
"(",
"data",
")",
"if",
"encoding",
"is",
"None",
":",
"... | 31.894737 | 16.684211 |
def sphere(target, pore_diameter='pore.diameter'):
r"""
Calculate pore volume from diameter assuming a spherical pore body
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls
the length of the calculated array, and also provide... | [
"def",
"sphere",
"(",
"target",
",",
"pore_diameter",
"=",
"'pore.diameter'",
")",
":",
"diams",
"=",
"target",
"[",
"pore_diameter",
"]",
"value",
"=",
"_pi",
"/",
"6",
"*",
"diams",
"**",
"3",
"return",
"value"
] | 29.444444 | 20.277778 |
def _history_locked(self):
""" Returns whether history movement is locked.
"""
return (self.history_lock and
(self._get_edited_history(self._history_index) !=
self.input_buffer) and
(self._get_prompt_cursor().blockNumber() !=
self... | [
"def",
"_history_locked",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"history_lock",
"and",
"(",
"self",
".",
"_get_edited_history",
"(",
"self",
".",
"_history_index",
")",
"!=",
"self",
".",
"input_buffer",
")",
"and",
"(",
"self",
".",
"_get_pro... | 43.375 | 9.625 |
def get_volume_remove_kwargs(self, action, volume_name, kwargs=None):
"""
Generates keyword arguments for the Docker client to remove a volume.
:param action: Action configuration.
:type action: ActionConfig
:param volume_name: Volume name.
:type volume_name: unicode | s... | [
"def",
"get_volume_remove_kwargs",
"(",
"self",
",",
"action",
",",
"volume_name",
",",
"kwargs",
"=",
"None",
")",
":",
"c_kwargs",
"=",
"dict",
"(",
"name",
"=",
"volume_name",
")",
"update_kwargs",
"(",
"c_kwargs",
",",
"kwargs",
")",
"return",
"c_kwargs"... | 39.3125 | 15.1875 |
def rotate_about(self, p, theta):
"""
Rotate counter-clockwise around a point, by theta degrees.
Positive y goes *up,* as in traditional mathematics.
The new position is returned as a new Point.
"""
result = self.clone()
result.translate(-p.x, -p.y)
resu... | [
"def",
"rotate_about",
"(",
"self",
",",
"p",
",",
"theta",
")",
":",
"result",
"=",
"self",
".",
"clone",
"(",
")",
"result",
".",
"translate",
"(",
"-",
"p",
".",
"x",
",",
"-",
"p",
".",
"y",
")",
"result",
".",
"rotate",
"(",
"theta",
")",
... | 29.307692 | 15.153846 |
def snippet(code, locations, sep=' | ', colmark=('-', '^'), context=5):
'''Given a code and list of locations, convert to snippet lines.
return will include line number, a separator (``sep``), then
line contents.
At most ``context`` lines are shown before each location line.
A... | [
"def",
"snippet",
"(",
"code",
",",
"locations",
",",
"sep",
"=",
"' | '",
",",
"colmark",
"=",
"(",
"'-'",
",",
"'^'",
")",
",",
"context",
"=",
"5",
")",
":",
"if",
"not",
"locations",
":",
"return",
"[",
"]",
"lines",
"=",
"code",
".",
"split"... | 40.129032 | 21.419355 |
def setRepCount(self, count):
"""Sets the repetition *count* for the stimulus model"""
self._rep_default_cache[0] = count
self.ui.trackview.model().setRepCount(count) | [
"def",
"setRepCount",
"(",
"self",
",",
"count",
")",
":",
"self",
".",
"_rep_default_cache",
"[",
"0",
"]",
"=",
"count",
"self",
".",
"ui",
".",
"trackview",
".",
"model",
"(",
")",
".",
"setRepCount",
"(",
"count",
")"
] | 46.75 | 6.25 |
def broadcast(*sinks_):
"""The |broadcast| decorator creates a |push| object that receives a
message by ``yield`` and then sends this message on to all the given sinks.
.. |broadcast| replace:: :py:func:`broadcast`
"""
@push
def bc():
sinks = [s() for s in sinks_]
while True:
... | [
"def",
"broadcast",
"(",
"*",
"sinks_",
")",
":",
"@",
"push",
"def",
"bc",
"(",
")",
":",
"sinks",
"=",
"[",
"s",
"(",
")",
"for",
"s",
"in",
"sinks_",
"]",
"while",
"True",
":",
"msg",
"=",
"yield",
"for",
"s",
"in",
"sinks",
":",
"s",
".",... | 26.533333 | 19.8 |
def load_yaml(self, _yaml: YamlDocument) -> AugmentedDict:
"""
Loads a partial yaml and augments it. A partial yaml in this context is a yaml that is
syntactically correct, but is not yet complete in terms of content.
The yaml will be completed by augmenting with some external resources ... | [
"def",
"load_yaml",
"(",
"self",
",",
"_yaml",
":",
"YamlDocument",
")",
"->",
"AugmentedDict",
":",
"return",
"self",
".",
"augment",
"(",
"self",
".",
"_load_plain_yaml",
"(",
"_yaml",
")",
",",
"document",
"=",
"_yaml",
")"
] | 45.133333 | 28.733333 |
def create_module_graph(module_spec):
"""Creates a graph and loads Hub Module into it.
Args:
module_spec: the hub.ModuleSpec for the image module being used.
Returns:
graph: the tf.Graph that was created.
bottleneck_tensor: the bottleneck values output by the module.
resized_input_tensor: the in... | [
"def",
"create_module_graph",
"(",
"module_spec",
")",
":",
"height",
",",
"width",
"=",
"hub",
".",
"get_expected_image_size",
"(",
"module_spec",
")",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
"as",
"graph",
":",
"resized_input_ten... | 43.857143 | 20.47619 |
def is_parent_of_book(self, id_, book_id):
"""Tests if an ``Id`` is a direct parent of book.
arg: id (osid.id.Id): an ``Id``
arg: book_id (osid.id.Id): the ``Id`` of a book
return: (boolean) - ``true`` if this ``id`` is a parent of
``book_id,`` f ``alse`` otherwise... | [
"def",
"is_parent_of_book",
"(",
"self",
",",
"id_",
",",
"book_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_parent_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_se... | 50.1 | 18.8 |
def calcDistMatchArr(matchArr, tKey, mKey):
"""Calculate the euclidean distance of all array positions in "matchArr".
:param matchArr: a dictionary of ``numpy.arrays`` containing at least two
entries that are treated as cartesian coordinates.
:param tKey: #TODO: docstring
:param mKey: #TODO: do... | [
"def",
"calcDistMatchArr",
"(",
"matchArr",
",",
"tKey",
",",
"mKey",
")",
":",
"#Calculate all sorted list of all eucledian feature distances",
"matchArrSize",
"=",
"listvalues",
"(",
"matchArr",
")",
"[",
"0",
"]",
".",
"size",
"distInfo",
"=",
"{",
"'posPairs'",
... | 37.935484 | 20.580645 |
def scale(arr, mn=0, mx=1):
"""
Apply min-max scaling (normalize)
then scale to (mn,mx)
"""
amn = arr.min()
amx = arr.max()
# normalize:
arr = (arr - amn) / (amx - amn)
# scale:
if amn != mn or amx != mx:
arr *= mx - mn
arr += mn
return arr | [
"def",
"scale",
"(",
"arr",
",",
"mn",
"=",
"0",
",",
"mx",
"=",
"1",
")",
":",
"amn",
"=",
"arr",
".",
"min",
"(",
")",
"amx",
"=",
"arr",
".",
"max",
"(",
")",
"# normalize:",
"arr",
"=",
"(",
"arr",
"-",
"amn",
")",
"/",
"(",
"amx",
"-... | 20.5 | 14.785714 |
def f_supports(self, data):
"""Checks if input data is supported by the parameter."""
dtype = type(data)
if dtype is tuple or dtype is list and len(data) == 0:
return True # ArrayParameter does support empty tuples
elif dtype is np.ndarray and data.size == 0 and data.ndim =... | [
"def",
"f_supports",
"(",
"self",
",",
"data",
")",
":",
"dtype",
"=",
"type",
"(",
"data",
")",
"if",
"dtype",
"is",
"tuple",
"or",
"dtype",
"is",
"list",
"and",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"True",
"# ArrayParameter does suppor... | 52.111111 | 21.333333 |
def get_commit_command(self, message, author=None):
"""Get the command to commit changes to tracked files in the working tree."""
command = ['git']
if author:
command.extend(('-c', 'user.name=%s' % author.name))
command.extend(('-c', 'user.email=%s' % author.email))
... | [
"def",
"get_commit_command",
"(",
"self",
",",
"message",
",",
"author",
"=",
"None",
")",
":",
"command",
"=",
"[",
"'git'",
"]",
"if",
"author",
":",
"command",
".",
"extend",
"(",
"(",
"'-c'",
",",
"'user.name=%s'",
"%",
"author",
".",
"name",
")",
... | 41.818182 | 13.363636 |
def overlay_gateway_map_vlan_vni_mapping_vni(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
... | [
"def",
"overlay_gateway_map_vlan_vni_mapping_vni",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\"",
",",
"xm... | 46.125 | 15.5625 |
def make_handler(robot):
"""
为一个 BaseRoBot 生成 Tornado Handler。
Usage ::
import tornado.ioloop
import tornado.web
from werobot import WeRoBot
from tornado_werobot import make_handler
robot = WeRoBot(token='token')
@robot.handler
def hello(message):... | [
"def",
"make_handler",
"(",
"robot",
")",
":",
"class",
"WeRoBotHandler",
"(",
"RequestHandler",
")",
":",
"def",
"prepare",
"(",
"self",
")",
":",
"timestamp",
"=",
"self",
".",
"get_argument",
"(",
"'timestamp'",
",",
"''",
")",
"nonce",
"=",
"self",
"... | 29.296875 | 17.921875 |
def keypoint_rot90(keypoint, factor, rows, cols, **params):
"""Rotates a keypoint by 90 degrees CCW (see np.rot90)
Args:
keypoint (tuple): A tuple (x, y, angle, scale).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int)... | [
"def",
"keypoint_rot90",
"(",
"keypoint",
",",
"factor",
",",
"rows",
",",
"cols",
",",
"*",
"*",
"params",
")",
":",
"if",
"factor",
"<",
"0",
"or",
"factor",
">",
"3",
":",
"raise",
"ValueError",
"(",
"'Parameter n must be in range [0;3]'",
")",
"x",
"... | 39.105263 | 19.684211 |
def get_all_subscriptions_by_topic(name, region=None, key=None, keyid=None, profile=None):
'''
Get list of all subscriptions to a specific topic.
CLI example to delete a topic::
salt myminion boto_sns.get_all_subscriptions_by_topic mytopic region=us-east-1
'''
cache_key = _subscriptions_ca... | [
"def",
"get_all_subscriptions_by_topic",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"cache_key",
"=",
"_subscriptions_cache_key",
"(",
"name",
")",
"try",
":",
"return... | 39.833333 | 31.055556 |
def split_data(data, squeeze=False):
"""
Split 1D or 2D into two parts, using the last axis
Parameters
----------
data:
squeeze : squeeze results to remove unnecessary dimensions
"""
vdata = np.atleast_2d(data)
nr_freqs = int(vdata.shape[1] / 2)
part1 = vdata[:, 0:nr_freqs]
... | [
"def",
"split_data",
"(",
"data",
",",
"squeeze",
"=",
"False",
")",
":",
"vdata",
"=",
"np",
".",
"atleast_2d",
"(",
"data",
")",
"nr_freqs",
"=",
"int",
"(",
"vdata",
".",
"shape",
"[",
"1",
"]",
"/",
"2",
")",
"part1",
"=",
"vdata",
"[",
":",
... | 25.647059 | 14.705882 |
def submit(self, *items):
"""Return job ids assigned to the submitted items."""
with self.lock:
if self.closed:
raise BrokenPipe('Job submission has been closed.')
id = self.jobcount
self._status += ['SUBMITTED'] * len(items)
self.jobcount += len(items)
for item in items:
self.waitqueue.put((... | [
"def",
"submit",
"(",
"self",
",",
"*",
"items",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"BrokenPipe",
"(",
"'Job submission has been closed.'",
")",
"id",
"=",
"self",
".",
"jobcount",
"self",
".",
"_status... | 27.466667 | 16.2 |
def interface_ip(interface):
"""Determine the IP assigned to us by the given network interface."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(
fcntl.ioctl(
sock.fileno(), 0x8915, struct.pack('256s', interface[:15])
)[20:24]
) | [
"def",
"interface_ip",
"(",
"interface",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"return",
"socket",
".",
"inet_ntoa",
"(",
"fcntl",
".",
"ioctl",
"(",
"sock",
".",
"fileno",
... | 37.375 | 19 |
def get_urls_and_locations(self, urls):
"""Get URLs and their redirection addresses.
:param urls: a list of URL addresses
:returns: an instance of CachedIterable containing given URLs
and valid location header values of their responses
"""
location_generator = self.get_n... | [
"def",
"get_urls_and_locations",
"(",
"self",
",",
"urls",
")",
":",
"location_generator",
"=",
"self",
".",
"get_new_locations",
"(",
"urls",
")",
"initial_cache",
"=",
"list",
"(",
"set",
"(",
"urls",
")",
")",
"return",
"CachedIterable",
"(",
"location_gene... | 43.4 | 13.5 |
def __read_lipd_contents():
"""
Use the file metadata to read in the LiPD file contents as a dataset library
:return dict: Metadata
"""
global files, settings
_d = {}
try:
if len(files[".lpd"]) == 1:
_d = lipd_read(files[".lpd"][0]["full_path"])
if settings["... | [
"def",
"__read_lipd_contents",
"(",
")",
":",
"global",
"files",
",",
"settings",
"_d",
"=",
"{",
"}",
"try",
":",
"if",
"len",
"(",
"files",
"[",
"\".lpd\"",
"]",
")",
"==",
"1",
":",
"_d",
"=",
"lipd_read",
"(",
"files",
"[",
"\".lpd\"",
"]",
"["... | 32.761905 | 17.52381 |
def find_for(self, name):
"""
Get the correct content type for a given name
"""
map = self.items
# first search the overrides (by name)
# then fall back to the defaults (by extension)
# finally, return None if unmatched
return map.get(name, None) or map.get(get_ext(name) or None, None) | [
"def",
"find_for",
"(",
"self",
",",
"name",
")",
":",
"map",
"=",
"self",
".",
"items",
"# first search the overrides (by name)",
"# then fall back to the defaults (by extension)",
"# finally, return None if unmatched",
"return",
"map",
".",
"get",
"(",
"name",
",",
"N... | 32.666667 | 9.333333 |
def _visit_recur(self, item):
"""
Recursively visits children of item.
:param item: object: project, folder or file we will add to upload_items if necessary.
"""
if item.kind == KindType.file_str:
if item.need_to_send:
self.add_upload_item(item.path)
... | [
"def",
"_visit_recur",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
".",
"kind",
"==",
"KindType",
".",
"file_str",
":",
"if",
"item",
".",
"need_to_send",
":",
"self",
".",
"add_upload_item",
"(",
"item",
".",
"path",
")",
"else",
":",
"if",
"i... | 36.125 | 11.125 |
def get_inventory(self, context):
"""
Will locate vm in vcenter and fill its uuid
:type context: cloudshell.shell.core.context.ResourceCommandContext
"""
vcenter_vm_name = context.resource.attributes['vCenter VM']
vcenter_vm_name = vcenter_vm_name.replace('\\', '/')
... | [
"def",
"get_inventory",
"(",
"self",
",",
"context",
")",
":",
"vcenter_vm_name",
"=",
"context",
".",
"resource",
".",
"attributes",
"[",
"'vCenter VM'",
"]",
"vcenter_vm_name",
"=",
"vcenter_vm_name",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"vcenter_... | 42.925 | 28.575 |
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queri... | [
"def",
"_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"_conn",
".",
"status",
"==",
"psycopg2",
".",
"extensions",
".",
"STATUS_BEGIN",
":",
"return",
"self",
".",
"READY",
"return",
"self",
".",
"_conn",
".",
"status"
] | 34.6 | 24.266667 |
def add_resource(self, filename, env_filename):
"""Add a resource to the PEX environment.
:param filename: The source filename to add to the PEX; None to create an empty file at
`env_filename`.
:param env_filename: The destination filename in the PEX. This path
must be a relative path.
"""... | [
"def",
"add_resource",
"(",
"self",
",",
"filename",
",",
"env_filename",
")",
":",
"self",
".",
"_ensure_unfrozen",
"(",
"'Adding a resource'",
")",
"self",
".",
"_copy_or_link",
"(",
"filename",
",",
"env_filename",
",",
"\"resource\"",
")"
] | 41.7 | 18.3 |
def dskv02(handle, dladsc, start, room):
"""
Fetch vertices from a type 2 DSK segment.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskv02_c.html
:param handle: DSK file handle.
:type handle: int
:param dladsc: DLA descriptor.
:type dladsc: spiceypy.utils.support_types.SpiceDLA... | [
"def",
"dskv02",
"(",
"handle",
",",
"dladsc",
",",
"start",
",",
"room",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"start",
"=",
"ctypes",
".",
"c_int",
"(",
"start",
")",
"room",
"=",
"ctypes",
".",
"c_int",
"(",
"room"... | 33.625 | 12.958333 |
def get_async(self, url, name, callback=None, params=None, headers=None):
"""
Asynchronous GET request with the process pool.
"""
if name is None: name = ''
params = params or {}
headers = headers or {}
endpoint = self._build_endpoint_url(url, name)
self._... | [
"def",
"get_async",
"(",
"self",
",",
"url",
",",
"name",
",",
"callback",
"=",
"None",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"''",
"params",
"=",
"params",
"or",
"{",
"}"... | 41.363636 | 11.363636 |
def load(self, path):
"""
Read Python file from 'path', execute it and return object that stores all variables of the
Python code as attributes.
:param path:
:return:
"""
with open(path) as f:
code = f.read()
exec(code, {}, self.__dict__) | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"code",
"=",
"f",
".",
"read",
"(",
")",
"exec",
"(",
"code",
",",
"{",
"}",
",",
"self",
".",
"__dict__",
")"
] | 30.9 | 15.3 |
def driver_name(self):
"""
Returns the name of the driver that provides this tacho motor device.
"""
(self._driver_name, value) = self.get_cached_attr_string(self._driver_name, 'driver_name')
return value | [
"def",
"driver_name",
"(",
"self",
")",
":",
"(",
"self",
".",
"_driver_name",
",",
"value",
")",
"=",
"self",
".",
"get_cached_attr_string",
"(",
"self",
".",
"_driver_name",
",",
"'driver_name'",
")",
"return",
"value"
] | 39.833333 | 22.166667 |
def jobs(self):
"""
schema.jobs provides a view of the job reservation table for the schema
:return: jobs table
"""
if self._jobs is None:
self._jobs = JobTable(self.connection, self.database)
return self._jobs | [
"def",
"jobs",
"(",
"self",
")",
":",
"if",
"self",
".",
"_jobs",
"is",
"None",
":",
"self",
".",
"_jobs",
"=",
"JobTable",
"(",
"self",
".",
"connection",
",",
"self",
".",
"database",
")",
"return",
"self",
".",
"_jobs"
] | 32.875 | 15.875 |
def get(cls, expression):
"""
Retrieve the model instance matching the given expression.
If the number of matching results is not equal to one, then
a ``ValueError`` will be raised.
:param expression: A boolean expression to filter by.
:returns: The matching :py:class:`M... | [
"def",
"get",
"(",
"cls",
",",
"expression",
")",
":",
"executor",
"=",
"Executor",
"(",
"cls",
".",
"__database__",
")",
"result",
"=",
"executor",
".",
"execute",
"(",
"expression",
")",
"if",
"len",
"(",
"result",
")",
"!=",
"1",
":",
"raise",
"Va... | 43.733333 | 16.533333 |
def as_json(self):
"""Return the proxy's properties in JSON format.
:rtype: dict
"""
info = {
'host': self.host,
'port': self.port,
'geo': {
'country': {'code': self._geo.code, 'name': self._geo.name},
'region': {
... | [
"def",
"as_json",
"(",
"self",
")",
":",
"info",
"=",
"{",
"'host'",
":",
"self",
".",
"host",
",",
"'port'",
":",
"self",
".",
"port",
",",
"'geo'",
":",
"{",
"'country'",
":",
"{",
"'code'",
":",
"self",
".",
"_geo",
".",
"code",
",",
"'name'",... | 32.96 | 18.68 |
def remove_opinion_layer(self):
"""
Removes the opinion layer (if exists) of the object (in memory)
"""
if self.opinion_layer is not None:
this_node = self.opinion_layer.get_node()
self.root.remove(this_node)
self.opinion_layer = None
if self.... | [
"def",
"remove_opinion_layer",
"(",
"self",
")",
":",
"if",
"self",
".",
"opinion_layer",
"is",
"not",
"None",
":",
"this_node",
"=",
"self",
".",
"opinion_layer",
".",
"get_node",
"(",
")",
"self",
".",
"root",
".",
"remove",
"(",
"this_node",
")",
"sel... | 34.090909 | 9.909091 |
def status(self, pk=None, detail=False, **kwargs):
"""Print the current job status. This is used to check a running job. You can look up the job with
the same parameters used for a get request.
=====API DOCS=====
Retrieve the current job status.
:param pk: Primary key of the re... | [
"def",
"status",
"(",
"self",
",",
"pk",
"=",
"None",
",",
"detail",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Remove default values (anything where the value is None).",
"self",
".",
"_pop_none",
"(",
"kwargs",
")",
"# Search for the record if pk not give... | 42.904762 | 25.119048 |
def _map(expr, func, rtype=None, resources=None, args=(), **kwargs):
"""
Call func on each element of this sequence.
:param func: lambda, function, :class:`odps.models.Function`,
or str which is the name of :class:`odps.models.Funtion`
:param rtype: if not provided, will be the dtype o... | [
"def",
"_map",
"(",
"expr",
",",
"func",
",",
"rtype",
"=",
"None",
",",
"resources",
"=",
"None",
",",
"args",
"=",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"None",
"if",
"isinstance",
"(",
"func",
",",
"FunctionWrapper",
")",
"... | 34.653846 | 23.192308 |
def com_google_fonts_check_code_pages(ttFont):
"""Check code page character ranges"""
if not hasattr(ttFont['OS/2'], "ulCodePageRange1") or \
not hasattr(ttFont['OS/2'], "ulCodePageRange2") or \
(ttFont['OS/2'].ulCodePageRange1 == 0 and \
ttFont['OS/2'].ulCodePageRange2 == 0):
yield FAIL, ("No ... | [
"def",
"com_google_fonts_check_code_pages",
"(",
"ttFont",
")",
":",
"if",
"not",
"hasattr",
"(",
"ttFont",
"[",
"'OS/2'",
"]",
",",
"\"ulCodePageRange1\"",
")",
"or",
"not",
"hasattr",
"(",
"ttFont",
"[",
"'OS/2'",
"]",
",",
"\"ulCodePageRange2\"",
")",
"or",... | 42.818182 | 16.090909 |
def makeGlyphsBoundingBoxes(self):
"""
Make bounding boxes for all the glyphs, and return a dictionary of
BoundingBox(xMin, xMax, yMin, yMax) namedtuples keyed by glyph names.
The bounding box of empty glyphs (without contours or components) is
set to None.
Float values ... | [
"def",
"makeGlyphsBoundingBoxes",
"(",
"self",
")",
":",
"def",
"getControlPointBounds",
"(",
"glyph",
")",
":",
"pen",
".",
"init",
"(",
")",
"glyph",
".",
"draw",
"(",
"pen",
")",
"return",
"pen",
".",
"bounds",
"glyphBoxes",
"=",
"{",
"}",
"pen",
"=... | 36.551724 | 18.62069 |
def array_2d_from_array_1d(self, padded_array_1d):
""" Map a padded 1D array of values to its original 2D array, trimming all edge values.
Parameters
-----------
padded_array_1d : ndarray
A 1D array of values which were computed using the *PaddedRegularGrid*.
"""
... | [
"def",
"array_2d_from_array_1d",
"(",
"self",
",",
"padded_array_1d",
")",
":",
"padded_array_2d",
"=",
"self",
".",
"map_to_2d_keep_padded",
"(",
"padded_array_1d",
")",
"pad_size_0",
"=",
"self",
".",
"mask",
".",
"shape",
"[",
"0",
"]",
"-",
"self",
".",
... | 50.384615 | 22.230769 |
def model_funcpointers(vk, model):
"""Fill the model with function pointer
model['funcpointers'] = {'pfn_name': 'struct_name'}
"""
model['funcpointers'] = {}
funcs = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'funcpointer']
structs = [x for x in vk['regis... | [
"def",
"model_funcpointers",
"(",
"vk",
",",
"model",
")",
":",
"model",
"[",
"'funcpointers'",
"]",
"=",
"{",
"}",
"funcs",
"=",
"[",
"x",
"for",
"x",
"in",
"vk",
"[",
"'registry'",
"]",
"[",
"'types'",
"]",
"[",
"'type'",
"]",
"if",
"x",
".",
"... | 31 | 15.454545 |
def fire_bundle_event(self, event):
"""
Notifies bundle events listeners of a new event in the calling thread.
:param event: The bundle event
"""
with self.__bnd_lock:
# Copy the list of listeners
listeners = self.__bnd_listeners[:]
# Call'em all... | [
"def",
"fire_bundle_event",
"(",
"self",
",",
"event",
")",
":",
"with",
"self",
".",
"__bnd_lock",
":",
"# Copy the list of listeners",
"listeners",
"=",
"self",
".",
"__bnd_listeners",
"[",
":",
"]",
"# Call'em all",
"for",
"listener",
"in",
"listeners",
":",
... | 31.125 | 15.75 |
def InvokeMethod(self, MethodName, ObjectName, Params=None, **params):
# pylint: disable=invalid-name
"""
Invoke a method on a target instance or on a target class.
The methods that can be invoked are static and non-static methods
defined in a class (also known as *extrinsic* me... | [
"def",
"InvokeMethod",
"(",
"self",
",",
"MethodName",
",",
"ObjectName",
",",
"Params",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"# pylint: disable=invalid-name",
"exc",
"=",
"None",
"result_tuple",
"=",
"None",
"if",
"self",
".",
"_operation_recorders... | 38.12 | 24.424 |
def set_level(self,
level,
console_only=False):
"""
Defines the logging level (from standard logging module) for log messages.
:param level: Level of logging for the file logger.
:param console_only: [Optional] If True then the file logger... | [
"def",
"set_level",
"(",
"self",
",",
"level",
",",
"console_only",
"=",
"False",
")",
":",
"self",
".",
"queue",
".",
"put",
"(",
"dill",
".",
"dumps",
"(",
"SetLevelCommand",
"(",
"level",
"=",
"level",
",",
"console_only",
"=",
"console_only",
")",
... | 48.7 | 22.3 |
def _get_type(self):
"""
Subclasses may override this method.
"""
point = self._point
typ = point.type
bType = None
if point.smooth:
if typ == "curve":
bType = "curve"
elif typ == "line":
nextSegment = self._... | [
"def",
"_get_type",
"(",
"self",
")",
":",
"point",
"=",
"self",
".",
"_point",
"typ",
"=",
"point",
".",
"type",
"bType",
"=",
"None",
"if",
"point",
".",
"smooth",
":",
"if",
"typ",
"==",
"\"curve\"",
":",
"bType",
"=",
"\"curve\"",
"elif",
"typ",
... | 31.826087 | 14.173913 |
def standard_parsing_functions(Block, Tx):
"""
Return the standard parsing functions for a given Block and Tx class.
The return value is expected to be used with the standard_streamer function.
"""
def stream_block(f, block):
assert isinstance(block, Block)
block.stream(f)
def s... | [
"def",
"standard_parsing_functions",
"(",
"Block",
",",
"Tx",
")",
":",
"def",
"stream_block",
"(",
"f",
",",
"block",
")",
":",
"assert",
"isinstance",
"(",
"block",
",",
"Block",
")",
"block",
".",
"stream",
"(",
"f",
")",
"def",
"stream_blockheader",
... | 35.815789 | 18.394737 |
def slow_iter_turns_eval_cmp(qry, oper, start_branch=None, engine=None):
"""Iterate over all turns on which a comparison holds.
This is expensive. It evaluates the query for every turn in history.
"""
def mungeside(side):
if isinstance(side, Query):
return side.iter_turns
e... | [
"def",
"slow_iter_turns_eval_cmp",
"(",
"qry",
",",
"oper",
",",
"start_branch",
"=",
"None",
",",
"engine",
"=",
"None",
")",
":",
"def",
"mungeside",
"(",
"side",
")",
":",
"if",
"isinstance",
"(",
"side",
",",
"Query",
")",
":",
"return",
"side",
".... | 39.517241 | 18.862069 |
def create_checkout_order(self, checkout_id, **params):
"""https://developers.coinbase.com/api/v2#create-a-new-order-for-a-checkout"""
response = self._post('v2', 'checkouts', checkout_id, 'orders', data=params)
return self._make_api_object(response, Order) | [
"def",
"create_checkout_order",
"(",
"self",
",",
"checkout_id",
",",
"*",
"*",
"params",
")",
":",
"response",
"=",
"self",
".",
"_post",
"(",
"'v2'",
",",
"'checkouts'",
",",
"checkout_id",
",",
"'orders'",
",",
"data",
"=",
"params",
")",
"return",
"s... | 69.5 | 18 |
def api(self, name):
'''return special API by package's name'''
assert name, 'name is none'
if flow.__name__ == name:
api = flow.FlowApi()
elif sign.__name__ == name:
api = sign.SignApi()
elif sms.__name__ == name:
api = sms.SmsApi()
e... | [
"def",
"api",
"(",
"self",
",",
"name",
")",
":",
"assert",
"name",
",",
"'name is none'",
"if",
"flow",
".",
"__name__",
"==",
"name",
":",
"api",
"=",
"flow",
".",
"FlowApi",
"(",
")",
"elif",
"sign",
".",
"__name__",
"==",
"name",
":",
"api",
"=... | 28.190476 | 13.047619 |
def zero_break(stack: tuple) -> tuple:
'''Handle Resets in input stack.
Breaks the input stack if a Reset operator (zero) is encountered.
'''
reducer = lambda x, y: tuple() if y == 0 else x + (y,)
return reduce(reducer, stack, tuple()) | [
"def",
"zero_break",
"(",
"stack",
":",
"tuple",
")",
"->",
"tuple",
":",
"reducer",
"=",
"lambda",
"x",
",",
"y",
":",
"tuple",
"(",
")",
"if",
"y",
"==",
"0",
"else",
"x",
"+",
"(",
"y",
",",
")",
"return",
"reduce",
"(",
"reducer",
",",
"sta... | 41.666667 | 14.666667 |
def instance_from_physical_vector(self, physical_vector):
"""
Creates a ModelInstance, which has an attribute and class instance corresponding to every PriorModel \
attributed to this instance.
This method takes as input a physical vector of parameter values, thus omitting the use of pr... | [
"def",
"instance_from_physical_vector",
"(",
"self",
",",
"physical_vector",
")",
":",
"arguments",
"=",
"dict",
"(",
"map",
"(",
"lambda",
"prior_tuple",
",",
"physical_unit",
":",
"(",
"prior_tuple",
".",
"prior",
",",
"physical_unit",
")",
",",
"self",
".",... | 35.73913 | 27.217391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.