text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def table_to_ligolw(table, tablename):
"""Convert a `astropy.table.Table` to a :class:`ligo.lw.table.Table`
"""
from ligo.lw import lsctables
# create new LIGO_LW table
columns = table.columns.keys()
cls = lsctables.TableByName[tablename]
llwcolumns = list(columns)
for col, llwcols in _... | [
"def",
"table_to_ligolw",
"(",
"table",
",",
"tablename",
")",
":",
"from",
"ligo",
".",
"lw",
"import",
"lsctables",
"# create new LIGO_LW table",
"columns",
"=",
"table",
".",
"columns",
".",
"keys",
"(",
")",
"cls",
"=",
"lsctables",
".",
"TableByName",
"... | 31.96 | 0.001215 |
def rot(self, t=0., transposed=False):
"""2D Rotation matrix for non-zero pa or pattern speed
to goto the aligned coordinates
"""
rotmat = np.array(
[[np.cos(self._pa+self._omegab*t),np.sin(self._pa+self._omegab*t)],
[-np.sin(self._pa+self._omegab*t),np.cos(se... | [
"def",
"rot",
"(",
"self",
",",
"t",
"=",
"0.",
",",
"transposed",
"=",
"False",
")",
":",
"rotmat",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"self",
".",
"_pa",
"+",
"self",
".",
"_omegab",
"*",
"t",
")",
",",
"np",
"... | 38.727273 | 0.011468 |
def import_jwks(self, jwks, issuer):
"""
Imports all the keys that are represented in a JWKS
:param jwks: Dictionary representation of a JWKS
:param issuer: Who 'owns' the JWKS
"""
try:
_keys = jwks["keys"]
except KeyError:
raise ValueErro... | [
"def",
"import_jwks",
"(",
"self",
",",
"jwks",
",",
"issuer",
")",
":",
"try",
":",
"_keys",
"=",
"jwks",
"[",
"\"keys\"",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'Not a proper JWKS'",
")",
"else",
":",
"try",
":",
"self",
".",
"i... | 34.944444 | 0.003096 |
def calc_move(self, c):
"""
calculate the amount of damage down using the battle.rules file
WARNING - shitty eval functions - careful with user input.
TODO = max_hit = parser.parse(self.rules['hit_max']).to_pyfunc()
"""
# first get local variables the same as bat... | [
"def",
"calc_move",
"(",
"self",
",",
"c",
")",
":",
"# first get local variables the same as battle.rules file so parser can interpret.",
"AGI",
"=",
"c",
".",
"stats",
"[",
"'AGI'",
"]",
"INT",
"=",
"c",
".",
"stats",
"[",
"'INT'",
"]",
"STR",
"=",
"c",
".",... | 58.632653 | 0.013352 |
def _load_ssh(self, tag):
"""Loads the SSH configuration into the vardict."""
for child in tag:
if child.tag == "server":
self._vardict["server"] = child.attrib
elif child.tag == "codes":
self._load_codes(child, True)
elif child.tag == ... | [
"def",
"_load_ssh",
"(",
"self",
",",
"tag",
")",
":",
"for",
"child",
"in",
"tag",
":",
"if",
"child",
".",
"tag",
"==",
"\"server\"",
":",
"self",
".",
"_vardict",
"[",
"\"server\"",
"]",
"=",
"child",
".",
"attrib",
"elif",
"child",
".",
"tag",
... | 41.909091 | 0.004246 |
def get_intrusion_data(self, Pc=None):
r"""
Obtain the numerical values of the calculated intrusion curve
Returns
-------
A named-tuple containing arrays of applied capillary pressures and
invading phase saturation.
"""
net = self.project.network
... | [
"def",
"get_intrusion_data",
"(",
"self",
",",
"Pc",
"=",
"None",
")",
":",
"net",
"=",
"self",
".",
"project",
".",
"network",
"if",
"Pc",
"is",
"None",
":",
"# Infer list of applied capillary pressures",
"points",
"=",
"np",
".",
"unique",
"(",
"self",
"... | 38.146341 | 0.001247 |
def fetch(self, ui_version=values.unset):
"""
Fetch a ConfigurationInstance
:param unicode ui_version: Pinned UI version
:returns: Fetched ConfigurationInstance
:rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance
"""
params = values.of({'UiVersio... | [
"def",
"fetch",
"(",
"self",
",",
"ui_version",
"=",
"values",
".",
"unset",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"'UiVersion'",
":",
"ui_version",
",",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",... | 28 | 0.003839 |
def broadcast_transaction(hex_tx, blockchain_client):
""" Dispatch a raw transaction to the network.
"""
if isinstance(blockchain_client, BitcoindClient):
bitcoind = blockchain_client.bitcoind
elif isinstance(blockchain_client, AuthServiceProxy):
bitcoind = blockchain_client
else:
... | [
"def",
"broadcast_transaction",
"(",
"hex_tx",
",",
"blockchain_client",
")",
":",
"if",
"isinstance",
"(",
"blockchain_client",
",",
"BitcoindClient",
")",
":",
"bitcoind",
"=",
"blockchain_client",
".",
"bitcoind",
"elif",
"isinstance",
"(",
"blockchain_client",
"... | 35.052632 | 0.001462 |
def _merge_args_opts(args_opts_dict, **kwargs):
"""Merge options with their corresponding arguments.
Iterates over the dictionary holding arguments (keys) and options (values). Merges each
options string with its corresponding argument.
:param dict args_opts_dict: a dictionary of arguments and options... | [
"def",
"_merge_args_opts",
"(",
"args_opts_dict",
",",
"*",
"*",
"kwargs",
")",
":",
"merged",
"=",
"[",
"]",
"if",
"not",
"args_opts_dict",
":",
"return",
"merged",
"for",
"arg",
",",
"opt",
"in",
"args_opts_dict",
".",
"items",
"(",
")",
":",
"if",
"... | 28.6 | 0.00451 |
def snake_case_methods(cls, debug=False):
"""
A class decorator adding snake_case methods
that alias capitalized ROOT methods. cls must subclass
a ROOT class and define the _ROOT class variable.
"""
if not CONVERT_SNAKE_CASE:
return cls
# get the ROOT base class
root_base = cls._... | [
"def",
"snake_case_methods",
"(",
"cls",
",",
"debug",
"=",
"False",
")",
":",
"if",
"not",
"CONVERT_SNAKE_CASE",
":",
"return",
"cls",
"# get the ROOT base class",
"root_base",
"=",
"cls",
".",
"_ROOT",
"members",
"=",
"inspect",
".",
"getmembers",
"(",
"root... | 34.518519 | 0.000522 |
def get_project(self, project_key):
"""Retrieve an existing project
This method retrieves metadata about an existing project
:param project_key: Project identifier, in the form of owner/id
:type project_key: str
:returns: Project definition, with all attributes
:rtype: ... | [
"def",
"get_project",
"(",
"self",
",",
"project_key",
")",
":",
"try",
":",
"owner_id",
",",
"project_id",
"=",
"parse_dataset_key",
"(",
"project_key",
")",
"return",
"self",
".",
"_projects_api",
".",
"get_project",
"(",
"owner_id",
",",
"project_id",
")",
... | 38.821429 | 0.001795 |
def sort(self, sortlist, name='',
limit=0, offset=0, style='Python'):
"""Sort the table and return the result as a reference table.
This method sorts the table. It forms a
`TaQL <../../doc/199.html>`_
command from the given arguments and executes it using the
:func:... | [
"def",
"sort",
"(",
"self",
",",
"sortlist",
",",
"name",
"=",
"''",
",",
"limit",
"=",
"0",
",",
"offset",
"=",
"0",
",",
"style",
"=",
"'Python'",
")",
":",
"command",
"=",
"'select from $1 orderby '",
"+",
"sortlist",
"if",
"limit",
">",
"0",
":",... | 43.297297 | 0.001832 |
def get_matches(self, text, cache=None, conflict_resolver=resolve_using_maximal_coverage):
"""Get the matches of the symbol on given text."""
is_root_node = False
if cache is None:
cache = {}
is_root_node = True
if id(self) in cache:
return cache[id(se... | [
"def",
"get_matches",
"(",
"self",
",",
"text",
",",
"cache",
"=",
"None",
",",
"conflict_resolver",
"=",
"resolve_using_maximal_coverage",
")",
":",
"is_root_node",
"=",
"False",
"if",
"cache",
"is",
"None",
":",
"cache",
"=",
"{",
"}",
"is_root_node",
"=",... | 39.8 | 0.00491 |
def _apply_best_spans_to_primaries(self):
"""
Apply best spans.
Given the best span, interpolate to compute the best smoothed value
at each observation.
"""
self.smooth_result = []
for xi, best_span in enumerate(self._smoothed_best_spans.smooth_result):
... | [
"def",
"_apply_best_spans_to_primaries",
"(",
"self",
")",
":",
"self",
".",
"smooth_result",
"=",
"[",
"]",
"for",
"xi",
",",
"best_span",
"in",
"enumerate",
"(",
"self",
".",
"_smoothed_best_spans",
".",
"smooth_result",
")",
":",
"primary_values",
"=",
"[",... | 42.307692 | 0.007117 |
def AddEventSource(self, event_source):
"""Adds an event source.
Args:
event_source (EventSource): event source.
Raises:
IOError: when the storage file is closed or read-only.
OSError: when the storage file is closed or read-only.
"""
self._RaiseIfNotWritable()
self._AddAttr... | [
"def",
"AddEventSource",
"(",
"self",
",",
"event_source",
")",
":",
"self",
".",
"_RaiseIfNotWritable",
"(",
")",
"self",
".",
"_AddAttributeContainer",
"(",
"self",
".",
"_CONTAINER_TYPE_EVENT_SOURCE",
",",
"event_source",
")"
] | 27.071429 | 0.002551 |
def question_field(self, move_x, move_y):
"""Question a grid by given position."""
field_status = self.info_map[move_y, move_x]
# a questioned or undiscovered field
if field_status != 10 and (field_status == 9 or field_status == 11):
self.info_map[move_y, move_x] = 10 | [
"def",
"question_field",
"(",
"self",
",",
"move_x",
",",
"move_y",
")",
":",
"field_status",
"=",
"self",
".",
"info_map",
"[",
"move_y",
",",
"move_x",
"]",
"# a questioned or undiscovered field",
"if",
"field_status",
"!=",
"10",
"and",
"(",
"field_status",
... | 43.857143 | 0.00639 |
def stop_actor(self, aid):
'''
This method removes one actor from the Host, stoping it and deleting
all its references.
:param str. aid: identifier of the actor you want to stop.
'''
url = '%s://%s/%s' % (self.transport, self.host_url.netloc, aid)
if url != self.... | [
"def",
"stop_actor",
"(",
"self",
",",
"aid",
")",
":",
"url",
"=",
"'%s://%s/%s'",
"%",
"(",
"self",
".",
"transport",
",",
"self",
".",
"host_url",
".",
"netloc",
",",
"aid",
")",
"if",
"url",
"!=",
"self",
".",
"url",
":",
"actor",
"=",
"self",
... | 34.857143 | 0.003992 |
def install(self):
'''
Use pip to install the requirements file.
'''
remote_path = os.path.join(self.venv, 'requirements.txt')
put(self.requirements, remote_path)
run('{pip} install -r {requirements}'.format(
pip=self.pip(), requirements=remote_path)) | [
"def",
"install",
"(",
"self",
")",
":",
"remote_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"venv",
",",
"'requirements.txt'",
")",
"put",
"(",
"self",
".",
"requirements",
",",
"remote_path",
")",
"run",
"(",
"'{pip} install -r {require... | 38 | 0.006431 |
def query(options, collection_name,
num_to_skip, num_to_return, query, field_selector=None):
"""Get a **query** message.
"""
data = struct.pack("<I", options)
data += bson._make_c_string(collection_name)
data += struct.pack("<i", num_to_skip)
data += struct.pack("<i", num_to_return)
... | [
"def",
"query",
"(",
"options",
",",
"collection_name",
",",
"num_to_skip",
",",
"num_to_return",
",",
"query",
",",
"field_selector",
"=",
"None",
")",
":",
"data",
"=",
"struct",
".",
"pack",
"(",
"\"<I\"",
",",
"options",
")",
"data",
"+=",
"bson",
".... | 38.666667 | 0.002105 |
def error(self, interface_id, errorcode, msg):
"""When some error occurs the CCU / Homegear will send it's error message here"""
LOG.debug("RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s" % (
interface_id, int(errorcode), str(msg)))
if self.systemcallback:
... | [
"def",
"error",
"(",
"self",
",",
"interface_id",
",",
"errorcode",
",",
"msg",
")",
":",
"LOG",
".",
"debug",
"(",
"\"RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s\"",
"%",
"(",
"interface_id",
",",
"int",
"(",
"errorcode",
")",
",",
"str",
... | 56.857143 | 0.009901 |
def matrix_check(table):
"""
Check input matrix format.
:param table: input matrix
:type table : dict
:return: bool
"""
try:
if len(table.keys()) == 0:
return False
for i in table.keys():
if table.keys() != table[i].keys() or vector_check(
... | [
"def",
"matrix_check",
"(",
"table",
")",
":",
"try",
":",
"if",
"len",
"(",
"table",
".",
"keys",
"(",
")",
")",
"==",
"0",
":",
"return",
"False",
"for",
"i",
"in",
"table",
".",
"keys",
"(",
")",
":",
"if",
"table",
".",
"keys",
"(",
")",
... | 24.333333 | 0.002198 |
def create_file(self, path, fp, force=False, update=False):
"""Store a new file at `path` in this storage.
The contents of the file descriptor `fp` (opened in 'rb' mode)
will be uploaded to `path` which is the full path at
which to store the file.
To force overwrite of an exist... | [
"def",
"create_file",
"(",
"self",
",",
"path",
",",
"fp",
",",
"force",
"=",
"False",
",",
"update",
"=",
"False",
")",
":",
"if",
"'b'",
"not",
"in",
"fp",
".",
"mode",
":",
"raise",
"ValueError",
"(",
"\"File has to be opened in binary mode.\"",
")",
... | 45.282051 | 0.001663 |
async def set_windows_kms_host(cls, host: typing.Optional[str]):
"""See `get_windows_kms_host`."""
await cls.set_config("windows_kms_host", "" if host is None else host) | [
"async",
"def",
"set_windows_kms_host",
"(",
"cls",
",",
"host",
":",
"typing",
".",
"Optional",
"[",
"str",
"]",
")",
":",
"await",
"cls",
".",
"set_config",
"(",
"\"windows_kms_host\"",
",",
"\"\"",
"if",
"host",
"is",
"None",
"else",
"host",
")"
] | 61 | 0.010811 |
def default_classification_value_maps(classification):
"""Helper to get default value maps from classification.
:param classification: Classification definition.
:type classification: dict
:returns: Dictionary with key = the class key and value = default strings.
:rtype: dict
"""
value_map... | [
"def",
"default_classification_value_maps",
"(",
"classification",
")",
":",
"value_maps",
"=",
"{",
"}",
"for",
"hazard_class",
"in",
"classification",
"[",
"'classes'",
"]",
":",
"value_maps",
"[",
"hazard_class",
"[",
"'key'",
"]",
"]",
"=",
"hazard_class",
"... | 32.066667 | 0.00202 |
def fs_dirty_attachments(self):
""" returns a list of absolute paths to the attachements"""
if exists(self.fs_attachment_container):
return [join(self.fs_attachment_container, attachment)
for attachment in listdir(self.fs_attachment_container)]
else:
r... | [
"def",
"fs_dirty_attachments",
"(",
"self",
")",
":",
"if",
"exists",
"(",
"self",
".",
"fs_attachment_container",
")",
":",
"return",
"[",
"join",
"(",
"self",
".",
"fs_attachment_container",
",",
"attachment",
")",
"for",
"attachment",
"in",
"listdir",
"(",
... | 46 | 0.006098 |
def create(gandi, email, quota, fallback, alias, password):
"""Create a mailbox."""
login, domain = email
options = {}
if not password:
password = click.prompt('password', hide_input=True,
confirmation_prompt=True)
options['password'] = password
if quota ... | [
"def",
"create",
"(",
"gandi",
",",
"email",
",",
"quota",
",",
"fallback",
",",
"alias",
",",
"password",
")",
":",
"login",
",",
"domain",
"=",
"email",
"options",
"=",
"{",
"}",
"if",
"not",
"password",
":",
"password",
"=",
"click",
".",
"prompt"... | 29.705882 | 0.001919 |
def get_model(name, **kwargs):
"""Returns a pre-defined model by name
Parameters
----------
name : str
Name of the model.
pretrained : bool
Whether to load the pretrained weights for model.
classes : int
Number of classes for the output layer.
ctx : Context, default ... | [
"def",
"get_model",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"models",
"=",
"{",
"'resnet18_v1'",
":",
"resnet18_v1",
",",
"'resnet34_v1'",
":",
"resnet34_v1",
",",
"'resnet50_v1'",
":",
"resnet50_v1",
",",
"'resnet101_v1'",
":",
"resnet101_v1",
",",
... | 34.854839 | 0.0009 |
def delete_organization(db, organization):
"""Remove an organization from the registry.
This function removes the given organization from the registry.
Related information such as domains or enrollments are also removed.
It checks first whether the organization is already on the registry.
When it i... | [
"def",
"delete_organization",
"(",
"db",
",",
"organization",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"org",
"=",
"find_organization",
"(",
"session",
",",
"organization",
")",
"if",
"not",
"org",
":",
"raise",
"NotFoundErro... | 35.954545 | 0.001232 |
def find_working_password(self, usernames=None, host_strings=None):
"""
Returns the first working combination of username and password for the current host.
"""
r = self.local_renderer
if host_strings is None:
host_strings = []
if not host_strings:
... | [
"def",
"find_working_password",
"(",
"self",
",",
"usernames",
"=",
"None",
",",
"host_strings",
"=",
"None",
")",
":",
"r",
"=",
"self",
".",
"local_renderer",
"if",
"host_strings",
"is",
"None",
":",
"host_strings",
"=",
"[",
"]",
"if",
"not",
"host_stri... | 39.444444 | 0.004948 |
def calculate_potential(self, t=None,
t_max=100, plot_optimal_t=False, ax=None):
"""Calculates the diffusion potential
Parameters
----------
t : int
power to which the diffusion operator is powered
sets the level of diffusion
... | [
"def",
"calculate_potential",
"(",
"self",
",",
"t",
"=",
"None",
",",
"t_max",
"=",
"100",
",",
"plot_optimal_t",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"if",
"t",
"is",
"None",
":",
"t",
"=",
"self",
".",
"t",
"if",
"self",
".",
"diff_... | 34.823529 | 0.001643 |
def tolist(x):
""" convenience function that takes in a
nested structure of lists and dictionaries
and converts everything to its base objects.
This is useful for dupming a file to yaml.
(a) numpy arrays into python lists
>>> type(tolist(np.asarray(123))) == int
... | [
"def",
"tolist",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"return",
"map",
"(",
"tolist",
",",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"tolist",
"(",
"k",
")",... | 28.558824 | 0.001493 |
def rparents(self, level=-1, intermediate=True):
"""Create a recursive list of children.
Note that the :param:`intermediate` can be used to include every
parents to the returned list, not only the most nested ones.
Parameters:
level (int): The depth level to continue fetchi... | [
"def",
"rparents",
"(",
"self",
",",
"level",
"=",
"-",
"1",
",",
"intermediate",
"=",
"True",
")",
":",
"try",
":",
"return",
"self",
".",
"_rparents",
"[",
"(",
"level",
",",
"intermediate",
")",
"]",
"except",
"KeyError",
":",
"rparents",
"=",
"["... | 33.694444 | 0.004006 |
def progress_bar_wrapper(iterable, **kwargs):
''' Wrapper that applies tqdm progress bar conditional on config settings.
'''
return tqdm(iterable, **kwargs) if (config.get_option('progress_bar')
and not isinstance(iterable, tqdm)) else iterable | [
"def",
"progress_bar_wrapper",
"(",
"iterable",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"tqdm",
"(",
"iterable",
",",
"*",
"*",
"kwargs",
")",
"if",
"(",
"config",
".",
"get_option",
"(",
"'progress_bar'",
")",
"and",
"not",
"isinstance",
"(",
"iter... | 52 | 0.007576 |
def area(self, x=None, y=None, **kwds):
"""
Draw a stacked area plot.
An area plot displays quantitative data visually.
This function wraps the matplotlib area function.
Parameters
----------
x : label or position, optional
Coordinates for the X axis... | [
"def",
"area",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"'area'",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"*",
"*",
"kwds",
")"
] | 29.444444 | 0.000913 |
def EnableNetworkInterfaces(
self, interfaces, logger, dhclient_script=None):
"""Enable the list of network interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path ... | [
"def",
"EnableNetworkInterfaces",
"(",
"self",
",",
"interfaces",
",",
"logger",
",",
"dhclient_script",
"=",
"None",
")",
":",
"helpers",
".",
"CallDhclient",
"(",
"interfaces",
",",
"logger",
",",
"dhclient_script",
"=",
"dhclient_script",
")"
] | 43.5 | 0.002252 |
async def async_set_switch_state(
self, switch_number: SwitchNumber, state: bool) -> None:
"""
Turn a switch on or off.
:param switch_number: the switch to be set.
:param state: True to turn on, False to turn off.
"""
await self._protocol.async_execute(
... | [
"async",
"def",
"async_set_switch_state",
"(",
"self",
",",
"switch_number",
":",
"SwitchNumber",
",",
"state",
":",
"bool",
")",
"->",
"None",
":",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"SetSwitchCommand",
"(",
"switch_number",
",",
"S... | 32.846154 | 0.004556 |
def smart_insert(engine, table, data, minimal_size=5):
"""
An optimized Insert strategy. Guarantee successful and highest insertion
speed. But ATOMIC WRITE IS NOT ENSURED IF THE PROGRAM IS INTERRUPTED.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采... | [
"def",
"smart_insert",
"(",
"engine",
",",
"table",
",",
"data",
",",
"minimal_size",
"=",
"5",
")",
":",
"insert",
"=",
"table",
".",
"insert",
"(",
")",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"# 首先进行尝试bulk insert",
"try",
":",
"engin... | 29.73913 | 0.000708 |
def parse_args():
"""Arg parser.
"""
parser = get_parser()
if len(sys.argv) < 2:
parser.print_help()
logging.warning('Too few arguments!')
parser.exit(1)
# parsing
try:
params = parser.parse_args()
except Exception as exc:
print(exc)
raise ... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"2",
":",
"parser",
".",
"print_help",
"(",
")",
"logging",
".",
"warning",
"(",
"'Too few arguments!'",
")",
"parser",
".",
"e... | 28.87037 | 0.003102 |
def state_destruction(self, model, prop_name, info):
""" Close state editor when state is being destructed """
import rafcon.gui.singleton as gui_singletons
states_editor_ctrl = gui_singletons.main_window_controller.get_controller('states_editor_ctrl')
state_identifier = states_editor_ct... | [
"def",
"state_destruction",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"import",
"rafcon",
".",
"gui",
".",
"singleton",
"as",
"gui_singletons",
"states_editor_ctrl",
"=",
"gui_singletons",
".",
"main_window_controller",
".",
"get_controll... | 69.833333 | 0.007075 |
def singleCalc(self,
m={'Al2O3': 13.01, 'Alpha': 0.6, 'Ba': 188.0, 'Be': 0.85, 'CaO': 8.35, 'Ce': 28.2, 'Co': 45.2,
'Cr': 117.0, 'Cs': 0.83, 'Cu': 53.5, 'Dy': 5.58, 'Er': 2.96, 'Eu': 1.79, 'Fe2O3': 14.47,
'FeO': 5.51, 'Ga': 19.4, 'Gd': 5.24, 'Hf': 3.38, 'Ho... | [
"def",
"singleCalc",
"(",
"self",
",",
"m",
"=",
"{",
"'Al2O3'",
":",
"13.01",
",",
"'Alpha'",
":",
"0.6",
",",
"'Ba'",
":",
"188.0",
",",
"'Be'",
":",
"0.85",
",",
"'CaO'",
":",
"8.35",
",",
"'Ce'",
":",
"28.2",
",",
"'Co'",
":",
"45.2",
",",
... | 37.005059 | 0.00315 |
def lookup(self, mbid, include=()):
"""
Lookup an entity directly from a specified :term:`MBID`\ .
"""
if include:
for included in include:
if included not in self.available_includes:
raise ValueError(
"{0!r} is no... | [
"def",
"lookup",
"(",
"self",
",",
"mbid",
",",
"include",
"=",
"(",
")",
")",
":",
"if",
"include",
":",
"for",
"included",
"in",
"include",
":",
"if",
"included",
"not",
"in",
"self",
".",
"available_includes",
":",
"raise",
"ValueError",
"(",
"\"{0!... | 33.15 | 0.004399 |
def get_property_dict(entity_proto):
"""Convert datastore.Entity to a dict of property name -> datastore.Value.
Args:
entity_proto: datastore.Entity proto message.
Usage:
>>> get_property_dict(entity_proto)
{'foo': {string_value='a'}, 'bar': {integer_value=2}}
Returns:
dict of entity properti... | [
"def",
"get_property_dict",
"(",
"entity_proto",
")",
":",
"return",
"dict",
"(",
"(",
"p",
".",
"key",
",",
"p",
".",
"value",
")",
"for",
"p",
"in",
"entity_proto",
".",
"property",
")"
] | 27.071429 | 0.007653 |
def ConvertSupportedOSToConditions(src_object):
"""Turn supported_os into a condition."""
if src_object.supported_os:
conditions = " OR ".join("os == '%s'" % o for o in src_object.supported_os)
return conditions | [
"def",
"ConvertSupportedOSToConditions",
"(",
"src_object",
")",
":",
"if",
"src_object",
".",
"supported_os",
":",
"conditions",
"=",
"\" OR \"",
".",
"join",
"(",
"\"os == '%s'\"",
"%",
"o",
"for",
"o",
"in",
"src_object",
".",
"supported_os",
")",
"return",
... | 43.8 | 0.013453 |
def decode_aes256_cbc_base64(data, encryption_key):
"""Decrypts base64 encoded AES-256 CBC bytes."""
if not data:
return b''
else:
# LastPass AES-256/CBC/base64 encryted string starts with an "!".
# Next 24 bytes are the base64 encoded IV for the cipher.
# Then comes the "|".... | [
"def",
"decode_aes256_cbc_base64",
"(",
"data",
",",
"encryption_key",
")",
":",
"if",
"not",
"data",
":",
"return",
"b''",
"else",
":",
"# LastPass AES-256/CBC/base64 encryted string starts with an \"!\".",
"# Next 24 bytes are the base64 encoded IV for the cipher.",
"# Then com... | 37.5 | 0.001859 |
def embed_batch(self, batch: List[List[str]]) -> List[numpy.ndarray]:
"""
Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Pa... | [
"def",
"embed_batch",
"(",
"self",
",",
"batch",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"List",
"[",
"numpy",
".",
"ndarray",
"]",
":",
"elmo_embeddings",
"=",
"[",
"]",
"# Batches with only an empty sentence will throw an exception inside Al... | 40.757576 | 0.005084 |
def hashVariant(cls, gaVariant):
"""
Produces an MD5 hash of the ga variant object to distinguish
it from other variants at the same genomic coordinate.
"""
hash_str = gaVariant.reference_bases + \
str(tuple(gaVariant.alternate_bases))
return hashlib.md5(hash_... | [
"def",
"hashVariant",
"(",
"cls",
",",
"gaVariant",
")",
":",
"hash_str",
"=",
"gaVariant",
".",
"reference_bases",
"+",
"str",
"(",
"tuple",
"(",
"gaVariant",
".",
"alternate_bases",
")",
")",
"return",
"hashlib",
".",
"md5",
"(",
"hash_str",
")",
".",
... | 41.125 | 0.005952 |
def revoke_admin_privileges(name, **client_args):
'''
Revoke cluster administration privileges from a user.
name
Name of the user from whom admin privileges will be revoked.
CLI Example:
.. code-block:: bash
salt '*' influxdb.revoke_admin_privileges <name>
'''
client = _c... | [
"def",
"revoke_admin_privileges",
"(",
"name",
",",
"*",
"*",
"client_args",
")",
":",
"client",
"=",
"_client",
"(",
"*",
"*",
"client_args",
")",
"client",
".",
"revoke_admin_privileges",
"(",
"name",
")",
"return",
"True"
] | 22.470588 | 0.002513 |
async def get_user(self, user_id, page_id):
"""
Query a user from the API and return its JSON
"""
access_token = self._access_token(page_id=page_id)
params = {
'fields': 'first_name,last_name,profile_pic,locale,timezone'
',gender',
... | [
"async",
"def",
"get_user",
"(",
"self",
",",
"user_id",
",",
"page_id",
")",
":",
"access_token",
"=",
"self",
".",
"_access_token",
"(",
"page_id",
"=",
"page_id",
")",
"params",
"=",
"{",
"'fields'",
":",
"'first_name,last_name,profile_pic,locale,timezone'",
... | 28.842105 | 0.003534 |
def _initialize_kvstore(kvstore, param_arrays, arg_params, param_names, update_on_kvstore):
"""Initialize kvstore"""
for idx, param_on_devs in enumerate(param_arrays):
name = param_names[idx]
kvstore.init(name, arg_params[name])
if update_on_kvstore:
kvstore.pull(name, param... | [
"def",
"_initialize_kvstore",
"(",
"kvstore",
",",
"param_arrays",
",",
"arg_params",
",",
"param_names",
",",
"update_on_kvstore",
")",
":",
"for",
"idx",
",",
"param_on_devs",
"in",
"enumerate",
"(",
"param_arrays",
")",
":",
"name",
"=",
"param_names",
"[",
... | 42.125 | 0.005814 |
def predict(self, X):
"""
Predictions with the model. Returns posterior means and standard deviations at X.
"""
X = np.atleast_2d(X)
m = np.empty(shape=(0,1))
s = np.empty(shape=(0,1))
for k in range(X.shape[0]):
preds = []
for pred in sel... | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"np",
".",
"atleast_2d",
"(",
"X",
")",
"m",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"(",
"0",
",",
"1",
")",
")",
"s",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"(",
"0",... | 33.933333 | 0.01912 |
def app_add_developers(app_name_or_id, alias=None, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /app-xxxx/addDevelopers API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Apps#API-method:-/app-xxxx%5B/yyyy%5D/addDevelopers
"""
fully_qualified_versio... | [
"def",
"app_add_developers",
"(",
"app_name_or_id",
",",
"alias",
"=",
"None",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"fully_qualified_version",
"=",
"app_name_or_id",
"+",
"(",
"(",
"'/'",
... | 61.125 | 0.008065 |
def replace_discount_promotion_by_id(cls, discount_promotion_id, discount_promotion, **kwargs):
"""Replace DiscountPromotion
Replace all attributes of DiscountPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
... | [
"def",
"replace_discount_promotion_by_id",
"(",
"cls",
",",
"discount_promotion_id",
",",
"discount_promotion",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
... | 53.909091 | 0.006628 |
def GetInput(self):
"""Yield client urns."""
client_list = GetAllClients(token=self.token)
logging.debug("Got %d clients", len(client_list))
for client_group in collection.Batch(client_list, self.client_chunksize):
for fd in aff4.FACTORY.MultiOpen(
client_group,
mode="r",
... | [
"def",
"GetInput",
"(",
"self",
")",
":",
"client_list",
"=",
"GetAllClients",
"(",
"token",
"=",
"self",
".",
"token",
")",
"logging",
".",
"debug",
"(",
"\"Got %d clients\"",
",",
"len",
"(",
"client_list",
")",
")",
"for",
"client_group",
"in",
"collect... | 40.733333 | 0.0096 |
def init(self):
"""Extract some info from chunks"""
for type_, data in self.chunks:
if type_ == "IHDR":
self.hdr = data
elif type_ == "IEND":
self.end = data
if self.hdr:
# grab w, h info
self.width, self.height = struct.unpack("!II", self.hdr[8:16]) | [
"def",
"init",
"(",
"self",
")",
":",
"for",
"type_",
",",
"data",
"in",
"self",
".",
"chunks",
":",
"if",
"type_",
"==",
"\"IHDR\"",
":",
"self",
".",
"hdr",
"=",
"data",
"elif",
"type_",
"==",
"\"IEND\"",
":",
"self",
".",
"end",
"=",
"data",
"... | 24.636364 | 0.046263 |
def cut(img, left, above, right, down):
"""
从图像中复制出一个矩形选区
box = (100, 100, 400, 400)
region = im.crop(box)
矩形选区有一个4元元组定义,分别表示左、上、右、下的坐标。这个库以左上角为坐标原点,
单位是px,所以上诉代码复制了一个 300x300 pixels 的矩形选区
:param img: 加载到内存的图片
:param left: 左
:param above: 上
:param right: 右
:param down: 下
... | [
"def",
"cut",
"(",
"img",
",",
"left",
",",
"above",
",",
"right",
",",
"down",
")",
":",
"box",
"=",
"(",
"left",
",",
"above",
",",
"right",
",",
"down",
")",
"region",
"=",
"img",
".",
"crop",
"(",
"box",
")",
"return",
"region"
] | 21.157895 | 0.002381 |
def mojo_predict_pandas(dataframe, mojo_zip_path, genmodel_jar_path=None, classpath=None, java_options=None, verbose=False):
"""
MOJO scoring function to take a Pandas frame and use MOJO model as zip file to score.
:param dataframe: Pandas frame to score.
:param mojo_zip_path: Path to MOJO zip download... | [
"def",
"mojo_predict_pandas",
"(",
"dataframe",
",",
"mojo_zip_path",
",",
"genmodel_jar_path",
"=",
"None",
",",
"classpath",
"=",
"None",
",",
"java_options",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"tmp_dir",
"=",
"tempfile",
".",
"mkdtemp",
... | 57.793103 | 0.005869 |
def bounds(self):
"""The bounds of the random variable.
Set `self.i=0.95` to return the 95% interval if this is used for setting
bounds on optimizers/etc. where infinite bounds may not be useful.
"""
return [scipy.stats.gamma.interval(self.i, a, loc=0, scale=1.0 / b) for... | [
"def",
"bounds",
"(",
"self",
")",
":",
"return",
"[",
"scipy",
".",
"stats",
".",
"gamma",
".",
"interval",
"(",
"self",
".",
"i",
",",
"a",
",",
"loc",
"=",
"0",
",",
"scale",
"=",
"1.0",
"/",
"b",
")",
"for",
"a",
",",
"b",
"in",
"zip",
... | 49 | 0.014327 |
def zrrange(self, name, offset, limit):
"""
Return a dict mapping key/score in a range of score from zset ``name``
between ``offset`` and ``offset+limit`` sorted in descending order.
.. warning:: This method is SLOW for large offset!
:param string nam... | [
"def",
"zrrange",
"(",
"self",
",",
"name",
",",
"offset",
",",
"limit",
")",
":",
"offset",
"=",
"get_nonnegative_integer",
"(",
"'offset'",
",",
"offset",
")",
"limit",
"=",
"get_positive_integer",
"(",
"'limit'",
",",
"limit",
")",
"return",
"self",
"."... | 41.791667 | 0.008772 |
def get_device_state(self):
"""
returns the full device state
"""
log.debug("getting device state...")
cmd, url = DEVICE_URLS["get_device_state"]
return self._exec(cmd, url) | [
"def",
"get_device_state",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"getting device state...\"",
")",
"cmd",
",",
"url",
"=",
"DEVICE_URLS",
"[",
"\"get_device_state\"",
"]",
"return",
"self",
".",
"_exec",
"(",
"cmd",
",",
"url",
")"
] | 30.714286 | 0.00905 |
def dragData(self, key=None, default=None):
"""
Returns the drag data associated with this data set. This will be
used when the user attempts to drag & drop a data set from the
chart somewhere. If no key is supplied, then the full data dictionary
is returned.
... | [
"def",
"dragData",
"(",
"self",
",",
"key",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"self",
".",
"_dragData",
"return",
"self",
".",
"_dragData",
".",
"get",
"(",
"nativestring",
"(",
"key",
")",
... | 38.0625 | 0.009615 |
def log(self, key, val, step_num):
"""Directly log a scalar value to the event file.
:param string key: a name for the value
:param val: a float
:param step_num: the iteration number at which this value was logged
"""
try:
ph, summ = self.summaries[key]
... | [
"def",
"log",
"(",
"self",
",",
"key",
",",
"val",
",",
"step_num",
")",
":",
"try",
":",
"ph",
",",
"summ",
"=",
"self",
".",
"summaries",
"[",
"key",
"]",
"except",
"KeyError",
":",
"# if we haven't defined a variable for this key, define one",
"with",
"se... | 38.473684 | 0.00267 |
def wrap(msg, indent, indent_first=True):
"""
Helper function that wraps msg to 120-chars page width. All lines (except maybe 1st) will be prefixed with
string {indent}. First line is prefixed only if {indent_first} is True.
:param msg: string to indent
:param indent: string that will be used fo... | [
"def",
"wrap",
"(",
"msg",
",",
"indent",
",",
"indent_first",
"=",
"True",
")",
":",
"wrapper",
".",
"width",
"=",
"120",
"wrapper",
".",
"initial_indent",
"=",
"indent",
"wrapper",
".",
"subsequent_indent",
"=",
"indent",
"msg",
"=",
"wrapper",
".",
"f... | 46.538462 | 0.004862 |
def get_newest_possible_languagetool_version():
"""Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True
"""
java_path = find_executable('java')
if not java_path:
# Just ignore this... | [
"def",
"get_newest_possible_languagetool_version",
"(",
")",
":",
"java_path",
"=",
"find_executable",
"(",
"'java'",
")",
"if",
"not",
"java_path",
":",
"# Just ignore this and assume an old version of Java. It might not be",
"# found because of a PATHEXT-related issue",
"# (https... | 38.864865 | 0.000678 |
def elliconstraint(self, x, cfac=1e8, tough=True, cond=1e6):
"""ellipsoid test objective function with "constraints" """
N = len(x)
f = sum(cond**(np.arange(N)[-1::-1] / (N - 1)) * x**2)
cvals = (x[0] + 1,
x[0] + 1 + 100 * x[1],
x[0] + 1 - 100 * x[1])
... | [
"def",
"elliconstraint",
"(",
"self",
",",
"x",
",",
"cfac",
"=",
"1e8",
",",
"tough",
"=",
"True",
",",
"cond",
"=",
"1e6",
")",
":",
"N",
"=",
"len",
"(",
"x",
")",
"f",
"=",
"sum",
"(",
"cond",
"**",
"(",
"np",
".",
"arange",
"(",
"N",
"... | 39.416667 | 0.004132 |
def get_magnet(self, detailed=True):
"""Returns torrent magnet link, consisting of BTIH (BitTorrent Info Hash) URN
anr optional other information.
:param bool|list|tuple|set detailed:
For boolean - whether additional info (such as trackers) should be included.
For iterab... | [
"def",
"get_magnet",
"(",
"self",
",",
"detailed",
"=",
"True",
")",
":",
"result",
"=",
"'magnet:?xt=urn:btih:'",
"+",
"self",
".",
"info_hash",
"def",
"add_tr",
"(",
")",
":",
"urls",
"=",
"self",
".",
"announce_urls",
"if",
"not",
"urls",
":",
"return... | 28.037736 | 0.002601 |
def _get_all_files(filename_regex,
path,
base_dir,
excluded_paths=None,
excluded_filename_regex=None):
"""Get all files for processing.
This starts iterating from `base_dir` and checks for all files
that look like `filename_regex` ... | [
"def",
"_get_all_files",
"(",
"filename_regex",
",",
"path",
",",
"base_dir",
",",
"excluded_paths",
"=",
"None",
",",
"excluded_filename_regex",
"=",
"None",
")",
":",
"# For windows",
"def",
"replace_backslashes",
"(",
"string",
")",
":",
"return",
"string",
"... | 40.3125 | 0.000505 |
def _remove_whitespace_nodes(self, node, unlink=True):
"""
删除空白无用节点
"""
remove_list = []
for child in node.childNodes:
if child.nodeType == Node.TEXT_NODE and not child.data.strip():
remove_list.append(child)
elif child.hasChildNodes():
... | [
"def",
"_remove_whitespace_nodes",
"(",
"self",
",",
"node",
",",
"unlink",
"=",
"True",
")",
":",
"remove_list",
"=",
"[",
"]",
"for",
"child",
"in",
"node",
".",
"childNodes",
":",
"if",
"child",
".",
"nodeType",
"==",
"Node",
".",
"TEXT_NODE",
"and",
... | 35.428571 | 0.003929 |
def expand_paths(path):
"""When given a path with brackets, expands it to return all permutations
of the path with expanded brackets, similar to ant.
>>> expand_paths('../{a,b}/{c,d}')
['../a/c', '../a/d', '../b/c', '../b/d']
>>> expand_paths('../{a,b}/{a,b}.py')
['../a/a.py', '.... | [
"def",
"expand_paths",
"(",
"path",
")",
":",
"pr",
"=",
"itertools",
".",
"product",
"parts",
"=",
"MAGIC_BRACKETS",
".",
"findall",
"(",
"path",
")",
"if",
"not",
"path",
":",
"return",
"if",
"not",
"parts",
":",
"return",
"[",
"path",
"]",
"permutat... | 33.64 | 0.002312 |
def change_max_svc_check_attempts(self, service, check_attempts):
"""Modify max service check attempt
Format of the line that triggers function call::
CHANGE_MAX_SVC_CHECK_ATTEMPTS;<host_name>;<service_description>;<check_attempts>
:param service: service to edit
:type service:... | [
"def",
"change_max_svc_check_attempts",
"(",
"self",
",",
"service",
",",
"check_attempts",
")",
":",
"service",
".",
"modified_attributes",
"|=",
"DICT_MODATTR",
"[",
"\"MODATTR_MAX_CHECK_ATTEMPTS\"",
"]",
".",
"value",
"service",
".",
"max_check_attempts",
"=",
"che... | 47.352941 | 0.004872 |
def get_vm(self, name, path=""):
"""Get a VirtualMachine object"""
if path:
return self.get_obj([vim.VirtualMachine], name, path=path)
else:
return self.get_obj([vim.VirtualMachine], name) | [
"def",
"get_vm",
"(",
"self",
",",
"name",
",",
"path",
"=",
"\"\"",
")",
":",
"if",
"path",
":",
"return",
"self",
".",
"get_obj",
"(",
"[",
"vim",
".",
"VirtualMachine",
"]",
",",
"name",
",",
"path",
"=",
"path",
")",
"else",
":",
"return",
"s... | 38.5 | 0.008475 |
def CrearRemito(self, tipo_comprobante, punto_emision, tipo_movimiento, categoria_emisor, cuit_titular_mercaderia, cod_dom_origen,
tipo_receptor, categoria_receptor=None, cuit_receptor=None, cuit_depositario=None,
cod_dom_destino=None, cod_rem_redestinar=None, cod_remito=None, es... | [
"def",
"CrearRemito",
"(",
"self",
",",
"tipo_comprobante",
",",
"punto_emision",
",",
"tipo_movimiento",
",",
"categoria_emisor",
",",
"cuit_titular_mercaderia",
",",
"cod_dom_origen",
",",
"tipo_receptor",
",",
"categoria_receptor",
"=",
"None",
",",
"cuit_receptor",
... | 82.571429 | 0.011976 |
def mkstemp(suffix="", prefix=template, dir=None, text=False):
"""User-callable function to create and return a unique temporary
file. The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename.
If 'suffix' is specified, the file name will end w... | [
"def",
"mkstemp",
"(",
"suffix",
"=",
"\"\"",
",",
"prefix",
"=",
"template",
",",
"dir",
"=",
"None",
",",
"text",
"=",
"False",
")",
":",
"if",
"dir",
"is",
"None",
":",
"dir",
"=",
"gettempdir",
"(",
")",
"if",
"text",
":",
"flags",
"=",
"_tex... | 36.914286 | 0.000754 |
def initialize(self):
""" Load the view on first load could also load based on session, group, etc..
"""
if self.__class__.view:
self.view.handler = self
self.view.request = self.request
return
#: Load the View class from the dotted view name... | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"self",
".",
"__class__",
".",
"view",
":",
"self",
".",
"view",
".",
"handler",
"=",
"self",
"self",
".",
"view",
".",
"request",
"=",
"self",
".",
"request",
"return",
"#: Load the View class from the dot... | 31.388889 | 0.010309 |
def list_records_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildRecords for a given Project
"""
data = list_records_for_project_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_records_for_project",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_records_for_project_raw",
"(",
... | 41.142857 | 0.010204 |
def to_wea(self, file_path, hoys=None):
"""Write an wea file from the epw file.
WEA carries radiation values from epw. Gendaymtx uses these values to
generate the sky. For an annual analysis it is identical to using epw2wea.
args:
file_path: Full file path for output file.
... | [
"def",
"to_wea",
"(",
"self",
",",
"file_path",
",",
"hoys",
"=",
"None",
")",
":",
"hoys",
"=",
"hoys",
"or",
"xrange",
"(",
"len",
"(",
"self",
".",
"direct_normal_radiation",
".",
"datetimes",
")",
")",
"if",
"not",
"file_path",
".",
"lower",
"(",
... | 33.675 | 0.002165 |
def _dist_wrapper():
"""Add temporary distribution build files (and then clean up)."""
try:
# Copy select *.rst files to *.txt for build.
for rst_file, txt_file in zip(SDIST_RST_FILES, SDIST_TXT_FILES):
local("cp %s %s" % (rst_file, txt_file))
# Perform action.
yield... | [
"def",
"_dist_wrapper",
"(",
")",
":",
"try",
":",
"# Copy select *.rst files to *.txt for build.",
"for",
"rst_file",
",",
"txt_file",
"in",
"zip",
"(",
"SDIST_RST_FILES",
",",
"SDIST_TXT_FILES",
")",
":",
"local",
"(",
"\"cp %s %s\"",
"%",
"(",
"rst_file",
",",
... | 35 | 0.002141 |
def SendVersion(self):
"""Send our client version."""
m = Message("version", VersionPayload(settings.NODE_PORT, self.remote_nodeid, settings.VERSION_NAME))
self.SendSerializedMessage(m) | [
"def",
"SendVersion",
"(",
"self",
")",
":",
"m",
"=",
"Message",
"(",
"\"version\"",
",",
"VersionPayload",
"(",
"settings",
".",
"NODE_PORT",
",",
"self",
".",
"remote_nodeid",
",",
"settings",
".",
"VERSION_NAME",
")",
")",
"self",
".",
"SendSerializedMes... | 51.5 | 0.014354 |
def tail(conn, stack_name, log_func=_tail_print, sleep_time=5,
include_initial=True):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_events = get_events(conn, stack_nam... | [
"def",
"tail",
"(",
"conn",
",",
"stack_name",
",",
"log_func",
"=",
"_tail_print",
",",
"sleep_time",
"=",
"5",
",",
"include_initial",
"=",
"True",
")",
":",
"# First dump the full list of events in chronological order and keep",
"# track of the events we've seen already"... | 34.4 | 0.001414 |
def handle(self, *args, **options):
"""
Renders the output by piecing together a few methods that do the
dirty work.
"""
# AWS SES connection, which can be re-used for each query needed.
conn = get_boto_ses_connection()
self._print_quota(conn)
self._print_... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"# AWS SES connection, which can be re-used for each query needed.",
"conn",
"=",
"get_boto_ses_connection",
"(",
")",
"self",
".",
"_print_quota",
"(",
"conn",
")",
"self",
".",
... | 36.555556 | 0.005935 |
def mark_backward(output_tensor, used_node_names):
"""Function to propagate backwards in the graph and mark nodes as used.
Traverses recursively through the graph from the end tensor, through the op
that generates the tensor, and then to the input tensors that feed the op.
Nodes encountered are stored in used_... | [
"def",
"mark_backward",
"(",
"output_tensor",
",",
"used_node_names",
")",
":",
"op",
"=",
"output_tensor",
".",
"op",
"if",
"op",
".",
"name",
"in",
"used_node_names",
":",
"return",
"used_node_names",
".",
"add",
"(",
"op",
".",
"name",
")",
"for",
"inpu... | 38.818182 | 0.010286 |
def hardlink(source, link_name):
"""
Create a hardlink in a portable way
The code for Windows support is adapted from:
https://github.com/sunshowers/ntfs/blob/master/ntfsutils/hardlink.py
"""
if sys.version_info < (3,) and platform.system() == 'Windows': # pragma: no cover
import ctype... | [
"def",
"hardlink",
"(",
"source",
",",
"link_name",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
")",
"and",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"# pragma: no cover",
"import",
"ctypes",
"create_hard_link",
"=",
... | 44.966667 | 0.00508 |
def _format_task_uri(fmt, job_metadata, task_metadata):
"""Returns a URI with placeholders replaced by metadata values."""
values = {
'job-id': None,
'task-id': 'task',
'job-name': None,
'user-id': None,
'task-attempt': None
}
for key in values:
values[key] = task_metadata.get... | [
"def",
"_format_task_uri",
"(",
"fmt",
",",
"job_metadata",
",",
"task_metadata",
")",
":",
"values",
"=",
"{",
"'job-id'",
":",
"None",
",",
"'task-id'",
":",
"'task'",
",",
"'job-name'",
":",
"None",
",",
"'user-id'",
":",
"None",
",",
"'task-attempt'",
... | 27.357143 | 0.015152 |
def from_row_wise_lists(self, lol, header_rows=0, transpose=False, names=None):
"""Create column-wise Columns object from a row-wise table (list of lists).
Useful for reading a CSV file."""
#print '-'*10
#super(Columns, self).__init__()
self.clear()
#print(list(self))
... | [
"def",
"from_row_wise_lists",
"(",
"self",
",",
"lol",
",",
"header_rows",
"=",
"0",
",",
"transpose",
"=",
"False",
",",
"names",
"=",
"None",
")",
":",
"#print '-'*10",
"#super(Columns, self).__init__()",
"self",
".",
"clear",
"(",
")",
"#print(list(self))",
... | 36.205128 | 0.012414 |
def _load_arg_defaults(kwargs):
"""Inject default arguments for load functions."""
if current_app:
kwargs.setdefault('cls', current_app.json_decoder)
else:
kwargs.setdefault('cls', JSONDecoder) | [
"def",
"_load_arg_defaults",
"(",
"kwargs",
")",
":",
"if",
"current_app",
":",
"kwargs",
".",
"setdefault",
"(",
"'cls'",
",",
"current_app",
".",
"json_decoder",
")",
"else",
":",
"kwargs",
".",
"setdefault",
"(",
"'cls'",
",",
"JSONDecoder",
")"
] | 36 | 0.004525 |
def ssh_sa_ssh_server_standby_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services")
ssh = ET.SubElement(ssh_sa, "ssh")
server = ET.SubElement(ssh, "serve... | [
"def",
"ssh_sa_ssh_server_standby_enable",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ssh_sa",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ssh-sa\"",
",",
"xmlns",
"=",
"\"urn:broc... | 42 | 0.005825 |
def _get_reference(self):
"""
Sets up references to important components. A reference is typically an
index or a list of indices that point to the corresponding elements
in a flatten array, which is how MuJoCo stores physical simulation data.
"""
super()._get_reference()
... | [
"def",
"_get_reference",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_get_reference",
"(",
")",
"self",
".",
"cube_body_id",
"=",
"self",
".",
"sim",
".",
"model",
".",
"body_name2id",
"(",
"\"cube\"",
")",
"self",
".",
"l_finger_geom_ids",
"=",
"[",... | 46 | 0.007102 |
def can_use_process_cache(self, use_cache):
"""Returns True if the process cache can be used
:param bool use_cache: Override the logic to force non-cached values
:rtype: bool
"""
return (use_cache and
self._active_cache and
self._active_cache[0] ... | [
"def",
"can_use_process_cache",
"(",
"self",
",",
"use_cache",
")",
":",
"return",
"(",
"use_cache",
"and",
"self",
".",
"_active_cache",
"and",
"self",
".",
"_active_cache",
"[",
"0",
"]",
">",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"po... | 34.8 | 0.005602 |
def reshape_1d(df):
"""If parameter is 1D row vector then convert it into 2D matrix."""
shape = df.shape
if len(shape) == 1:
return df.reshape(shape[0], 1)
else:
return df | [
"def",
"reshape_1d",
"(",
"df",
")",
":",
"shape",
"=",
"df",
".",
"shape",
"if",
"len",
"(",
"shape",
")",
"==",
"1",
":",
"return",
"df",
".",
"reshape",
"(",
"shape",
"[",
"0",
"]",
",",
"1",
")",
"else",
":",
"return",
"df"
] | 28.142857 | 0.004926 |
def str2unixtime(ts, fmt='%Y-%m-%d %H:%M:%S'):
"""
将固定格式的字符串转换成对应的时间戳到秒级别
- 使用:
>>> str2unixtime('2016-01-01 01:01:01')
1451581261
:param ts:
:type ts:
:param fmt:
:type fmt:
:return:
:rtype:
"""
t = time.strptime(ts, fmt)
return int(time.mktime(t)) | [
"def",
"str2unixtime",
"(",
"ts",
",",
"fmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
")",
":",
"t",
"=",
"time",
".",
"strptime",
"(",
"ts",
",",
"fmt",
")",
"return",
"int",
"(",
"time",
".",
"mktime",
"(",
"t",
")",
")"
] | 16.388889 | 0.003205 |
def calculate_piece_size(self):
"""
Calculate and add ``piece length`` to ``info`` in :attr:`metainfo`
The piece size is calculated so that there are no more than
:attr:`MAX_PIECES` pieces unless it is larger than
:attr:`MAX_PIECE_SIZE`, in which case there is no limit on the nu... | [
"def",
"calculate_piece_size",
"(",
"self",
")",
":",
"size",
"=",
"self",
".",
"size",
"if",
"not",
"size",
":",
"raise",
"RuntimeError",
"(",
"f'Cannot calculate piece size with no \"path\" specified'",
")",
"else",
":",
"self",
".",
"metainfo",
"[",
"'info'",
... | 41.588235 | 0.006916 |
def info(ctx):
"""
Display status of PIV application.
"""
controller = ctx.obj['controller']
click.echo('PIV version: %d.%d.%d' % controller.version)
# Largest possible number of PIN tries to get back is 15
tries = controller.get_pin_tries()
tries = '15 or more.' if tries == 15 else tri... | [
"def",
"info",
"(",
"ctx",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"click",
".",
"echo",
"(",
"'PIV version: %d.%d.%d'",
"%",
"controller",
".",
"version",
")",
"# Largest possible number of PIN tries to get back is 15",
"tries",
... | 40.253521 | 0.001708 |
def _model_columns(ins):
""" Get columns info
:type ins: sqlalchemy.orm.mapper.Mapper
:rtype: list[SaColumnDoc]
"""
columns = []
for c in ins.column_attrs:
# Skip protected
if c.key.startswith('_'):
continue
# Collect
columns.append(SaColumnDoc(
... | [
"def",
"_model_columns",
"(",
"ins",
")",
":",
"columns",
"=",
"[",
"]",
"for",
"c",
"in",
"ins",
".",
"column_attrs",
":",
"# Skip protected",
"if",
"c",
".",
"key",
".",
"startswith",
"(",
"'_'",
")",
":",
"continue",
"# Collect",
"columns",
".",
"ap... | 25.05 | 0.003846 |
def list_pkgs(*packages, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
External dependencies::
Virtual package resolution requires aptitude. Because this function
uses dpkg, virtual packages will be reported as not installed.
... | [
"def",
"list_pkgs",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"pkgs",
"=",
"{",
"}",
"cmd",
"=",
"'dpkg -l {0}'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"packages",
")",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"... | 25.84375 | 0.001166 |
def fix_e731(self, result):
"""Fix do not assign a lambda expression check."""
(line_index, _, target) = get_index_offset_contents(result,
self.source)
match = LAMBDA_REGEX.search(target)
if match:
end = match.end()
... | [
"def",
"fix_e731",
"(",
"self",
",",
"result",
")",
":",
"(",
"line_index",
",",
"_",
",",
"target",
")",
"=",
"get_index_offset_contents",
"(",
"result",
",",
"self",
".",
"source",
")",
"match",
"=",
"LAMBDA_REGEX",
".",
"search",
"(",
"target",
")",
... | 49.4 | 0.003976 |
def generic_document_type_formatter(view, context, model, name):
"""Return AdminLog.document field wrapped in URL to its list view."""
_document_model = model.get('document').document_type
url = _document_model.get_admin_list_url()
return Markup('<a href="%s">%s</a>' % (url, _document_model.__name__)) | [
"def",
"generic_document_type_formatter",
"(",
"view",
",",
"context",
",",
"model",
",",
"name",
")",
":",
"_document_model",
"=",
"model",
".",
"get",
"(",
"'document'",
")",
".",
"document_type",
"url",
"=",
"_document_model",
".",
"get_admin_list_url",
"(",
... | 62.8 | 0.003145 |
def _try_coerce_result(self, result):
""" reverse of try_coerce_args """
if isinstance(result, np.ndarray):
if result.dtype.kind in ['i', 'f']:
result = result.astype('M8[ns]')
elif isinstance(result, (np.integer, np.float, np.datetime64)):
result = self.... | [
"def",
"_try_coerce_result",
"(",
"self",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"result",
".",
"dtype",
".",
"kind",
"in",
"[",
"'i'",
",",
"'f'",
"]",
":",
"result",
"=",
"result",
"... | 38.368421 | 0.002677 |
def visit_Starred(self, node):
""" Python 3 """
position = (node.value.first_line, node.value.first_col + 1)
r_set_pos(node, *self.operators['*'].find_previous(position))
last = node.value
node.last_line, node.last_col = last.last_line, last.last_col
node.op_pos = [
... | [
"def",
"visit_Starred",
"(",
"self",
",",
"node",
")",
":",
"position",
"=",
"(",
"node",
".",
"value",
".",
"first_line",
",",
"node",
".",
"value",
".",
"first_col",
"+",
"1",
")",
"r_set_pos",
"(",
"node",
",",
"*",
"self",
".",
"operators",
"[",
... | 41.777778 | 0.005208 |
def set_section( self, section_name ):
"""set current section during parsing"""
if not self.sections.has_key( section_name ):
section = DocSection( section_name )
self.sections[section_name] = section
self.section = section
else:
se... | [
"def",
"set_section",
"(",
"self",
",",
"section_name",
")",
":",
"if",
"not",
"self",
".",
"sections",
".",
"has_key",
"(",
"section_name",
")",
":",
"section",
"=",
"DocSection",
"(",
"section_name",
")",
"self",
".",
"sections",
"[",
"section_name",
"]"... | 44.125 | 0.030556 |
def show_network(self):
"""!
@brief Shows structure of the network: neurons and connections between them.
"""
dimension = len(self.__location[0])
if (dimension != 3) and (dimension != 2):
raise NameError('Network that is located in different ... | [
"def",
"show_network",
"(",
"self",
")",
":",
"dimension",
"=",
"len",
"(",
"self",
".",
"__location",
"[",
"0",
"]",
")",
"if",
"(",
"dimension",
"!=",
"3",
")",
"and",
"(",
"dimension",
"!=",
"2",
")",
":",
"raise",
"NameError",
"(",
"'Network that... | 53.392857 | 0.015112 |
def plot_spectra_pages_pdf(ss, pdf_filename='pages.pdf', setup=_default_setup):
"""
Plots spectra into a PDF file, one spectrum per page.
Splits into several pieces of width
Args:
ss: list of Spectrum objects
pdf_filename: name of output file
"""
logger = a99.get_python_logger()
... | [
"def",
"plot_spectra_pages_pdf",
"(",
"ss",
",",
"pdf_filename",
"=",
"'pages.pdf'",
",",
"setup",
"=",
"_default_setup",
")",
":",
"logger",
"=",
"a99",
".",
"get_python_logger",
"(",
")",
"xmin",
",",
"xmax",
",",
"ymin_",
",",
"ymax",
",",
"xspan",
",",... | 38.558824 | 0.002232 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.