text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def vdp_uplink_proc(self):
"""Periodic handler to detect the uplink interface to the switch.
-> restart_uplink_called: should be called by agent initially to set
the stored uplink and veth from DB
-> process_uplink_ongoing: Will be set when uplink message is enqueue
and reset wh... | [
"def",
"vdp_uplink_proc",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"\"In Periodic Uplink Task\"",
")",
"if",
"not",
"self",
".",
"is_os_run",
":",
"if",
"not",
"self",
".",
"is_openstack_running",
"(",
")",
":",
"LOG",
".",
"info",
"(",
"\"OpenStack... | 49.141667 | 0.000332 |
def _generate_id_maps(self, unique_stmts, poolsize=None,
size_cutoff=100, split_idx=None):
"""Connect statements using their refinement relationships."""
# Check arguments relating to multiprocessing
if poolsize is None:
logger.debug('combine_related: poolsi... | [
"def",
"_generate_id_maps",
"(",
"self",
",",
"unique_stmts",
",",
"poolsize",
"=",
"None",
",",
"size_cutoff",
"=",
"100",
",",
"split_idx",
"=",
"None",
")",
":",
"# Check arguments relating to multiprocessing",
"if",
"poolsize",
"is",
"None",
":",
"logger",
"... | 44.282828 | 0.000669 |
def add(self, campaign_id, item_id, default_price, title, img_url, nick=None):
'''xxxxx.xxxxx.adgroup.add
===================================
创建一个推广组'''
request = TOPRequest('xxxxx.xxxxx.adgroup.add')
request['campaign_id'] = campaign_id
request['item_id'] = item_id
... | [
"def",
"add",
"(",
"self",
",",
"campaign_id",
",",
"item_id",
",",
"default_price",
",",
"title",
",",
"img_url",
",",
"nick",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'xxxxx.xxxxx.adgroup.add'",
")",
"request",
"[",
"'campaign_id'",
"]",
... | 48.769231 | 0.017028 |
def is_required(action):
'''
_actions possessing the `required` flag and not implicitly optional
through `nargs` being '*' or '?'
'''
return not isinstance(action, _SubParsersAction) and (
action.required == True and action.nargs not in ['*', '?']) | [
"def",
"is_required",
"(",
"action",
")",
":",
"return",
"not",
"isinstance",
"(",
"action",
",",
"_SubParsersAction",
")",
"and",
"(",
"action",
".",
"required",
"==",
"True",
"and",
"action",
".",
"nargs",
"not",
"in",
"[",
"'*'",
",",
"'?'",
"]",
")... | 38.857143 | 0.010791 |
def _missing_(cls, value):
"""Lookup function used when value is not found."""
if not (isinstance(value, int) and 0 <= value <= 65535):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
if 0 <= value <= 64:
extend_enum(cls, 'Unassigned [%d]' % value, value)... | [
"def",
"_missing_",
"(",
"cls",
",",
"value",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"value",
",",
"int",
")",
"and",
"0",
"<=",
"value",
"<=",
"65535",
")",
":",
"raise",
"ValueError",
"(",
"'%r is not a valid %s'",
"%",
"(",
"value",
",",
"... | 41.42963 | 0.000524 |
def get_referenced_object(self):
"""
:rtype: core.BunqModel
:raise: BunqException
"""
if self._BunqMeFundraiserResult is not None:
return self._BunqMeFundraiserResult
if self._BunqMeTab is not None:
return self._BunqMeTab
if self._BunqMe... | [
"def",
"get_referenced_object",
"(",
"self",
")",
":",
"if",
"self",
".",
"_BunqMeFundraiserResult",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_BunqMeFundraiserResult",
"if",
"self",
".",
"_BunqMeTab",
"is",
"not",
"None",
":",
"return",
"self",
".",
... | 28.369863 | 0.000933 |
def bills(self, member_id, type='introduced'):
"Same as BillsClient.by_member"
path = "members/{0}/bills/{1}.json".format(member_id, type)
return self.fetch(path) | [
"def",
"bills",
"(",
"self",
",",
"member_id",
",",
"type",
"=",
"'introduced'",
")",
":",
"path",
"=",
"\"members/{0}/bills/{1}.json\"",
".",
"format",
"(",
"member_id",
",",
"type",
")",
"return",
"self",
".",
"fetch",
"(",
"path",
")"
] | 45.75 | 0.010753 |
def _handle_adapter(self, app):
"""
Handle storage _adapter configuration
:param app: Flask application
"""
if 'IMAGINE_ADAPTER' in app.config \
and 'name' in app.config['IMAGINE_ADAPTER'] \
and app.config['IMAGINE_ADAPTER']['name'] in self._adapte... | [
"def",
"_handle_adapter",
"(",
"self",
",",
"app",
")",
":",
"if",
"'IMAGINE_ADAPTER'",
"in",
"app",
".",
"config",
"and",
"'name'",
"in",
"app",
".",
"config",
"[",
"'IMAGINE_ADAPTER'",
"]",
"and",
"app",
".",
"config",
"[",
"'IMAGINE_ADAPTER'",
"]",
"[",... | 43.615385 | 0.008636 |
def dispatch_job(self, link, key, job_archive, stream=sys.stdout):
"""Function to dispatch a single job
Parameters
----------
link : `Link`
Link object that sendes the job
key : str
Key used to identify this particular job
job_archive : `JobArc... | [
"def",
"dispatch_job",
"(",
"self",
",",
"link",
",",
"key",
",",
"job_archive",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"try",
":",
"job_details",
"=",
"link",
".",
"jobs",
"[",
"key",
"]",
"except",
"KeyError",
":",
"print",
"(",
"key",... | 28.787879 | 0.002037 |
def state_preorder_put_account_payment_info( nameop, account_addr, token_type, amount ):
"""
Call this in a @state_create-decorated method.
Identifies the account that must be debited.
"""
assert amount is None or isinstance(amount, (int,long)), 'Amount is {} (type {})'.format(amount, type(amount))
... | [
"def",
"state_preorder_put_account_payment_info",
"(",
"nameop",
",",
"account_addr",
",",
"token_type",
",",
"amount",
")",
":",
"assert",
"amount",
"is",
"None",
"or",
"isinstance",
"(",
"amount",
",",
"(",
"int",
",",
"long",
")",
")",
",",
"'Amount is {} (... | 55.461538 | 0.010914 |
def read_cumulative_iss_index():
"Read in the whole cumulative index and return dataframe."
indexdir = get_index_dir()
path = indexdir / "COISS_2999_index.hdf"
try:
df = pd.read_hdf(path, "df")
except FileNotFoundError:
path = indexdir / "cumindex.hdf"
df = pd.read_hdf(path,... | [
"def",
"read_cumulative_iss_index",
"(",
")",
":",
"indexdir",
"=",
"get_index_dir",
"(",
")",
"path",
"=",
"indexdir",
"/",
"\"COISS_2999_index.hdf\"",
"try",
":",
"df",
"=",
"pd",
".",
"read_hdf",
"(",
"path",
",",
"\"df\"",
")",
"except",
"FileNotFoundError... | 34.307692 | 0.002183 |
def unpack_data(self, usnap=.2): # 2/10th second sleep between empty requests
""" Iterates over socket response and unpacks values of object attributes.
Sleeping here has the greatest response to cpu cycles short of blocking sockets
"""
for new_data in self.socket:
if new_da... | [
"def",
"unpack_data",
"(",
"self",
",",
"usnap",
"=",
".2",
")",
":",
"# 2/10th second sleep between empty requests",
"for",
"new_data",
"in",
"self",
".",
"socket",
":",
"if",
"new_data",
":",
"self",
".",
"data_stream",
".",
"unpack",
"(",
"new_data",
")",
... | 45.777778 | 0.009524 |
def max_event_offset(event_list):
"""Find the offset (end-time) of last event
Parameters
----------
event_list : list or dcase_util.containers.MetaDataContainer
A list containing event dicts
Returns
-------
float > 0
maximum offset
"""
if isinstance(event_list, dc... | [
"def",
"max_event_offset",
"(",
"event_list",
")",
":",
"if",
"isinstance",
"(",
"event_list",
",",
"dcase_util",
".",
"containers",
".",
"MetaDataContainer",
")",
":",
"return",
"event_list",
".",
"max_offset",
"else",
":",
"max_offset",
"=",
"0",
"for",
"eve... | 24.866667 | 0.00129 |
def convert_value(self, v):
""" convert the expression that is in the term to something that is
accepted by pytables """
def stringify(value):
if self.encoding is not None:
encoder = partial(pprint_thing_encoded,
encoding=self.encodi... | [
"def",
"convert_value",
"(",
"self",
",",
"v",
")",
":",
"def",
"stringify",
"(",
"value",
")",
":",
"if",
"self",
".",
"encoding",
"is",
"not",
"None",
":",
"encoder",
"=",
"partial",
"(",
"pprint_thing_encoded",
",",
"encoding",
"=",
"self",
".",
"en... | 39.703704 | 0.00091 |
def __create_map(self, map_size):
'''
Create map.
References:
- https://qiita.com/kusano_t/items/487eec15d42aace7d685
'''
import random
import numpy as np
from itertools import product
news = ['n', 'e', 'w', 's']
m, n = map_s... | [
"def",
"__create_map",
"(",
"self",
",",
"map_size",
")",
":",
"import",
"random",
"import",
"numpy",
"as",
"np",
"from",
"itertools",
"import",
"product",
"news",
"=",
"[",
"'n'",
",",
"'e'",
",",
"'w'",
",",
"'s'",
"]",
"m",
",",
"n",
"=",
"map_siz... | 27.828125 | 0.002169 |
async def get_version(self, tp, params):
"""
Loads version from the stream / version database
# TODO: instance vs. tp.
:param tp:
:param params:
:return:
"""
tw = TypeWrapper(tp, params)
if not tw.is_versioned():
# self.registry.set_tr... | [
"async",
"def",
"get_version",
"(",
"self",
",",
"tp",
",",
"params",
")",
":",
"tw",
"=",
"TypeWrapper",
"(",
"tp",
",",
"params",
")",
"if",
"not",
"tw",
".",
"is_versioned",
"(",
")",
":",
"# self.registry.set_tr()",
"return",
"TypeWrapper",
".",
"ELE... | 30.807692 | 0.002421 |
def update_metadata(self, dataset_identifier, update_fields, content_type="json"):
'''
Update the metadata for a particular dataset.
update_fields is a dictionary containing [metadata key:new value] pairs.
This method performs a full replace for the key:value pairs listed in `update... | [
"def",
"update_metadata",
"(",
"self",
",",
"dataset_identifier",
",",
"update_fields",
",",
"content_type",
"=",
"\"json\"",
")",
":",
"resource",
"=",
"_format_old_api_request",
"(",
"dataid",
"=",
"dataset_identifier",
",",
"content_type",
"=",
"content_type",
")... | 56.3 | 0.01049 |
def user_getinfo(self, fields, access_token=None):
"""
Request multiple fields of information about the user.
:param fields: The names of the fields requested.
:type fields: list
:returns: The values of the current user for the fields requested.
The keys are the fiel... | [
"def",
"user_getinfo",
"(",
"self",
",",
"fields",
",",
"access_token",
"=",
"None",
")",
":",
"if",
"g",
".",
"oidc_id_token",
"is",
"None",
"and",
"access_token",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'User was not authenticated'",
")",
"info",
"=... | 42.694444 | 0.001272 |
def return_hdr(self):
"""
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
list of all the channels
n_samples : int
... | [
"def",
"return_hdr",
"(",
"self",
")",
":",
"self",
".",
"fdtfile",
"=",
"None",
"try",
":",
"self",
".",
"EEG",
"=",
"loadmat",
"(",
"str",
"(",
"self",
".",
"filename",
")",
",",
"struct_as_record",
"=",
"False",
",",
"squeeze_me",
"=",
"True",
")"... | 35.064935 | 0.001801 |
def FindPosition(node, addition, index=0):
'''
Method to search for children according to their position in list. Similar functionality to above method,
except this is for adding items to the tree according to the nodes limits on children or types of children they can have
:param node: current node bein... | [
"def",
"FindPosition",
"(",
"node",
",",
"addition",
",",
"index",
"=",
"0",
")",
":",
"if",
"node",
"is",
"None",
":",
"return",
"None",
"if",
"type",
"(",
"addition",
")",
"in",
"node",
".",
"rules",
":",
"if",
"len",
"(",
"node",
".",
"children"... | 34.16 | 0.001707 |
def A(g,i):
"""recursively constructs A line for g; i = len(g)-1"""
g1 = g&(2**i)
if i:
n = Awidth(i)
An = A(g,i-1)
if g1:
return An<<n | An
else:
return int('1'*n,2)<<n | An
else:
if g1:
return int('00',2)
else:
... | [
"def",
"A",
"(",
"g",
",",
"i",
")",
":",
"g1",
"=",
"g",
"&",
"(",
"2",
"**",
"i",
")",
"if",
"i",
":",
"n",
"=",
"Awidth",
"(",
"i",
")",
"An",
"=",
"A",
"(",
"g",
",",
"i",
"-",
"1",
")",
"if",
"g1",
":",
"return",
"An",
"<<",
"n... | 21.933333 | 0.026239 |
def get_states(self, merge_multi_context=True):
"""Gets states from all devices.
Parameters
----------
merge_multi_context : bool
Default is `True`. In the case when data-parallelism is used, the states
will be collected from multiple devices. A `True` value indi... | [
"def",
"get_states",
"(",
"self",
",",
"merge_multi_context",
"=",
"True",
")",
":",
"assert",
"self",
".",
"binded",
"and",
"self",
".",
"params_initialized",
"return",
"self",
".",
"_curr_module",
".",
"get_states",
"(",
"merge_multi_context",
"=",
"merge_mult... | 43.75 | 0.008949 |
def make_db_data_fetcher(postgresql_conn_info, template_path, reload_templates,
query_cfg, io_pool):
"""
Returns an object which is callable with the zoom and unpadded bounds and
which returns a list of rows.
"""
sources = parse_source_data(query_cfg)
queries_generator ... | [
"def",
"make_db_data_fetcher",
"(",
"postgresql_conn_info",
",",
"template_path",
",",
"reload_templates",
",",
"query_cfg",
",",
"io_pool",
")",
":",
"sources",
"=",
"parse_source_data",
"(",
"query_cfg",
")",
"queries_generator",
"=",
"make_queries_generator",
"(",
... | 38.833333 | 0.002096 |
def get_subject_guide_for_section_params(
year, quarter, curriculum_abbr, course_number, section_id=None):
"""
Returns a SubjectGuide model for the passed section params:
year: year for the section term (4-digits)
quarter: quarter (AUT, WIN, SPR, or SUM)
curriculum_abbr: curriculum abbrevia... | [
"def",
"get_subject_guide_for_section_params",
"(",
"year",
",",
"quarter",
",",
"curriculum_abbr",
",",
"course_number",
",",
"section_id",
"=",
"None",
")",
":",
"quarter",
"=",
"quarter",
".",
"upper",
"(",
")",
"[",
":",
"3",
"]",
"url",
"=",
"\"{}/{}/{}... | 36.48 | 0.001068 |
def load_observations((observations, regex, rename), path, filenames):
"""
Returns a provisional name based dictionary of observations of the object.
Each observations is keyed on the date. ie. a dictionary of dictionaries.
@param path: the directory where filenames are.
@type path str
@param f... | [
"def",
"load_observations",
"(",
"(",
"observations",
",",
"regex",
",",
"rename",
")",
",",
"path",
",",
"filenames",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"if",
"re",
".",
"search",
"(",
"regex",
",",
"filename",
")",
"is",
"None",
":"... | 41.155556 | 0.001582 |
def from_dict(self, d):
"""
Set MobID from a dict
"""
self.length = d.get("length", 0)
self.instanceHigh = d.get("instanceHigh", 0)
self.instanceMid = d.get("instanceMid", 0)
self.instanceLow = d.get("instanceLow", 0)
material = d.get("material", {'Data1'... | [
"def",
"from_dict",
"(",
"self",
",",
"d",
")",
":",
"self",
".",
"length",
"=",
"d",
".",
"get",
"(",
"\"length\"",
",",
"0",
")",
"self",
".",
"instanceHigh",
"=",
"d",
".",
"get",
"(",
"\"instanceHigh\"",
",",
"0",
")",
"self",
".",
"instanceMid... | 37.529412 | 0.009174 |
def get_excitation_spectrum(self, width=0.1, npoints=2000):
"""
Generate an excitation spectra from the singlet roots of TDDFT
calculations.
Args:
width (float): Width for Gaussian smearing.
npoints (int): Number of energy points. More points => smoother
... | [
"def",
"get_excitation_spectrum",
"(",
"self",
",",
"width",
"=",
"0.1",
",",
"npoints",
"=",
"2000",
")",
":",
"roots",
"=",
"self",
".",
"parse_tddft",
"(",
")",
"data",
"=",
"roots",
"[",
"\"singlet\"",
"]",
"en",
"=",
"np",
".",
"array",
"(",
"["... | 30.217391 | 0.001394 |
def _has_exclusive_option(cls, options):
"""Return `True` iff one or more exclusive options were selected."""
return any([getattr(options, opt) is not None for opt in
cls.BASE_ERROR_SELECTION_OPTIONS]) | [
"def",
"_has_exclusive_option",
"(",
"cls",
",",
"options",
")",
":",
"return",
"any",
"(",
"[",
"getattr",
"(",
"options",
",",
"opt",
")",
"is",
"not",
"None",
"for",
"opt",
"in",
"cls",
".",
"BASE_ERROR_SELECTION_OPTIONS",
"]",
")"
] | 58.5 | 0.008439 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: HostedNumberOrderContext for this HostedNumberOrderInstance
:rtype: twilio.rest.preview.hosted_nu... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"HostedNumberOrderContext",
"(",
"self",
".",
"_version",
",",
"sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
... | 48.363636 | 0.01107 |
def getAvgBySweep(abf,feature,T0=None,T1=None):
"""return average of a feature divided by sweep."""
if T1 is None:
T1=abf.sweepLength
if T0 is None:
T0=0
data = [np.empty((0))]*abf.sweeps
for AP in cm.dictFlat(cm.matrixToDicts(abf.APs)):
if T0<AP['sweepT']<T1:
val... | [
"def",
"getAvgBySweep",
"(",
"abf",
",",
"feature",
",",
"T0",
"=",
"None",
",",
"T1",
"=",
"None",
")",
":",
"if",
"T1",
"is",
"None",
":",
"T1",
"=",
"abf",
".",
"sweepLength",
"if",
"T0",
"is",
"None",
":",
"T0",
"=",
"0",
"data",
"=",
"[",
... | 35.210526 | 0.024745 |
def query_helper(request,namespace, docid, configuration=None):
"""Does the actual query, called by query() or pub_query(), not directly"""
flatargs = {
'customslicesize': request.POST.get('customslicesize',settings.CONFIGURATIONS[configuration].get('customslicesize','50')), #for pagination of search re... | [
"def",
"query_helper",
"(",
"request",
",",
"namespace",
",",
"docid",
",",
"configuration",
"=",
"None",
")",
":",
"flatargs",
"=",
"{",
"'customslicesize'",
":",
"request",
".",
"POST",
".",
"get",
"(",
"'customslicesize'",
",",
"settings",
".",
"CONFIGURA... | 57.090909 | 0.01315 |
def quadratic_jacobian_polynomial(nodes):
r"""Compute the Jacobian determinant of a quadratic surface.
.. note::
This is used **only** by :meth:`Surface._compute_valid` (which is
in turn used to compute / cache the :attr:`Surface.is_valid`
property).
Converts :math:`\det(J(s, t))` to... | [
"def",
"quadratic_jacobian_polynomial",
"(",
"nodes",
")",
":",
"# First evaluate the Jacobian at each of the 6 nodes.",
"jac_parts",
"=",
"_helpers",
".",
"matrix_product",
"(",
"nodes",
",",
"_QUADRATIC_JACOBIAN_HELPER",
")",
"jac_at_nodes",
"=",
"np",
".",
"empty",
"("... | 41.027027 | 0.000644 |
def build_duration(self):
"""Return the difference between build and build_done states"""
return int(self.state.build_done) - int(self.state.build) | [
"def",
"build_duration",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"state",
".",
"build_done",
")",
"-",
"int",
"(",
"self",
".",
"state",
".",
"build",
")"
] | 40.25 | 0.012195 |
def multiple_breeding_pups(request, breeding_id):
"""This view is used to enter multiple animals at the same time from a breeding cage.
It will generate a form containing animal information and a number of mice. It is intended to create several identical animals with the same attributes.
This view requres a... | [
"def",
"multiple_breeding_pups",
"(",
"request",
",",
"breeding_id",
")",
":",
"breeding",
"=",
"Breeding",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"breeding_id",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"MultipleBreedingA... | 47.9 | 0.040246 |
def add_sam2rnf_parser(subparsers, subcommand, help, description, simulator_name=None):
"""Add another parser for a SAM2RNF-like command.
Args:
subparsers (subparsers): File name of the genome from which read tuples are created (FASTA file).
simulator_name (str): Name of the simulator used in comments.
"""
... | [
"def",
"add_sam2rnf_parser",
"(",
"subparsers",
",",
"subcommand",
",",
"help",
",",
"description",
",",
"simulator_name",
"=",
"None",
")",
":",
"parser_sam2rnf",
"=",
"subparsers",
".",
"add_parser",
"(",
"subcommand",
",",
"help",
"=",
"help",
",",
"descrip... | 35.714286 | 0.011685 |
def create_variant(cls, variant, **kwargs):
"""Create Variant
Create a new Variant
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_variant(variant, async=True)
>>> result = thre... | [
"def",
"create_variant",
"(",
"cls",
",",
"variant",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_variant_with_http_info",... | 38.809524 | 0.002395 |
def delete_thumbnails(self, source_cache=None):
"""
Delete any thumbnails generated from the source image.
:arg source_cache: An optional argument only used for optimisation
where the source cache instance is already known.
:returns: The number of files deleted.
"""
... | [
"def",
"delete_thumbnails",
"(",
"self",
",",
"source_cache",
"=",
"None",
")",
":",
"source_cache",
"=",
"self",
".",
"get_source_cache",
"(",
")",
"deleted",
"=",
"0",
"if",
"source_cache",
":",
"thumbnail_storage_hash",
"=",
"utils",
".",
"get_storage_hash",
... | 45.272727 | 0.001967 |
def readMyEC2Tag(tagName, connection=None):
"""
Load an EC2 tag for the running instance & print it.
:param str tagName: Name of the tag to read
:param connection: Optional boto connection
"""
assert isinstance(tagName, basestring), ("tagName must be a string but is %r" % tagName)
# Load metadata. if ==... | [
"def",
"readMyEC2Tag",
"(",
"tagName",
",",
"connection",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"tagName",
",",
"basestring",
")",
",",
"(",
"\"tagName must be a string but is %r\"",
"%",
"tagName",
")",
"# Load metadata. if == {} we are on localhost",
"... | 38 | 0.012162 |
def get_upload_form(self):
"""Construct form for accepting file upload."""
return self.form_class(self.request.POST, self.request.FILES) | [
"def",
"get_upload_form",
"(",
"self",
")",
":",
"return",
"self",
".",
"form_class",
"(",
"self",
".",
"request",
".",
"POST",
",",
"self",
".",
"request",
".",
"FILES",
")"
] | 50 | 0.013158 |
def offset(self, offset):
"""Fetch results after `offset` value"""
clone = self._clone()
if isinstance(offset, int):
clone._offset = offset
return clone | [
"def",
"offset",
"(",
"self",
",",
"offset",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"isinstance",
"(",
"offset",
",",
"int",
")",
":",
"clone",
".",
"_offset",
"=",
"offset",
"return",
"clone"
] | 23.875 | 0.010101 |
def perform(self):
"""Perform the version upgrade on the database.
"""
db_versions = self.table.versions()
version = self.version
if (version.is_processed(db_versions) and
not self.config.force_version == self.version.number):
self.log(
... | [
"def",
"perform",
"(",
"self",
")",
":",
"db_versions",
"=",
"self",
".",
"table",
".",
"versions",
"(",
")",
"version",
"=",
"self",
".",
"version",
"if",
"(",
"version",
".",
"is_processed",
"(",
"db_versions",
")",
"and",
"not",
"self",
".",
"config... | 33.12 | 0.002347 |
def _set_client_id(self, client_id):
"""
Method for tracer to set client ID of throttler.
"""
with self.lock:
if self.client_id is None:
self.client_id = client_id | [
"def",
"_set_client_id",
"(",
"self",
",",
"client_id",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"client_id",
"is",
"None",
":",
"self",
".",
"client_id",
"=",
"client_id"
] | 31 | 0.008969 |
def _parse_template(self, code, label):
'''
Pare smart indented templates
Takes a template a returns a list of sub-templates, taking in account
the indentation of the original code based on the first line indentation(0)
Special treatment of whitespace: returns special Offset and... | [
"def",
"_parse_template",
"(",
"self",
",",
"code",
",",
"label",
")",
":",
"if",
"isinstance",
"(",
"code",
",",
"tuple",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"_parse_template",
"(",
"c",
",",
"label",
")",
"for",
"c",
"in",
"code",
")",
... | 37.180233 | 0.001218 |
def UndoTransaction(self):
""" Cancels any running transaction. """
from Ucs import ConfigMap
self._transactionInProgress = False
self._configMap = ConfigMap() | [
"def",
"UndoTransaction",
"(",
"self",
")",
":",
"from",
"Ucs",
"import",
"ConfigMap",
"self",
".",
"_transactionInProgress",
"=",
"False",
"self",
".",
"_configMap",
"=",
"ConfigMap",
"(",
")"
] | 27.166667 | 0.035714 |
def addLengthMeters(stream_network):
"""
Adds length field in meters to network
(The added field name will be 'LENGTH_M').
.. note:: This may be needed for generating the kfac file
depending on the units of your raster. See: :doc:`gis_tools`.
Parameters
... | [
"def",
"addLengthMeters",
"(",
"stream_network",
")",
":",
"network_shapefile",
"=",
"ogr",
".",
"Open",
"(",
"stream_network",
",",
"1",
")",
"network_layer",
"=",
"network_shapefile",
".",
"GetLayer",
"(",
")",
"network_layer_defn",
"=",
"network_layer",
".",
... | 36.603175 | 0.000845 |
def group_memberships(self, user, include=None):
"""
Retrieve the group memberships for this user.
:param include: list of objects to sideload. `Side-loading API Docs
<https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.
:param user: User object or id
... | [
"def",
"group_memberships",
"(",
"self",
",",
"user",
",",
"include",
"=",
"None",
")",
":",
"return",
"self",
".",
"_query_zendesk",
"(",
"self",
".",
"endpoint",
".",
"group_memberships",
",",
"'group_membership'",
",",
"id",
"=",
"user",
",",
"include",
... | 47.666667 | 0.009153 |
def focus_next_unfolded(self):
"""focus next unfolded message in depth first order"""
self.focus_property(lambda x: not x.is_collapsed(x.root),
self._tree.next_position) | [
"def",
"focus_next_unfolded",
"(",
"self",
")",
":",
"self",
".",
"focus_property",
"(",
"lambda",
"x",
":",
"not",
"x",
".",
"is_collapsed",
"(",
"x",
".",
"root",
")",
",",
"self",
".",
"_tree",
".",
"next_position",
")"
] | 52.5 | 0.00939 |
def cmd_camctrlmsg(self, args):
'''camctrlmsg'''
print("Sent DIGICAM_CONFIGURE CMD_LONG")
self.master.mav.command_long_send(
self.settings.target_system, # target_system
0, # target_component
mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONFIGURE, # command
... | [
"def",
"cmd_camctrlmsg",
"(",
"self",
",",
"args",
")",
":",
"print",
"(",
"\"Sent DIGICAM_CONFIGURE CMD_LONG\"",
")",
"self",
".",
"master",
".",
"mav",
".",
"command_long_send",
"(",
"self",
".",
"settings",
".",
"target_system",
",",
"# target_system",
"0",
... | 30.625 | 0.021782 |
def office_content(self, election_day, office):
"""
Return serialized content for an office page.
"""
from electionnight.models import PageType
office_type = ContentType.objects.get_for_model(office)
page_type = PageType.objects.get(
model_type=office_type,
... | [
"def",
"office_content",
"(",
"self",
",",
"election_day",
",",
"office",
")",
":",
"from",
"electionnight",
".",
"models",
"import",
"PageType",
"office_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"office",
")",
"page_type",
"=",
"Pa... | 34.75 | 0.002 |
def extract_tar(fileobj):
"""Yields 3-tuples of (name, modified, bytes)."""
import time
archive = tarfile.open(fileobj=fileobj)
filenames = [info.name for info in archive.getmembers() if info.isfile()]
for src_name, dst_name in filter_tzfiles(filenames):
mtime = archive.getmember(src_name)... | [
"def",
"extract_tar",
"(",
"fileobj",
")",
":",
"import",
"time",
"archive",
"=",
"tarfile",
".",
"open",
"(",
"fileobj",
"=",
"fileobj",
")",
"filenames",
"=",
"[",
"info",
".",
"name",
"for",
"info",
"in",
"archive",
".",
"getmembers",
"(",
")",
"if"... | 35.153846 | 0.002132 |
def draw_text(self, video_name, out, start, end, x, y, text,
color='0xFFFFFF', show_background=0,
background_color='0x000000', size=16):
"""
Draws text over a video
@param video_name : name of video input file
@param out : name of video output file
... | [
"def",
"draw_text",
"(",
"self",
",",
"video_name",
",",
"out",
",",
"start",
",",
"end",
",",
"x",
",",
"y",
",",
"text",
",",
"color",
"=",
"'0xFFFFFF'",
",",
"show_background",
"=",
"0",
",",
"background_color",
"=",
"'0x000000'",
",",
"size",
"=",
... | 42.55814 | 0.002137 |
def validate_metadata(target_dir, metadata):
"""
Check that the files listed in metadata exactly match files in target dir.
:param target_dir: This field is the target directory from which to
match metadata
:param metadata: This field contains the metadata to be matched.
"""
if not os.p... | [
"def",
"validate_metadata",
"(",
"target_dir",
",",
"metadata",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"target_dir",
")",
":",
"print",
"(",
"\"Error: \"",
"+",
"target_dir",
"+",
"\" is not a directory\"",
")",
"return",
"False",
"file... | 38.826087 | 0.001093 |
def graceful_exit(self, msg):
""" This function Tries to update the MSQL database before exiting. """
# Print stored errors to stderr
if self.caught_error:
self.print2file(self.stderr, False, False, self.caught_error)
# Kill process with error message
self.log(msg)
sys.exit(... | [
"def",
"graceful_exit",
"(",
"self",
",",
"msg",
")",
":",
"# Print stored errors to stderr",
"if",
"self",
".",
"caught_error",
":",
"self",
".",
"print2file",
"(",
"self",
".",
"stderr",
",",
"False",
",",
"False",
",",
"self",
".",
"caught_error",
")",
... | 39.375 | 0.02795 |
def _check_pending_document_role_state(cursor, document_id):
"""Check the aggregate state on the pending document."""
cursor.execute("""\
SELECT BOOL_AND(accepted IS TRUE)
FROM
role_acceptances AS ra,
pending_documents as pd
WHERE
pd.id = %s
AND
pd.uuid = ra.uuid""",
(document_id,))... | [
"def",
"_check_pending_document_role_state",
"(",
"cursor",
",",
"document_id",
")",
":",
"cursor",
".",
"execute",
"(",
"\"\"\"\\\nSELECT BOOL_AND(accepted IS TRUE)\nFROM\n role_acceptances AS ra,\n pending_documents as pd\nWHERE\n pd.id = %s\n AND\n pd.uuid = ra.uuid\"\"\"",
",",
... | 25.888889 | 0.00207 |
def nx_gen_edge_values(G, key, edges=None, default=util_const.NoParam,
on_missing='error', on_keyerr='default'):
"""
Generates attributes values of specific edges
Args:
on_missing (str): Strategy for handling nodes missing from G.
Can be {'error', 'default'}. def... | [
"def",
"nx_gen_edge_values",
"(",
"G",
",",
"key",
",",
"edges",
"=",
"None",
",",
"default",
"=",
"util_const",
".",
"NoParam",
",",
"on_missing",
"=",
"'error'",
",",
"on_keyerr",
"=",
"'default'",
")",
":",
"if",
"edges",
"is",
"None",
":",
"edges",
... | 40.486486 | 0.001304 |
def aws_client(self, client_id=None):
"""
Get AWS client if it exists (must have been formerly stored with set_aws_clients)
If client_id is not provided, returns the dictionary of all clients
Args:
client_id: label for the client, e.g. 'ec2'; omit to get a dictionary of all clients
Returns:
... | [
"def",
"aws_client",
"(",
"self",
",",
"client_id",
"=",
"None",
")",
":",
"if",
"client_id",
"is",
"None",
":",
"return",
"self",
".",
"_aws_clients",
"elif",
"self",
".",
"_aws_clients",
"is",
"not",
"None",
"and",
"self",
".",
"_aws_clients",
".",
"ha... | 37.4 | 0.013913 |
def register(name: str):
"""
Registers a coverage extractor class under a given name.
.. code: python
from bugzoo.mgr.coverage import CoverageExtractor, register
@register('mycov')
class MyCoverageExtractor(CoverageExtractor):
...
"""
def decorator(cls: Type['C... | [
"def",
"register",
"(",
"name",
":",
"str",
")",
":",
"def",
"decorator",
"(",
"cls",
":",
"Type",
"[",
"'CoverageExtractor'",
"]",
")",
":",
"cls",
".",
"register",
"(",
"name",
")",
"return",
"cls",
"return",
"decorator"
] | 24.5 | 0.002457 |
def create_profile():
"""If this is the user's first login, the create_or_login function
will redirect here so that the user can set up his profile.
"""
if g.user is not None or 'openid' not in session:
return redirect(url_for('index'))
if request.method == 'POST':
name = request.for... | [
"def",
"create_profile",
"(",
")",
":",
"if",
"g",
".",
"user",
"is",
"not",
"None",
"or",
"'openid'",
"not",
"in",
"session",
":",
"return",
"redirect",
"(",
"url_for",
"(",
"'index'",
")",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"... | 44.333333 | 0.001227 |
def stopped(name=None,
containers=None,
shutdown_timeout=None,
unpause=False,
error_on_absent=True,
**kwargs):
'''
Ensure that a container (or containers) is stopped
name
Name or ID of the container
containers
Run this state o... | [
"def",
"stopped",
"(",
"name",
"=",
"None",
",",
"containers",
"=",
"None",
",",
"shutdown_timeout",
"=",
"None",
",",
"unpause",
"=",
"False",
",",
"error_on_absent",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"n... | 30.797386 | 0.000206 |
def on_confirmation(self, frame):
"""Invoked by pika when RabbitMQ responds to a Basic.Publish RPC
command, passing in either a Basic.Ack or Basic.Nack frame with
the delivery tag of the message that was published. The delivery tag
is an integer counter indicating the message number that... | [
"def",
"on_confirmation",
"(",
"self",
",",
"frame",
")",
":",
"delivered",
"=",
"frame",
".",
"method",
".",
"NAME",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"'ack'",
"self",
".",
"logger",
".",
"debug",
"(",
"... | 50.263158 | 0.002055 |
def evpn_prefix_del(self, route_type, route_dist, esi=0,
ethernet_tag_id=None, mac_addr=None, ip_addr=None,
ip_prefix=None):
""" This method deletes an advertised EVPN route.
``route_type`` specifies one of the EVPN route type name.
``route_dist`... | [
"def",
"evpn_prefix_del",
"(",
"self",
",",
"route_type",
",",
"route_dist",
",",
"esi",
"=",
"0",
",",
"ethernet_tag_id",
"=",
"None",
",",
"mac_addr",
"=",
"None",
",",
"ip_addr",
"=",
"None",
",",
"ip_prefix",
"=",
"None",
")",
":",
"func_name",
"=",
... | 34.285714 | 0.002025 |
def estimate_tuning(y=None, sr=22050, S=None, n_fft=2048,
resolution=0.01, bins_per_octave=12, **kwargs):
'''Estimate the tuning of an audio time series or spectrogram input.
Parameters
----------
y: np.ndarray [shape=(n,)] or None
audio signal
sr : number > 0 [scalar]
... | [
"def",
"estimate_tuning",
"(",
"y",
"=",
"None",
",",
"sr",
"=",
"22050",
",",
"S",
"=",
"None",
",",
"n_fft",
"=",
"2048",
",",
"resolution",
"=",
"0.01",
",",
"bins_per_octave",
"=",
"12",
",",
"*",
"*",
"kwargs",
")",
":",
"pitch",
",",
"mag",
... | 29.311688 | 0.000429 |
def save_config(
self, cmd="write memory flash-synchro", confirm=False, confirm_response=""
):
"""Save Config"""
return super(AlcatelAosSSH, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) | [
"def",
"save_config",
"(",
"self",
",",
"cmd",
"=",
"\"write memory flash-synchro\"",
",",
"confirm",
"=",
"False",
",",
"confirm_response",
"=",
"\"\"",
")",
":",
"return",
"super",
"(",
"AlcatelAosSSH",
",",
"self",
")",
".",
"save_config",
"(",
"cmd",
"="... | 37.571429 | 0.01487 |
def warning(self, i: int=None) -> str:
"""
Returns a warning message
"""
head = "[" + colors.purple("\033[1mwarning") + "]"
if i is not None:
head = str(i) + " " + head
return head | [
"def",
"warning",
"(",
"self",
",",
"i",
":",
"int",
"=",
"None",
")",
"->",
"str",
":",
"head",
"=",
"\"[\"",
"+",
"colors",
".",
"purple",
"(",
"\"\\033[1mwarning\"",
")",
"+",
"\"]\"",
"if",
"i",
"is",
"not",
"None",
":",
"head",
"=",
"str",
"... | 29.125 | 0.016667 |
def relationship_descriptor(action, *names):
"""
Wrap a function for modification of a relationship. This allows for
specific handling for serialization and deserialization.
:param action: The RelationshipActions that this descriptor performs
:param names: A list of names of the relationships this... | [
"def",
"relationship_descriptor",
"(",
"action",
",",
"*",
"names",
")",
":",
"if",
"isinstance",
"(",
"action",
",",
"RelationshipActions",
")",
":",
"action",
"=",
"[",
"action",
"]",
"def",
"wrapped",
"(",
"fn",
")",
":",
"if",
"not",
"hasattr",
"(",
... | 34.55 | 0.001408 |
def group_retrieve(self, device_group_id, **kwargs): # noqa: E501
"""Get a group. # noqa: E501
Get a group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_retriev... | [
"def",
"group_retrieve",
"(",
"self",
",",
"device_group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
... | 44.047619 | 0.002116 |
def is_namedtuple_like(x):
"""Helper which returns `True` if input is `collections.namedtuple`-like."""
try:
for fn in x._fields:
_ = getattr(x, fn)
return True
except AttributeError:
return False | [
"def",
"is_namedtuple_like",
"(",
"x",
")",
":",
"try",
":",
"for",
"fn",
"in",
"x",
".",
"_fields",
":",
"_",
"=",
"getattr",
"(",
"x",
",",
"fn",
")",
"return",
"True",
"except",
"AttributeError",
":",
"return",
"False"
] | 26.625 | 0.022727 |
def ps_(filters=None, **kwargs):
'''
Returns information about the Docker containers on the Minion. Equivalent
to running the ``docker ps`` Docker CLI command.
all : False
If ``True``, stopped containers will also be returned
host: False
If ``True``, local host's network topology w... | [
"def",
"ps_",
"(",
"filters",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"_client_wrapper",
"(",
"'containers'",
",",
"all",
"=",
"True",
",",
"filters",
"=",
"filters",
")",
"key_map",
"=",
"{",
"'Created'",
":",
"'Time_Created_Epo... | 32.945946 | 0.000398 |
def filebrowser_remove_file(request, item_id, file_type):
""" Remove file """
fobj = get_object_or_404(FileBrowserFile, file_type=file_type, id=item_id)
fobj.delete()
if file_type == 'doc':
return HttpResponseRedirect(reverse('mce-filebrowser-documents'))
return HttpResponseRedirec... | [
"def",
"filebrowser_remove_file",
"(",
"request",
",",
"item_id",
",",
"file_type",
")",
":",
"fobj",
"=",
"get_object_or_404",
"(",
"FileBrowserFile",
",",
"file_type",
"=",
"file_type",
",",
"id",
"=",
"item_id",
")",
"fobj",
".",
"delete",
"(",
")",
"if",... | 38.666667 | 0.008427 |
def read_raster_no_crs(input_file, indexes=None, gdal_opts=None):
"""
Wrapper function around rasterio.open().read().
Parameters
----------
input_file : str
Path to file
indexes : int or list
Band index or list of band indexes to be read.
Returns
-------
MaskedArray... | [
"def",
"read_raster_no_crs",
"(",
"input_file",
",",
"indexes",
"=",
"None",
",",
"gdal_opts",
"=",
"None",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"try",
":",
"with",
"ra... | 29.342857 | 0.001885 |
def date_tuple(ovls):
"""
We should have a list of overlays from which to extract day month
year.
"""
day = month = year = 0
for o in ovls:
if 'day' in o.props:
day = o.value
if 'month' in o.props:
month = o.value
if 'year' in o.props:
... | [
"def",
"date_tuple",
"(",
"ovls",
")",
":",
"day",
"=",
"month",
"=",
"year",
"=",
"0",
"for",
"o",
"in",
"ovls",
":",
"if",
"'day'",
"in",
"o",
".",
"props",
":",
"day",
"=",
"o",
".",
"value",
"if",
"'month'",
"in",
"o",
".",
"props",
":",
... | 23.772727 | 0.001838 |
def autopage(self):
"""Iterate through results from all pages.
:return: all results
:rtype: generator
"""
while self.items:
yield from self.items
self.items = self.fetch_next() | [
"def",
"autopage",
"(",
"self",
")",
":",
"while",
"self",
".",
"items",
":",
"yield",
"from",
"self",
".",
"items",
"self",
".",
"items",
"=",
"self",
".",
"fetch_next",
"(",
")"
] | 25.888889 | 0.008299 |
def _voltage_deviation(network, nodes, v_dev_allowed_upper,
v_dev_allowed_lower, voltage_level):
"""
Checks for voltage stability issues in LV grids.
Parameters
----------
network : :class:`~.grid.network.Network`
nodes : :obj:`list`
List of nodes (of type :class:`... | [
"def",
"_voltage_deviation",
"(",
"network",
",",
"nodes",
",",
"v_dev_allowed_upper",
",",
"v_dev_allowed_lower",
",",
"voltage_level",
")",
":",
"def",
"_append_crit_node",
"(",
"series",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"'v_mag_pu'",
":",... | 44.828947 | 0.000287 |
def _get_el_to_normative(parent_elem, normative_parent_elem):
"""Return ordered dict ``el_to_normative``, which maps children of
``parent_elem`` to their normative counterparts in the children of
``normative_parent_elem`` or to ``None`` if there is no normative
parent. If there is a norm... | [
"def",
"_get_el_to_normative",
"(",
"parent_elem",
",",
"normative_parent_elem",
")",
":",
"el_to_normative",
"=",
"OrderedDict",
"(",
")",
"if",
"normative_parent_elem",
"is",
"None",
":",
"for",
"el",
"in",
"parent_elem",
":",
"el_to_normative",
"[",
"el",
"]",
... | 47.269231 | 0.001595 |
def fix_e713(self, result):
"""Fix (trivial case of) non-membership check."""
(line_index, offset, target) = get_index_offset_contents(result,
self.source)
# to convert once 'not in' -> 'in'
before_target = target[:offset]... | [
"def",
"fix_e713",
"(",
"self",
",",
"result",
")",
":",
"(",
"line_index",
",",
"offset",
",",
"target",
")",
"=",
"get_index_offset_contents",
"(",
"result",
",",
"self",
".",
"source",
")",
"# to convert once 'not in' -> 'in'",
"before_target",
"=",
"target",... | 46.677419 | 0.001354 |
def prints(*texts, **kwargs):
"""Print formatted message (manual ANSI escape sequences to avoid
dependency)
*texts (unicode): Texts to print. Each argument is rendered as paragraph.
**kwargs: 'title' becomes coloured headline. exits=True performs sys exit.
"""
exits = kwargs.get('exits', None)
... | [
"def",
"prints",
"(",
"*",
"texts",
",",
"*",
"*",
"kwargs",
")",
":",
"exits",
"=",
"kwargs",
".",
"get",
"(",
"'exits'",
",",
"None",
")",
"title",
"=",
"kwargs",
".",
"get",
"(",
"'title'",
",",
"None",
")",
"title",
"=",
"'\\033[93m{}\\033[0m\\n'... | 40.714286 | 0.001715 |
def read_relation_file(filename):
'''
Reads the GermaNet relation file ``gn_relations.xml`` which lists
all the relations holding between lexical units and synsets.
Arguments:
- `filename`:
'''
with open(filename, 'rb') as input_file:
doc = etree.parse(input_file)
lex_rels = []... | [
"def",
"read_relation_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"input_file",
":",
"doc",
"=",
"etree",
".",
"parse",
"(",
"input_file",
")",
"lex_rels",
"=",
"[",
"]",
"con_rels",
"=",
"[",
"]",
"assert... | 40.404762 | 0.001151 |
def groupby(self, group, squeeze: bool = True):
"""Returns a GroupBy object for performing grouped operations.
Parameters
----------
group : str, DataArray or IndexVariable
Array whose unique values should be used to group this array. If a
string, must be the nam... | [
"def",
"groupby",
"(",
"self",
",",
"group",
",",
"squeeze",
":",
"bool",
"=",
"True",
")",
":",
"# noqa",
"return",
"self",
".",
"_groupby_cls",
"(",
"self",
",",
"group",
",",
"squeeze",
"=",
"squeeze",
")"
] | 42.866667 | 0.001014 |
def load_data(fname):
""" loads previously exported CSV file to redis database """
print('Loading ' + fname + ' to redis')
r = redis.StrictRedis(host = '127.0.0.1', port = 6379, db = 0);
with open(fname, 'r') as f:
for line_num, row in enumerate(f):
if row.strip('') != '':
... | [
"def",
"load_data",
"(",
"fname",
")",
":",
"print",
"(",
"'Loading '",
"+",
"fname",
"+",
"' to redis'",
")",
"r",
"=",
"redis",
".",
"StrictRedis",
"(",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"6379",
",",
"db",
"=",
"0",
")",
"with",
"open",... | 46.769231 | 0.017742 |
def cli(env, name, description):
"""Create a security group."""
mgr = SoftLayer.NetworkManager(env.client)
result = mgr.create_securitygroup(name, description)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', resul... | [
"def",
"cli",
"(",
"env",
",",
"name",
",",
"description",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"mgr",
".",
"create_securitygroup",
"(",
"name",
",",
"description",
")",
"table",
"=",
... | 36.25 | 0.001681 |
def _detect_migration_layout(vars, apps):
"""
Detect migrations layout for plugins
:param vars: installer settings
:param apps: installed applications
"""
DJANGO_MODULES = {}
for module in vars.MIGRATIONS_CHECK_MODULES:
if module in apps:
try:
mod = __imp... | [
"def",
"_detect_migration_layout",
"(",
"vars",
",",
"apps",
")",
":",
"DJANGO_MODULES",
"=",
"{",
"}",
"for",
"module",
"in",
"vars",
".",
"MIGRATIONS_CHECK_MODULES",
":",
"if",
"module",
"in",
"apps",
":",
"try",
":",
"mod",
"=",
"__import__",
"(",
"'{0}... | 32.1875 | 0.001887 |
def basic_range1(ranged_hparams):
"""A basic range of hyperparameters."""
rhp = ranged_hparams
rhp.set_discrete("batch_size", [1024, 2048, 4096])
rhp.set_discrete("num_hidden_layers", [1, 2, 3, 4, 5, 6])
rhp.set_discrete("hidden_size", [32, 64, 128, 256, 512], scale=rhp.LOG_SCALE)
rhp.set_discrete("kernel_h... | [
"def",
"basic_range1",
"(",
"ranged_hparams",
")",
":",
"rhp",
"=",
"ranged_hparams",
"rhp",
".",
"set_discrete",
"(",
"\"batch_size\"",
",",
"[",
"1024",
",",
"2048",
",",
"4096",
"]",
")",
"rhp",
".",
"set_discrete",
"(",
"\"num_hidden_layers\"",
",",
"[",... | 50 | 0.016484 |
def _Pcn_zm(x, dsz, Nv, dimN=2, dimC=1):
"""
Projection onto dictionary update constraint set: support projection,
mean subtraction, and normalisation. The result has the full spatial
dimensions of the input.
Parameters
----------
x : array_like
Input array
dsz : tuple
Fil... | [
"def",
"_Pcn_zm",
"(",
"x",
",",
"dsz",
",",
"Nv",
",",
"dimN",
"=",
"2",
",",
"dimC",
"=",
"1",
")",
":",
"return",
"normalise",
"(",
"zeromean",
"(",
"zpad",
"(",
"bcrop",
"(",
"x",
",",
"dsz",
",",
"dimN",
")",
",",
"Nv",
")",
",",
"dsz",
... | 28.740741 | 0.001247 |
def statistics(cls, function, group=None):
"""
Compute statistics (average, max, median, minimun and sum) from _results
into a dictionary of numpy array.
"""
benchmark = cls.results(function, group)
results = {}
for name, stat in {'avg': numpy.average, 'max': nump... | [
"def",
"statistics",
"(",
"cls",
",",
"function",
",",
"group",
"=",
"None",
")",
":",
"benchmark",
"=",
"cls",
".",
"results",
"(",
"function",
",",
"group",
")",
"results",
"=",
"{",
"}",
"for",
"name",
",",
"stat",
"in",
"{",
"'avg'",
":",
"nump... | 46 | 0.008529 |
def available_ports(low=1024, high=65535, exclude_ranges=None):
"""
Returns a set of possible ports (excluding system,
ephemeral and well-known ports).
Pass ``high`` and/or ``low`` to limit the port range.
"""
if exclude_ranges is None:
exclude_ranges = []
available = utils.ranges_t... | [
"def",
"available_ports",
"(",
"low",
"=",
"1024",
",",
"high",
"=",
"65535",
",",
"exclude_ranges",
"=",
"None",
")",
":",
"if",
"exclude_ranges",
"is",
"None",
":",
"exclude_ranges",
"=",
"[",
"]",
"available",
"=",
"utils",
".",
"ranges_to_set",
"(",
... | 30.368421 | 0.001681 |
def scan_interfaces(address=None):
""" Scan all the interfaces for available Crazyflies """
available = []
found = []
for driverClass in CLASSES:
try:
logger.debug('Scanning: %s', driverClass)
instance = driverClass()
found = instance.scan_interface(address)
... | [
"def",
"scan_interfaces",
"(",
"address",
"=",
"None",
")",
":",
"available",
"=",
"[",
"]",
"found",
"=",
"[",
"]",
"for",
"driverClass",
"in",
"CLASSES",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"'Scanning: %s'",
",",
"driverClass",
")",
"instance... | 30.923077 | 0.002415 |
def fit_points_in_bounding_box(df_points, bounding_box, padding_fraction=0):
'''
Return data frame with ``x``, ``y`` columns scaled to fit points from
:data:`df_points` to fill :data:`bounding_box` while maintaining aspect
ratio.
Arguments
---------
df_points : pandas.DataFrame
A fr... | [
"def",
"fit_points_in_bounding_box",
"(",
"df_points",
",",
"bounding_box",
",",
"padding_fraction",
"=",
"0",
")",
":",
"df_scaled_points",
"=",
"df_points",
".",
"copy",
"(",
")",
"offset",
",",
"padded_scale",
"=",
"fit_points_in_bounding_box_params",
"(",
"df_po... | 39.344828 | 0.000855 |
async def status(self, *args, **kwargs):
"""
Get task status
Get task status structure from `taskId`
This method gives output: ``v1/task-status-response.json#``
This method is ``stable``
"""
return await self._makeApiCall(self.funcinfo["status"], *args, **kwar... | [
"async",
"def",
"status",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"status\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 26 | 0.009288 |
def has_layer(self, class_: Type[L], became: bool=True) -> bool:
"""
Proxy to stack
"""
return self.stack.has_layer(class_, became) | [
"def",
"has_layer",
"(",
"self",
",",
"class_",
":",
"Type",
"[",
"L",
"]",
",",
"became",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"return",
"self",
".",
"stack",
".",
"has_layer",
"(",
"class_",
",",
"became",
")"
] | 31.8 | 0.02454 |
def _normalizeParseActionArgs( f ):
"""Internal method used to decorate parse actions that take fewer than 3 arguments,
so that all parse actions can be called as f(s,l,t)."""
STAR_ARGS = 4
try:
restore = None
if isinstance(f,type):
restore = f... | [
"def",
"_normalizeParseActionArgs",
"(",
"f",
")",
":",
"STAR_ARGS",
"=",
"4",
"try",
":",
"restore",
"=",
"None",
"if",
"isinstance",
"(",
"f",
",",
"type",
")",
":",
"restore",
"=",
"f",
"f",
"=",
"f",
".",
"__init__",
"if",
"not",
"_PY3K",
":",
... | 35.836957 | 0.010035 |
def sheetheader(sheet, startstops, usecols=None):
"""Return the channel names in a list suitable as an argument to
ChannelPack's `set_channel_names` method. Return None if first two
StartStops are None.
This function is slightly confusing, because it shall be called with
the same parameters as shee... | [
"def",
"sheetheader",
"(",
"sheet",
",",
"startstops",
",",
"usecols",
"=",
"None",
")",
":",
"headstart",
",",
"headstop",
",",
"dstart",
",",
"dstop",
"=",
"startstops",
"if",
"headstart",
"is",
"None",
":",
"return",
"None",
"assert",
"headstop",
".",
... | 37.333333 | 0.000669 |
def _predict_in_session(self, sess, other_var, X_feat, X_seq, variable="y_pred"):
"""
Predict y (or any other variable) from inside the tf session. Variable has to be in other_var
"""
# other_var["tf_X_seq"]: X_seq, tf_y: y,
feed_dict = {other_var["tf_X_feat"]: X_feat,
... | [
"def",
"_predict_in_session",
"(",
"self",
",",
"sess",
",",
"other_var",
",",
"X_feat",
",",
"X_seq",
",",
"variable",
"=",
"\"y_pred\"",
")",
":",
"# other_var[\"tf_X_seq\"]: X_seq, tf_y: y,",
"feed_dict",
"=",
"{",
"other_var",
"[",
"\"tf_X_feat\"",
"]",
":",
... | 44.2 | 0.008869 |
def _remove_rid_from_vrf_list(self, ri):
"""Remove router ID from a VRF list.
This removes a router from the list of routers that's kept
in a map, using a VRF ID as the key. If the VRF exists, the
router is removed from the list if it's present. If the last
router in the list is... | [
"def",
"_remove_rid_from_vrf_list",
"(",
"self",
",",
"ri",
")",
":",
"if",
"ri",
".",
"ex_gw_port",
"or",
"ri",
".",
"router",
".",
"get",
"(",
"'gw_port'",
")",
":",
"driver",
"=",
"self",
".",
"driver_manager",
".",
"get_driver",
"(",
"ri",
".",
"id... | 53.681818 | 0.001664 |
def raise_error(subject, error_class):
'''
Call function `subject` and expect the function to raise an exception.
>>> expect = Expector([])
>>> expect(lambda: 1 / 0).to(raise_error, ZeroDivisionError)
(True, 'Expect ZeroDivisionError to be raised')
'''
description = 'Expect {} to be raised'.... | [
"def",
"raise_error",
"(",
"subject",
",",
"error_class",
")",
":",
"description",
"=",
"'Expect {} to be raised'",
".",
"format",
"(",
"error_class",
".",
"__name__",
")",
"try",
":",
"subject",
"(",
")",
"return",
"(",
"False",
",",
"description",
")",
"ex... | 35.230769 | 0.002128 |
def _fetch_option(cfg, ret_config, virtualname, attr_name):
"""
Fetch a given option value from the config.
@see :func:`get_returner_options`
"""
# c_cfg is a dictionary returned from config.option for
# any options configured for this returner.
if isinstance(cfg, dict):
c_cfg = cfg... | [
"def",
"_fetch_option",
"(",
"cfg",
",",
"ret_config",
",",
"virtualname",
",",
"attr_name",
")",
":",
"# c_cfg is a dictionary returned from config.option for",
"# any options configured for this returner.",
"if",
"isinstance",
"(",
"cfg",
",",
"dict",
")",
":",
"c_cfg",... | 31.227273 | 0.000706 |
def showdeletion(self, *objects):
"""
Record a stack trace at the point when an ROOT TObject is deleted
"""
from ..memory import showdeletion as S
for o in objects:
S.monitor_object_cleanup(o) | [
"def",
"showdeletion",
"(",
"self",
",",
"*",
"objects",
")",
":",
"from",
".",
".",
"memory",
"import",
"showdeletion",
"as",
"S",
"for",
"o",
"in",
"objects",
":",
"S",
".",
"monitor_object_cleanup",
"(",
"o",
")"
] | 34 | 0.008197 |
def _fill_row_borders(self):
"""Add the first and last rows to the data by extrapolation.
"""
lines = len(self.hrow_indices)
chunk_size = self.chunk_size or lines
factor = len(self.hrow_indices) / len(self.row_indices)
tmp_data = []
for num in range(len(self.tie_... | [
"def",
"_fill_row_borders",
"(",
"self",
")",
":",
"lines",
"=",
"len",
"(",
"self",
".",
"hrow_indices",
")",
"chunk_size",
"=",
"self",
".",
"chunk_size",
"or",
"lines",
"factor",
"=",
"len",
"(",
"self",
".",
"hrow_indices",
")",
"/",
"len",
"(",
"s... | 46.675676 | 0.002269 |
def set_xml_output(self, xml_file):
"""
Tell ligolw_sqlite to dump the contents of the database to a file.
"""
if self.get_database() is None:
raise ValueError, "no database specified"
self.add_file_opt('extract', xml_file)
self.__xml_output = xml_file | [
"def",
"set_xml_output",
"(",
"self",
",",
"xml_file",
")",
":",
"if",
"self",
".",
"get_database",
"(",
")",
"is",
"None",
":",
"raise",
"ValueError",
",",
"\"no database specified\"",
"self",
".",
"add_file_opt",
"(",
"'extract'",
",",
"xml_file",
")",
"se... | 34.375 | 0.010638 |
def plot_sampler_fingerprint(
sampler, hyperprior, weights=None, cutoff_weight=None, nbins=None,
labels=None, burn=0, chain_mask=None, temp_idx=0, points=None,
plot_samples=False, sample_color='k', point_color=None, point_lw=3,
title='', rot_x_labels=False, figsize=None
):
"""Mak... | [
"def",
"plot_sampler_fingerprint",
"(",
"sampler",
",",
"hyperprior",
",",
"weights",
"=",
"None",
",",
"cutoff_weight",
"=",
"None",
",",
"nbins",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"burn",
"=",
"0",
",",
"chain_mask",
"=",
"None",
",",
"temp... | 44.586207 | 0.002396 |
def beacon(config):
'''
Check if installed packages are the latest versions
and fire an event for those that have upgrades.
.. code-block:: yaml
beacons:
pkg:
- pkgs:
- zsh
- apache2
- refresh: True
'''
ret = []
_re... | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"_refresh",
"=",
"False",
"pkgs",
"=",
"[",
"]",
"for",
"config_item",
"in",
"config",
":",
"if",
"'pkgs'",
"in",
"config_item",
":",
"pkgs",
"+=",
"config_item",
"[",
"'pkgs'",
"]",
"if... | 24.787879 | 0.001176 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.