text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def calendar(request, year=None, month=None, template="gnotty/calendar.html"):
"""
Show calendar months for the given year/month.
"""
try:
year = int(year)
except TypeError:
year = datetime.now().year
lookup = {"message_time__year": year}
if month:
lookup["message_ti... | [
"def",
"calendar",
"(",
"request",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"template",
"=",
"\"gnotty/calendar.html\"",
")",
":",
"try",
":",
"year",
"=",
"int",
"(",
"year",
")",
"except",
"TypeError",
":",
"year",
"=",
"datetime",
"... | 34.977273 | 16.113636 |
def remove(self, force=False, timeout=-1):
"""
Removes the rackserver with the specified URI.
Note: This operation is only supported on appliances that support rack-mounted servers.
Args:
force (bool):
If set to true, the operation completes despite any probl... | [
"def",
"remove",
"(",
"self",
",",
"force",
"=",
"False",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"delete",
"(",
"force",
"=",
"force",
",",
"timeout",
"=",
"timeout",
")"
] | 45.411765 | 28.352941 |
def dumpload(self, site=None, role=None):
"""
Dumps and loads a database snapshot simultaneously.
Requires that the destination server has direct database access
to the source server.
This is better than a serial dump+load when:
1. The network connection is reliable.
... | [
"def",
"dumpload",
"(",
"self",
",",
"site",
"=",
"None",
",",
"role",
"=",
"None",
")",
":",
"r",
"=",
"self",
".",
"database_renderer",
"(",
"site",
"=",
"site",
",",
"role",
"=",
"role",
")",
"r",
".",
"run",
"(",
"'pg_dump -c --host={host_string} -... | 43.5 | 17.9 |
def upload_file(self, container, src_file_path, dst_name=None, put=True,
content_type=None):
"""Upload a single file."""
if not os.path.exists(src_file_path):
raise RuntimeError('file not found: ' + src_file_path)
if not dst_name:
dst_name = os.path.ba... | [
"def",
"upload_file",
"(",
"self",
",",
"container",
",",
"src_file_path",
",",
"dst_name",
"=",
"None",
",",
"put",
"=",
"True",
",",
"content_type",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"src_file_path",
")",
":",... | 43.566667 | 18.066667 |
def add_suspect(self, case_obj, variant_obj):
"""Link a suspect to a case."""
new_suspect = Suspect(case=case_obj, variant_id=variant_obj.variant_id,
name=variant_obj.display_name)
self.session.add(new_suspect)
self.save()
return new_suspect | [
"def",
"add_suspect",
"(",
"self",
",",
"case_obj",
",",
"variant_obj",
")",
":",
"new_suspect",
"=",
"Suspect",
"(",
"case",
"=",
"case_obj",
",",
"variant_id",
"=",
"variant_obj",
".",
"variant_id",
",",
"name",
"=",
"variant_obj",
".",
"display_name",
")"... | 43.571429 | 14.571429 |
def sample_cleanup(data, sample):
""" stats, cleanup, and link to samples """
## get maxlen and depths array from clusters
maxlens, depths = get_quick_depths(data, sample)
try:
depths.max()
except ValueError:
## If depths is an empty array max() will raise
print(" no clu... | [
"def",
"sample_cleanup",
"(",
"data",
",",
"sample",
")",
":",
"## get maxlen and depths array from clusters",
"maxlens",
",",
"depths",
"=",
"get_quick_depths",
"(",
"data",
",",
"sample",
")",
"try",
":",
"depths",
".",
"max",
"(",
")",
"except",
"ValueError",... | 44.806452 | 24.989247 |
def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True):
"""Calculate the bounding pressure and height in a layer.
Given pressure, optional heights, and a bound, return either the closest pressure/height
or interpolated pressure/height. If no heights are provided, a standard atmosph... | [
"def",
"_get_bound_pressure_height",
"(",
"pressure",
",",
"bound",
",",
"heights",
"=",
"None",
",",
"interpolate",
"=",
"True",
")",
":",
"# Make sure pressure is monotonically decreasing",
"sort_inds",
"=",
"np",
".",
"argsort",
"(",
"pressure",
")",
"[",
":",
... | 47.735294 | 24.735294 |
def delete(self, key):
'''Removes the object named by `key` in `service`.
Args:
key: Key naming the object to remove.
'''
key = self._service_key(key)
self._service_ops['delete'](key) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"self",
".",
"_service_key",
"(",
"key",
")",
"self",
".",
"_service_ops",
"[",
"'delete'",
"]",
"(",
"key",
")"
] | 25.375 | 18.875 |
def fs_c(self, percent=0.9, N=None):
"""Get the column factor scores (dimensionality-reduced representation),
choosing how many factors to retain, directly or based on the explained
variance.
'percent': The minimum variance that the retained factors are required
to explain (default: 90% = 0.9)
'N': T... | [
"def",
"fs_c",
"(",
"self",
",",
"percent",
"=",
"0.9",
",",
"N",
"=",
"None",
")",
":",
"if",
"not",
"0",
"<=",
"percent",
"<=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Percent should be a real number between 0 and 1.\"",
")",
"if",
"N",
":",
"if",
"no... | 43.925926 | 18.111111 |
def dispatch(self,request,*args,**kwargs):
'''
Handle the session data passed by the prior view.
'''
lessonSession = request.session.get(PRIVATELESSON_VALIDATION_STR,{})
try:
self.lesson = PrivateLessonEvent.objects.get(id=lessonSession.get('lesson'))
except... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lessonSession",
"=",
"request",
".",
"session",
".",
"get",
"(",
"PRIVATELESSON_VALIDATION_STR",
",",
"{",
"}",
")",
"try",
":",
"self",
".",
"lesson"... | 46.55 | 31.15 |
def wrap (text, width, **kwargs):
"""Adjust lines of text to be not longer than width. The text will be
returned unmodified if width <= 0.
See textwrap.wrap() for a list of supported kwargs.
Returns text with lines no longer than given width."""
if width <= 0 or not text:
return text
ret... | [
"def",
"wrap",
"(",
"text",
",",
"width",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"width",
"<=",
"0",
"or",
"not",
"text",
":",
"return",
"text",
"ret",
"=",
"[",
"]",
"for",
"para",
"in",
"get_paragraphs",
"(",
"text",
")",
":",
"text",
"=",
... | 40.583333 | 9.666667 |
def twovec(axdef, indexa, plndef, indexp):
"""
Find the transformation to the right-handed frame having a
given vector as a specified axis and having a second given
vector lying in a specified coordinate plane.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/twovec_c.html
:param axdef:... | [
"def",
"twovec",
"(",
"axdef",
",",
"indexa",
",",
"plndef",
",",
"indexp",
")",
":",
"axdef",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"axdef",
")",
"indexa",
"=",
"ctypes",
".",
"c_int",
"(",
"indexa",
")",
"plndef",
"=",
"stypes",
".",
"toDoubleVe... | 39.961538 | 13.423077 |
def load_grid(self, alpha):
'''Load grid and calculate alpha values from the coverage/2.5.
'''
grid = CRGrid.crt_grid(self.dirs[0] + '/grid/elem.dat',
self.dirs[0] + '/grid/elec.dat')
self.plotman = CRPlot.plotManager(grid=grid)
name = self.dirs[0]... | [
"def",
"load_grid",
"(",
"self",
",",
"alpha",
")",
":",
"grid",
"=",
"CRGrid",
".",
"crt_grid",
"(",
"self",
".",
"dirs",
"[",
"0",
"]",
"+",
"'/grid/elem.dat'",
",",
"self",
".",
"dirs",
"[",
"0",
"]",
"+",
"'/grid/elec.dat'",
")",
"self",
".",
"... | 43.111111 | 18.666667 |
def post(hosts=None, services=None, check_existance=True, create_services=True, create_hosts=False):
""" Puts a list of hosts into local instance of nagios checkresults
Arguments:
hosts -- list of dicts, like one obtained from get_checkresults
services -- list of dicts, like... | [
"def",
"post",
"(",
"hosts",
"=",
"None",
",",
"services",
"=",
"None",
",",
"check_existance",
"=",
"True",
",",
"create_services",
"=",
"True",
",",
"create_hosts",
"=",
"False",
")",
":",
"nagios_config",
"=",
"config",
"(",
")",
"nagios_config",
".",
... | 39.794872 | 26.923077 |
def matches(self, spec):
"""
Matches a specification against the current Plot.
"""
if callable(spec) and not isinstance(spec, type): return spec(self)
elif isinstance(spec, type): return isinstance(self, spec)
else:
raise ValueError("Matching specs have to be ... | [
"def",
"matches",
"(",
"self",
",",
"spec",
")",
":",
"if",
"callable",
"(",
"spec",
")",
"and",
"not",
"isinstance",
"(",
"spec",
",",
"type",
")",
":",
"return",
"spec",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"spec",
",",
"type",
")",
":",
... | 42.875 | 20.875 |
def get_best_gain(mapping, candidate_mappings, weight_dict, instance_len, cur_match_num):
"""
Hill-climbing method to return the best gain swap/move can get
Arguments:
mapping: current node mapping
candidate_mappings: the candidates mapping list
weight_dict: the weight dictionary
instance_le... | [
"def",
"get_best_gain",
"(",
"mapping",
",",
"candidate_mappings",
",",
"weight_dict",
",",
"instance_len",
",",
"cur_match_num",
")",
":",
"largest_gain",
"=",
"0",
"# True: using swap; False: using move",
"use_swap",
"=",
"True",
"# the node to be moved/swapped",
"node1... | 43 | 16.212121 |
def tell(self):
"""Return the current position in the stream (ignoring bit
position)
:returns: int for the position in the stream
"""
res = self._stream.tell()
if len(self._bits) > 0:
res -= 1
return res | [
"def",
"tell",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"_stream",
".",
"tell",
"(",
")",
"if",
"len",
"(",
"self",
".",
"_bits",
")",
">",
"0",
":",
"res",
"-=",
"1",
"return",
"res"
] | 26.3 | 15.8 |
def df_query(self, query, with_labels=False):
"""
Run a :mod:`sqlalchemy` query and return result as a :class:`pandas.DataFrame`
Args:
query (sqlalchemy.orm.query.Query): query object, usually generated by :func:`session.query()` in
an :class:`sqlalchemy.orm.session... | [
"def",
"df_query",
"(",
"self",
",",
"query",
",",
"with_labels",
"=",
"False",
")",
":",
"import",
"pandas",
"as",
"pd",
"if",
"with_labels",
":",
"query",
"=",
"query",
".",
"with_labels",
"(",
")",
"# compile sql statement, including arguments",
"statement",
... | 44.703704 | 33.444444 |
def specific_gains(string):
"""Convert string with gains of individual amplification elements to dict"""
if not string:
return {}
gains = {}
for gain in string.split(','):
amp_name, value = gain.split('=')
gains[amp_name.strip()] = float(value.strip())
return gains | [
"def",
"specific_gains",
"(",
"string",
")",
":",
"if",
"not",
"string",
":",
"return",
"{",
"}",
"gains",
"=",
"{",
"}",
"for",
"gain",
"in",
"string",
".",
"split",
"(",
"','",
")",
":",
"amp_name",
",",
"value",
"=",
"gain",
".",
"split",
"(",
... | 30.1 | 16.9 |
def load_file(self, input_file):
""" Loads data array from file (result of this converter)
Tries to import, load and replace files' data.
It will overwirte previously added items with #add_file or #load_file.
:param input_file
:type str or unicode
"""
pyimg = im... | [
"def",
"load_file",
"(",
"self",
",",
"input_file",
")",
":",
"pyimg",
"=",
"imp",
".",
"load_source",
"(",
"'image2py_taf'",
",",
"input_file",
")",
"self",
".",
"files",
"=",
"pyimg",
".",
"data",
"self",
".",
"set_template",
"(",
"templates",
".",
"te... | 37.5 | 18.5 |
def strip_seq_cntrl(self, idx):
"""strip(2 byte) wlan.seq(12 bit) and wlan.fram(4 bit)
number information.
:seq_cntrl: ctypes.Structure
:return: int
sequence number
:return: int
fragment number
"""
seq_cntrl = struct.unpack('H', self._packe... | [
"def",
"strip_seq_cntrl",
"(",
"self",
",",
"idx",
")",
":",
"seq_cntrl",
"=",
"struct",
".",
"unpack",
"(",
"'H'",
",",
"self",
".",
"_packet",
"[",
"idx",
":",
"idx",
"+",
"2",
"]",
")",
"[",
"0",
"]",
"seq_num",
"=",
"seq_cntrl",
">>",
"4",
"f... | 33.076923 | 10.692308 |
def best_other_class(logits, exclude):
"""Returns the index of the largest logit, ignoring the class that
is passed as `exclude`."""
other_logits = logits - onehot_like(logits, exclude, value=np.inf)
return np.argmax(other_logits) | [
"def",
"best_other_class",
"(",
"logits",
",",
"exclude",
")",
":",
"other_logits",
"=",
"logits",
"-",
"onehot_like",
"(",
"logits",
",",
"exclude",
",",
"value",
"=",
"np",
".",
"inf",
")",
"return",
"np",
".",
"argmax",
"(",
"other_logits",
")"
] | 51.6 | 7.6 |
def _general_multithread(func):
""" return the general multithreading function using func """
def multithread(templates, stream, *args, **kwargs):
with pool_boy(ThreadPool, len(stream), **kwargs) as pool:
return _pool_normxcorr(templates, stream, pool=pool, func=func)
return multithrea... | [
"def",
"_general_multithread",
"(",
"func",
")",
":",
"def",
"multithread",
"(",
"templates",
",",
"stream",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"pool_boy",
"(",
"ThreadPool",
",",
"len",
"(",
"stream",
")",
",",
"*",
"*",
"k... | 39.25 | 22.875 |
def create_objects_for_type(self, raw_objects, o_type):
"""Generic function to create objects regarding the o_type
This function create real Alignak objects from the raw data got from the configuration.
:param raw_objects: Raw objects
:type raw_objects: dict
:param o_type: the ... | [
"def",
"create_objects_for_type",
"(",
"self",
",",
"raw_objects",
",",
"o_type",
")",
":",
"# Ex: the above code do for timeperiods:",
"# timeperiods = []",
"# for timeperiodcfg in objects['timeperiod']:",
"# t = Timeperiod(timeperiodcfg)",
"# timeperiods.append(t)",
"# self.tim... | 36.526316 | 17.289474 |
def reset_params(self):
"""(Re)set all parameters."""
units = [N_FEATURES]
units += [self.hidden_units] * self.num_hidden
units += [N_CLASSES]
sequence = []
for u0, u1 in zip(units, units[1:]):
sequence.append(nn.Linear(u0, u1))
sequence.append(se... | [
"def",
"reset_params",
"(",
"self",
")",
":",
"units",
"=",
"[",
"N_FEATURES",
"]",
"units",
"+=",
"[",
"self",
".",
"hidden_units",
"]",
"*",
"self",
".",
"num_hidden",
"units",
"+=",
"[",
"N_CLASSES",
"]",
"sequence",
"=",
"[",
"]",
"for",
"u0",
",... | 32.571429 | 13.928571 |
def has_throttled(self):
"""
Check whether any of the CPU cores monitored by this instance has
throttled since this instance was created.
@return a boolean value
"""
for file, value in self.cpu_throttle_count.items():
try:
new_value = int(util.... | [
"def",
"has_throttled",
"(",
"self",
")",
":",
"for",
"file",
",",
"value",
"in",
"self",
".",
"cpu_throttle_count",
".",
"items",
"(",
")",
":",
"try",
":",
"new_value",
"=",
"int",
"(",
"util",
".",
"read_file",
"(",
"file",
")",
")",
"if",
"new_va... | 38.5 | 15.071429 |
def angle_to_cartesian(lon, lat):
"""Convert spherical coordinates to cartesian unit vectors."""
theta = np.array(np.pi / 2. - lat)
return np.vstack((np.sin(theta) * np.cos(lon),
np.sin(theta) * np.sin(lon),
np.cos(theta))).T | [
"def",
"angle_to_cartesian",
"(",
"lon",
",",
"lat",
")",
":",
"theta",
"=",
"np",
".",
"array",
"(",
"np",
".",
"pi",
"/",
"2.",
"-",
"lat",
")",
"return",
"np",
".",
"vstack",
"(",
"(",
"np",
".",
"sin",
"(",
"theta",
")",
"*",
"np",
".",
"... | 46 | 5 |
def visit_Identifier(self, node):
"""Mangle names."""
if not self._is_mangle_candidate(node):
return
name = node.value
symbol = node.scope.resolve(node.value)
if symbol is None:
return
mangled = symbol.scope.mangled.get(name)
if mangled is ... | [
"def",
"visit_Identifier",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"self",
".",
"_is_mangle_candidate",
"(",
"node",
")",
":",
"return",
"name",
"=",
"node",
".",
"value",
"symbol",
"=",
"node",
".",
"scope",
".",
"resolve",
"(",
"node",
".",
... | 32 | 10.818182 |
def forward(self, inputs, begin_state): # pylint: disable=arguments-differ
"""Implement forward computation.
Parameters
-----------
inputs : NDArray
input tensor with shape `(sequence_length, batch_size)`
when `layout` is "TNC".
begin_state : list
... | [
"def",
"forward",
"(",
"self",
",",
"inputs",
",",
"begin_state",
")",
":",
"# pylint: disable=arguments-differ",
"encoded",
"=",
"self",
".",
"embedding",
"(",
"inputs",
")",
"length",
"=",
"inputs",
".",
"shape",
"[",
"0",
"]",
"batch_size",
"=",
"inputs",... | 42.59375 | 20.71875 |
def _load_db():
"""Deserializes the script database from JSON."""
from os import path
from pyci.utility import get_json
global datapath, db
datapath = path.abspath(path.expanduser(settings.datafile))
vms("Deserializing DB from {}".format(datapath))
db = get_json(datapath, {"installed": [], "... | [
"def",
"_load_db",
"(",
")",
":",
"from",
"os",
"import",
"path",
"from",
"pyci",
".",
"utility",
"import",
"get_json",
"global",
"datapath",
",",
"db",
"datapath",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"expanduser",
"(",
"settings",
".",
"dataf... | 43 | 16.875 |
def nickmask(prefix: str, kwargs: Dict[str, Any]) -> None:
""" store nick, user, host in kwargs if prefix is correct format """
if "!" in prefix and "@" in prefix:
# From a user
kwargs["nick"], remainder = prefix.split("!", 1)
kwargs["user"], kwargs["host"] = remainder.split("@", 1)
... | [
"def",
"nickmask",
"(",
"prefix",
":",
"str",
",",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"if",
"\"!\"",
"in",
"prefix",
"and",
"\"@\"",
"in",
"prefix",
":",
"# From a user",
"kwargs",
"[",
"\"nick\"",
"]",
",",
... | 43.555556 | 13.333333 |
def predict_step(F, covX, filt):
"""Predictive step of Kalman filter.
Parameters
----------
F: (dx, dx) numpy array
Mean of X_t | X_{t-1} is F * X_{t-1}
covX: (dx, dx) numpy array
covariance of X_t | X_{t-1}
filt: MeanAndCov object
filtering distribution at time t-1
... | [
"def",
"predict_step",
"(",
"F",
",",
"covX",
",",
"filt",
")",
":",
"pred_mean",
"=",
"np",
".",
"matmul",
"(",
"filt",
".",
"mean",
",",
"F",
".",
"T",
")",
"pred_cov",
"=",
"dotdot",
"(",
"F",
",",
"filt",
".",
"cov",
",",
"F",
".",
"T",
"... | 27.48 | 16.8 |
def color_features(in_objectinfo,
deredden=True,
custom_bandpasses=None,
dust_timeout=10.0):
'''Stellar colors and dereddened stellar colors using 2MASS DUST API:
http://irsa.ipac.caltech.edu/applications/DUST/docs/dustProgramInterface.html
Paramete... | [
"def",
"color_features",
"(",
"in_objectinfo",
",",
"deredden",
"=",
"True",
",",
"custom_bandpasses",
"=",
"None",
",",
"dust_timeout",
"=",
"10.0",
")",
":",
"objectinfo",
"=",
"in_objectinfo",
".",
"copy",
"(",
")",
"# this is the initial output dict",
"outdict... | 40.9275 | 25.4125 |
def get_parameter_infos(config_hpp):
"""Parse config header file.
Parameters
----------
config_hpp : string
Path to the config header file.
Returns
-------
infos : tuple
Tuple with names and content of sections.
"""
is_inparameter = False
parameter_group = None
... | [
"def",
"get_parameter_infos",
"(",
"config_hpp",
")",
":",
"is_inparameter",
"=",
"False",
"parameter_group",
"=",
"None",
"cur_key",
"=",
"None",
"cur_info",
"=",
"{",
"}",
"keys",
"=",
"[",
"]",
"member_infos",
"=",
"[",
"]",
"with",
"open",
"(",
"config... | 37.727273 | 12.227273 |
def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
"""
fpminfo = PHPfpmInfo(self._host, self._port, self._user, self._password,
self._monpath,... | [
"def",
"autoconf",
"(",
"self",
")",
":",
"fpminfo",
"=",
"PHPfpmInfo",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"self",
".",
"_user",
",",
"self",
".",
"_password",
",",
"self",
".",
"_monpath",
",",
"self",
".",
"_ssl",
")",
"re... | 39.777778 | 18.888889 |
def grant_symlink_privilege(who, machine=''):
"""
Grant the 'create symlink' privilege to who.
Based on http://support.microsoft.com/kb/132958
"""
flags = security.POLICY_CREATE_ACCOUNT | security.POLICY_LOOKUP_NAMES
policy = OpenPolicy(machine, flags)
return policy | [
"def",
"grant_symlink_privilege",
"(",
"who",
",",
"machine",
"=",
"''",
")",
":",
"flags",
"=",
"security",
".",
"POLICY_CREATE_ACCOUNT",
"|",
"security",
".",
"POLICY_LOOKUP_NAMES",
"policy",
"=",
"OpenPolicy",
"(",
"machine",
",",
"flags",
")",
"return",
"p... | 29.555556 | 13.111111 |
def make_update(cls, table, set_query, where=None):
"""
Make UPDATE query.
:param str table: Table name of executing the query.
:param str set_query: SET part of the UPDATE query.
:param str where:
Add a WHERE clause to execute query,
if the value is not ... | [
"def",
"make_update",
"(",
"cls",
",",
"table",
",",
"set_query",
",",
"where",
"=",
"None",
")",
":",
"validate_table_name",
"(",
"table",
")",
"if",
"typepy",
".",
"is_null_string",
"(",
"set_query",
")",
":",
"raise",
"ValueError",
"(",
"\"SET query is nu... | 36.4 | 17.04 |
def protected_adminview_factory(base_class):
"""Factory for creating protected admin view classes.
The factory will ensure that the admin view will check if a user is
authenticated and has the necessary permissions (as defined by the
permission factory).
The factory creates a new class using the pr... | [
"def",
"protected_adminview_factory",
"(",
"base_class",
")",
":",
"class",
"ProtectedAdminView",
"(",
"base_class",
")",
":",
"\"\"\"Admin view class protected by authentication.\"\"\"",
"def",
"_handle_view",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
"... | 46 | 20.181818 |
def index(request, template_name="index.html"):
"""\
The index view, which basically just displays a button and increments
a counter.
"""
if request.GET.get('ic-request'):
counter, created = Counter.objects.get_or_create(pk=1)
counter.value += 1
counter.save()
else:
... | [
"def",
"index",
"(",
"request",
",",
"template_name",
"=",
"\"index.html\"",
")",
":",
"if",
"request",
".",
"GET",
".",
"get",
"(",
"'ic-request'",
")",
":",
"counter",
",",
"created",
"=",
"Counter",
".",
"objects",
".",
"get_or_create",
"(",
"pk",
"="... | 31.5625 | 17.125 |
def write_dataframe(rows, encoding=ENCODING, dialect=DIALECT, **kwargs):
"""Dump ``rows`` to string buffer and load with ``pandas.read_csv()`` using ``kwargs``."""
global pandas
if pandas is None: # pragma: no cover
import pandas
with contextlib.closing(CsvBuffer()) as fd:
write_csv(fd,... | [
"def",
"write_dataframe",
"(",
"rows",
",",
"encoding",
"=",
"ENCODING",
",",
"dialect",
"=",
"DIALECT",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"pandas",
"if",
"pandas",
"is",
"None",
":",
"# pragma: no cover",
"import",
"pandas",
"with",
"contextlib",... | 43 | 15.8 |
def read(self, vals):
"""Read values.
Args:
vals (list): list of strings representing values
"""
i = 0
count = int(vals[i])
i += 1
for _ in range(count):
obj = DesignCondition()
obj.read(vals[i:i + obj.field_count])
... | [
"def",
"read",
"(",
"self",
",",
"vals",
")",
":",
"i",
"=",
"0",
"count",
"=",
"int",
"(",
"vals",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"for",
"_",
"in",
"range",
"(",
"count",
")",
":",
"obj",
"=",
"DesignCondition",
"(",
")",
"obj",
".",
... | 24.733333 | 16.333333 |
def fetch_exac_constraint():
"""Fetch the file with exac constraint scores
Returns:
exac_lines(iterable(str))
"""
file_name = 'fordist_cleaned_exac_r03_march16_z_pli_rec_null_data.txt'
url = ('ftp://ftp.broadinstitute.org/pub/ExAC_release/release0.3/functional_gene_constraint'
... | [
"def",
"fetch_exac_constraint",
"(",
")",
":",
"file_name",
"=",
"'fordist_cleaned_exac_r03_march16_z_pli_rec_null_data.txt'",
"url",
"=",
"(",
"'ftp://ftp.broadinstitute.org/pub/ExAC_release/release0.3/functional_gene_constraint'",
"'/{0}'",
")",
".",
"format",
"(",
"file_name",
... | 36.086957 | 24.26087 |
def visit_ListComp(self, node: ast.ListComp) -> Any:
"""Compile the list comprehension as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
re... | [
"def",
"visit_ListComp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"ListComp",
")",
"->",
"Any",
":",
"result",
"=",
"self",
".",
"_execute_comprehension",
"(",
"node",
"=",
"node",
")",
"for",
"generator",
"in",
"node",
".",
"generators",
":",
"self",
... | 35.888889 | 14.888889 |
def convert_images(image_list, image_format="png", timeout=20):
"""Convert images from list of images to given format, if needed.
Figure out the types of the images that were extracted from
the tarball and determine how to convert them into PNG.
:param: image_list ([string, string, ...]): the list of ... | [
"def",
"convert_images",
"(",
"image_list",
",",
"image_format",
"=",
"\"png\"",
",",
"timeout",
"=",
"20",
")",
":",
"png_output_contains",
"=",
"'PNG image'",
"image_mapping",
"=",
"{",
"}",
"for",
"image_file",
"in",
"image_list",
":",
"if",
"os",
".",
"p... | 40.837209 | 21.255814 |
def _handle_redirect(self, r, **kwargs):
"""Reset auth_attempted on redirects."""
if r.is_redirect:
self._thread_local.auth_attempted = False | [
"def",
"_handle_redirect",
"(",
"self",
",",
"r",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"r",
".",
"is_redirect",
":",
"self",
".",
"_thread_local",
".",
"auth_attempted",
"=",
"False"
] | 41.5 | 7 |
def _save_multi(data, file_name, sep=";"):
"""convenience function for storing data column-wise in a csv-file."""
logger.debug("saving multi")
with open(file_name, "w", newline='') as f:
logger.debug(f"{file_name} opened")
writer = csv.writer(f, delimiter=sep)
try:
writer... | [
"def",
"_save_multi",
"(",
"data",
",",
"file_name",
",",
"sep",
"=",
"\";\"",
")",
":",
"logger",
".",
"debug",
"(",
"\"saving multi\"",
")",
"with",
"open",
"(",
"file_name",
",",
"\"w\"",
",",
"newline",
"=",
"''",
")",
"as",
"f",
":",
"logger",
"... | 46.083333 | 12.583333 |
def NamedDict(name, fields, description=None, type_attributes=DEFAULT_TYPE_ATTRIBUTES):
'''
A :py:class:`Dict` with a name allowing it to be referenced by that name.
'''
check_user_facing_fields_dict(fields, 'NamedDict named "{}"'.format(name))
class _NamedDict(_ConfigComposite):
def __init... | [
"def",
"NamedDict",
"(",
"name",
",",
"fields",
",",
"description",
"=",
"None",
",",
"type_attributes",
"=",
"DEFAULT_TYPE_ATTRIBUTES",
")",
":",
"check_user_facing_fields_dict",
"(",
"fields",
",",
"'NamedDict named \"{}\"'",
".",
"format",
"(",
"name",
")",
")"... | 33.529412 | 22.352941 |
def classify(self, text):
"""
Chooses the highest scoring category for a sample of text
:param text: sample text to classify
:type text: str
:return: the "winning" category
:rtype: str
"""
score = self.score(text)
if not score:
return ... | [
"def",
"classify",
"(",
"self",
",",
"text",
")",
":",
"score",
"=",
"self",
".",
"score",
"(",
"text",
")",
"if",
"not",
"score",
":",
"return",
"None",
"return",
"sorted",
"(",
"score",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"v",
":... | 28.923077 | 14.615385 |
def cmd_search(*args):
"""
Arguments: <keyword1> [<keyword2> [<keyword3> [...]]]
List the documents containing the keywords.
Syntax is the same than with the search field in Paperwork-gui.
Search "" (empty string) to get all the documents.
Example: 'label:contrat AND paperwork'
Possible ... | [
"def",
"cmd_search",
"(",
"*",
"args",
")",
":",
"dsearch",
"=",
"get_docsearch",
"(",
")",
"verbose",
"(",
"\"Search: {}\"",
".",
"format",
"(",
"\" \"",
".",
"join",
"(",
"args",
")",
")",
")",
"r",
"=",
"{",
"'results'",
":",
"[",
"]",
"}",
"doc... | 27.404762 | 21.404762 |
def write(self, filename, compress=True, catalog_format="QUAKEML"):
"""
Write the tribe to a file using tar archive formatting.
:type filename: str
:param filename:
Filename to write to, if it exists it will be appended to.
:type compress: bool
:param compres... | [
"def",
"write",
"(",
"self",
",",
"filename",
",",
"compress",
"=",
"True",
",",
"catalog_format",
"=",
"\"QUAKEML\"",
")",
":",
"if",
"catalog_format",
"not",
"in",
"CAT_EXT_MAP",
".",
"keys",
"(",
")",
":",
"raise",
"TypeError",
"(",
"\"{0} is not supporte... | 40.577778 | 17.288889 |
def to_json(self):
"""Serialize an object to JSON based on its "properties" class
attribute.
:rtype: string"""
j = {}
for p in self.properties:
try:
v = getattr(self, p)
except AttributeError:
continue
if v is ... | [
"def",
"to_json",
"(",
"self",
")",
":",
"j",
"=",
"{",
"}",
"for",
"p",
"in",
"self",
".",
"properties",
":",
"try",
":",
"v",
"=",
"getattr",
"(",
"self",
",",
"p",
")",
"except",
"AttributeError",
":",
"continue",
"if",
"v",
"is",
"not",
"None... | 25.894737 | 16.789474 |
def get_assessments_metadata(self):
"""Gets the metadata for the assessments.
return: (osid.Metadata) - metadata for the assessments
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.learning.ActivityForm.get_assets_metadata_te... | [
"def",
"get_assessments_metadata",
"(",
"self",
")",
":",
"# Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_mdata",
"[",
"'assessments'",
"]",
")",
"metadata",
".",
"update",
"(",
"{",
... | 44.727273 | 22.909091 |
def observe(matcher):
"""
Internal decorator to trigger operator hooks before/after
matcher execution.
"""
@functools.wraps(matcher)
def observer(self, subject, *expected, **kw):
# Trigger before hook, if present
if hasattr(self, 'before'):
... | [
"def",
"observe",
"(",
"matcher",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"matcher",
")",
"def",
"observer",
"(",
"self",
",",
"subject",
",",
"*",
"expected",
",",
"*",
"*",
"kw",
")",
":",
"# Trigger before hook, if present",
"if",
"hasattr",
"(... | 35.935484 | 18.387097 |
def SetName(obj, name):
"""A compatibility wrapper for setting object's name.
See documentation for `GetName` for more information.
Args:
obj: A type or function object to set the name for.
name: A name to set.
"""
# Not doing type assertion on obj, since it may be a mock object used
# in tests.
... | [
"def",
"SetName",
"(",
"obj",
",",
"name",
")",
":",
"# Not doing type assertion on obj, since it may be a mock object used",
"# in tests.",
"precondition",
".",
"AssertType",
"(",
"name",
",",
"str",
")",
"if",
"PY2",
":",
"obj",
".",
"__name__",
"=",
"name",
"."... | 24.823529 | 21.176471 |
def add_triples(self, ontol):
"""
Adds triples to an ontology object.
Currently assumes gocam/lego-style
"""
rg = self.rdfgraph
g = ontol.get_graph()
typemap = {}
inds = rg.subjects(RDF.type, OWL.NamedIndividual)
for s in inds:
for (s,... | [
"def",
"add_triples",
"(",
"self",
",",
"ontol",
")",
":",
"rg",
"=",
"self",
".",
"rdfgraph",
"g",
"=",
"ontol",
".",
"get_graph",
"(",
")",
"typemap",
"=",
"{",
"}",
"inds",
"=",
"rg",
".",
"subjects",
"(",
"RDF",
".",
"type",
",",
"OWL",
".",
... | 37.83871 | 14.225806 |
def write_satellites(self, *args):
"""
Write a satellite constellation record::
writer.write_satellites(datetime.time(12, 34, 56), [1, 2, 5, 22])
# -> F12345601020522
:param time: UTC time of the satellite constellation record (default:
:meth:`~datetime.date... | [
"def",
"write_satellites",
"(",
"self",
",",
"*",
"args",
")",
":",
"num_args",
"=",
"len",
"(",
"args",
")",
"if",
"num_args",
"not",
"in",
"(",
"1",
",",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid number of parameters received'",
")",
"if",
"... | 29 | 19 |
def _del_process(self, dwProcessId):
"""
Private method to remove a process object from the snapshot.
@type dwProcessId: int
@param dwProcessId: Global process ID.
"""
try:
aProcess = self.__processDict[dwProcessId]
del self.__processDict[dwProce... | [
"def",
"_del_process",
"(",
"self",
",",
"dwProcessId",
")",
":",
"try",
":",
"aProcess",
"=",
"self",
".",
"__processDict",
"[",
"dwProcessId",
"]",
"del",
"self",
".",
"__processDict",
"[",
"dwProcessId",
"]",
"except",
"KeyError",
":",
"aProcess",
"=",
... | 32.25 | 13.625 |
def _run_play(self, play):
''' run a list of tasks for a given pattern, in order '''
self.callbacks.on_play_start(play.name)
# if no hosts matches this play, drop out
if not self.inventory.list_hosts(play.hosts):
self.callbacks.on_no_hosts_matched()
return True
... | [
"def",
"_run_play",
"(",
"self",
",",
"play",
")",
":",
"self",
".",
"callbacks",
".",
"on_play_start",
"(",
"play",
".",
"name",
")",
"# if no hosts matches this play, drop out",
"if",
"not",
"self",
".",
"inventory",
".",
"list_hosts",
"(",
"play",
".",
"h... | 36.552239 | 18.940299 |
def validate(self, value, messages=None, prefix=None):
"""validate(value[, messages[, prefix]]) -> True | False
Validates the given value according to this PrimitiveType
definition. Validation error messages are appended to an optional
messages array, each with the optional message pre... | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"messages",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"valid",
"=",
"False",
"def",
"log",
"(",
"msg",
")",
":",
"if",
"messages",
"is",
"not",
"None",
":",
"if",
"prefix",
"is",
"not",
... | 39.939394 | 20.272727 |
def get_action(self, parent, undo_stack: QUndoStack, sel_range, protocol: ProtocolAnalyzer, view: int):
"""
:type parent: QTableView
:type undo_stack: QUndoStack
:type protocol_analyzers: list of ProtocolAnalyzer
"""
min_row, max_row, start, end = sel_range
if min... | [
"def",
"get_action",
"(",
"self",
",",
"parent",
",",
"undo_stack",
":",
"QUndoStack",
",",
"sel_range",
",",
"protocol",
":",
"ProtocolAnalyzer",
",",
"view",
":",
"int",
")",
":",
"min_row",
",",
"max_row",
",",
"start",
",",
"end",
"=",
"sel_range",
"... | 38.857143 | 20.571429 |
def rank(matrix, atol=1e-13, rtol=0):
"""
Estimate the rank, i.e., the dimension of the column space, of a matrix.
The algorithm used by this function is based on the singular value
decomposition of `stoichiometry_matrix`.
Parameters
----------
matrix : ndarray
The matrix should be... | [
"def",
"rank",
"(",
"matrix",
",",
"atol",
"=",
"1e-13",
",",
"rtol",
"=",
"0",
")",
":",
"matrix",
"=",
"np",
".",
"atleast_2d",
"(",
"matrix",
")",
"sigma",
"=",
"svd",
"(",
"matrix",
",",
"compute_uv",
"=",
"False",
")",
"tol",
"=",
"max",
"("... | 30.533333 | 23.066667 |
def create_status(self, state, target_url=github.GithubObject.NotSet, description=github.GithubObject.NotSet, context=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/statuses/:sha <http://developer.github.com/v3/repos/statuses>`_
:param state: string
:param target_url:... | [
"def",
"create_status",
"(",
"self",
",",
"state",
",",
"target_url",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"description",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"context",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",... | 54.107143 | 26.964286 |
def tofile(path=""):
"""Instead of printing to a screen print to a file
:Example:
with pout.tofile("/path/to/file.txt"):
# all pout calls in this with block will print to file.txt
pout.v("a string")
pout.b()
pout.h()
:param path: str, a path to the f... | [
"def",
"tofile",
"(",
"path",
"=",
"\"\"",
")",
":",
"if",
"not",
"path",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"\"{}.txt\"",
".",
"format",
"(",
"__name__",
")",
")",
"global",
"stream",
"orig... | 23.583333 | 22.625 |
def resolve(self, *pargs, **kwargs):
"""Resolve the promise."""
self._cached = (pargs, kwargs)
self._try_then() | [
"def",
"resolve",
"(",
"self",
",",
"*",
"pargs",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_cached",
"=",
"(",
"pargs",
",",
"kwargs",
")",
"self",
".",
"_try_then",
"(",
")"
] | 33 | 5.5 |
def _map_or_starmap(function, iterable, args, kwargs, map_or_starmap):
"""
Shared function between parmap.map and parmap.starmap.
Refer to those functions for details.
"""
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"),
("pool", "pm_pool"), ("processes", "... | [
"def",
"_map_or_starmap",
"(",
"function",
",",
"iterable",
",",
"args",
",",
"kwargs",
",",
"map_or_starmap",
")",
":",
"arg_newarg",
"=",
"(",
"(",
"\"parallel\"",
",",
"\"pm_parallel\"",
")",
",",
"(",
"\"chunksize\"",
",",
"\"pm_chunksize\"",
")",
",",
"... | 43.592593 | 16.740741 |
def create_float(self, value: float) -> Float:
"""
Creates a new :class:`ConstantFloat`, adding it to the pool and
returning it.
:param value: The value of the new float.
"""
self.append((4, value))
return self.get(self.raw_count - 1) | [
"def",
"create_float",
"(",
"self",
",",
"value",
":",
"float",
")",
"->",
"Float",
":",
"self",
".",
"append",
"(",
"(",
"4",
",",
"value",
")",
")",
"return",
"self",
".",
"get",
"(",
"self",
".",
"raw_count",
"-",
"1",
")"
] | 31.444444 | 13 |
def register(self, resource_name, dependent=None):
'''
Register the given dependent as depending on the "resource"
named by resource_name.
'''
if dependent is None:
# Give a partial usable as a decorator
return partial(self.register, resource_name)
... | [
"def",
"register",
"(",
"self",
",",
"resource_name",
",",
"dependent",
"=",
"None",
")",
":",
"if",
"dependent",
"is",
"None",
":",
"# Give a partial usable as a decorator",
"return",
"partial",
"(",
"self",
".",
"register",
",",
"resource_name",
")",
"dependen... | 37.266667 | 20.466667 |
def get_airport_metars(self, iata, page=1, limit=100):
"""Retrieve the metar data at the current time
Given the IATA code of an airport, this method returns the metar information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number;... | [
"def",
"get_airport_metars",
"(",
"self",
",",
"iata",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"url",
"=",
"AIRPORT_DATA_BASE",
".",
"format",
"(",
"iata",
",",
"str",
"(",
"self",
".",
"AUTH_TOKEN",
")",
",",
"page",
",",
"limit",... | 35.92 | 25.16 |
def apply_chromatic_adaptation_on_color(color, targ_illum, adaptation='bradford'):
"""
Convenience function to apply an adaptation directly to a Color object.
"""
xyz_x = color.xyz_x
xyz_y = color.xyz_y
xyz_z = color.xyz_z
orig_illum = color.illuminant
targ_illum = targ_illum.lower()
... | [
"def",
"apply_chromatic_adaptation_on_color",
"(",
"color",
",",
"targ_illum",
",",
"adaptation",
"=",
"'bradford'",
")",
":",
"xyz_x",
"=",
"color",
".",
"xyz_x",
"xyz_y",
"=",
"color",
".",
"xyz_y",
"xyz_z",
"=",
"color",
".",
"xyz_z",
"orig_illum",
"=",
"... | 33.894737 | 17.052632 |
def split(text: str) -> List[str]:
"""Split a text into a list of tokens.
:param text: the text to split
:return: tokens
"""
return [word for word in SEPARATOR.split(text) if word.strip(' \t')] | [
"def",
"split",
"(",
"text",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"word",
"for",
"word",
"in",
"SEPARATOR",
".",
"split",
"(",
"text",
")",
"if",
"word",
".",
"strip",
"(",
"' \\t'",
")",
"]"
] | 29.714286 | 15 |
def mdot_t(self,ifig=None,lims=[7.4,2.6,-8.5,-4.5],label=None,colour=None,s2ms=False,
dashes=None):
"""
Plot mass loss history as a function of log-time-left
Parameters
----------
ifig : integer or string
Figure label, if None the current figure is use... | [
"def",
"mdot_t",
"(",
"self",
",",
"ifig",
"=",
"None",
",",
"lims",
"=",
"[",
"7.4",
",",
"2.6",
",",
"-",
"8.5",
",",
"-",
"4.5",
"]",
",",
"label",
"=",
"None",
",",
"colour",
"=",
"None",
",",
"s2ms",
"=",
"False",
",",
"dashes",
"=",
"No... | 29.882353 | 15.882353 |
def on_lxml_loads(self, lxml, config, content, **kwargs):
""" The `lxml <https://pypi.org/project/lxml/>`_ loads method.
:param module lxml: The ``lxml`` module
:param class config: The loading config class
:param str content: The content to deserialize
:param str encoding: The ... | [
"def",
"on_lxml_loads",
"(",
"self",
",",
"lxml",
",",
"config",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"# NOTE: lazy import of XMLParser because class requires lxml to exist on import",
"from",
".",
".",
"contrib",
".",
"xml_parser",
"import",
"XMLParser"... | 40.277778 | 20 |
def list(self, all_pages=False, **kwargs):
"""Return a list of objects.
If one or more filters are provided through keyword arguments, filter the results accordingly.
If no filters are provided, return all results.
=====API DOCS=====
Retrieve a list of objects.
:param... | [
"def",
"list",
"(",
"self",
",",
"all_pages",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Move to a field callback method to make it generic",
"# If multiple statuses where given, add OR queries for each of them",
"if",
"kwargs",
".",
"get",
"(",
"'status'",
... | 42 | 23.12069 |
def from_folder(cls, path:PathOrStr, train:PathOrStr='train', valid:PathOrStr='valid',
valid_pct=None, classes:Collection=None, **kwargs:Any)->'ImageDataBunch':
"Create from imagenet style dataset in `path` with `train`,`valid`,`test` subfolders (or provide `valid_pct`)."
path=Path(p... | [
"def",
"from_folder",
"(",
"cls",
",",
"path",
":",
"PathOrStr",
",",
"train",
":",
"PathOrStr",
"=",
"'train'",
",",
"valid",
":",
"PathOrStr",
"=",
"'valid'",
",",
"valid_pct",
"=",
"None",
",",
"classes",
":",
"Collection",
"=",
"None",
",",
"*",
"*... | 65.777778 | 29.555556 |
def pop(self):
'''
Pop an event from the queue. The event in the queue with higher priority is popped before ones in lower priority.
If there are multiple queues with the same priority, events are taken in turn from each queue.
May return some queueEvents indicating that some of the queu... | [
"def",
"pop",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"_pop",
"(",
")",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"pr",
"=",
"self",
".",
"parent",
".",
"notifyPop",
"(",
"self",
")",
"ret",
"[",
"1",
"]",
".",
"extend",
... | 52.266667 | 35.466667 |
def _handle_loads(cls, handler, content, validate=False, **kwargs):
""" Loads caller, used by partial method for dynamic handler assignments.
:param object handler: The loads handler
:param str content: The content to load from
:param bool validate: Performs content validation before loading,
d... | [
"def",
"_handle_loads",
"(",
"cls",
",",
"handler",
",",
"content",
",",
"validate",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"from_dict",
"(",
"cls",
",",
"handler",
".",
"loads",
"(",
"cls",
",",
"content",
",",
"*",
"*",
"kwargs"... | 40 | 18.833333 |
def _add_numeric_operations(cls):
"""
Add the operations to the cls; evaluate the doc strings again
"""
axis_descr, name, name2 = _doc_parms(cls)
cls.any = _make_logical_function(
cls, 'any', name, name2, axis_descr, _any_desc, nanops.nanany,
_any_see_al... | [
"def",
"_add_numeric_operations",
"(",
"cls",
")",
":",
"axis_descr",
",",
"name",
",",
"name2",
"=",
"_doc_parms",
"(",
"cls",
")",
"cls",
".",
"any",
"=",
"_make_logical_function",
"(",
"cls",
",",
"'any'",
",",
"name",
",",
"name2",
",",
"axis_descr",
... | 46.336 | 16.752 |
def print_object_attributes( thing, heading=None, file=None ):
'''
Print the attribute names in thing vertically
'''
if heading : print( '==', heading, '==', file=file )
print( '\n'.join( object_attributes( thing ) ), file=file ) | [
"def",
"print_object_attributes",
"(",
"thing",
",",
"heading",
"=",
"None",
",",
"file",
"=",
"None",
")",
":",
"if",
"heading",
":",
"print",
"(",
"'=='",
",",
"heading",
",",
"'=='",
",",
"file",
"=",
"file",
")",
"print",
"(",
"'\\n'",
".",
"join... | 40.666667 | 22.666667 |
def update(self, dt=None):
"""Simulate the model for a given time interval.
Parameters
----------
dt : Optional[float]
The time step to simulate, if None, the default built-in time step
is used.
"""
# EMELI passes dt = -1 so we need to handle that... | [
"def",
"update",
"(",
"self",
",",
"dt",
"=",
"None",
")",
":",
"# EMELI passes dt = -1 so we need to handle that here",
"dt",
"=",
"dt",
"if",
"(",
"dt",
"is",
"not",
"None",
"and",
"dt",
">",
"0",
")",
"else",
"self",
".",
"dt",
"tspan",
"=",
"[",
"0... | 38 | 16.047619 |
def download(self, force=False):
"""
Download file containing this package.
:param force: Force download even if it seems file already exists
:return: Full path with filename of downloaded package file.
"""
exists, dest_path = self._downloader.cache.exists_packed(package=... | [
"def",
"download",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"exists",
",",
"dest_path",
"=",
"self",
".",
"_downloader",
".",
"cache",
".",
"exists_packed",
"(",
"package",
"=",
"self",
",",
"pkg_path",
"=",
"self",
".",
"packed_path",
",",
"... | 40.388889 | 18.222222 |
def deposit(self, asset, amount, private_key):
"""
This function is a wrapper function around the create and execute deposit functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
depos... | [
"def",
"deposit",
"(",
"self",
",",
"asset",
",",
"amount",
",",
"private_key",
")",
":",
"create_deposit",
"=",
"self",
".",
"create_deposit",
"(",
"asset",
"=",
"asset",
",",
"amount",
"=",
"amount",
",",
"private_key",
"=",
"private_key",
")",
"return",... | 48.92 | 31.48 |
def ValidateAndReturnIntValue(value, allowed_values, default, allow_empty,
column_name=None, problems=None):
"""
Validates a value to be a valid integer in the list of allowed values:
- if no integer value adds InvalidValue error and returns the default value
- if integer but n... | [
"def",
"ValidateAndReturnIntValue",
"(",
"value",
",",
"allowed_values",
",",
"default",
",",
"allow_empty",
",",
"column_name",
"=",
"None",
",",
"problems",
"=",
"None",
")",
":",
"if",
"allow_empty",
"and",
"IsEmpty",
"(",
"value",
")",
":",
"return",
"de... | 36.441176 | 18.441176 |
def get_gene_seqs(database_path, gene):
"""
This function takes the database path and a gene name as inputs and
returns the gene sequence contained in the file given by the gene name
"""
gene_path = database_path + "/" + gene + ".fsa"
gene_seq = ""
# Open fasta file
with open(gene_path)... | [
"def",
"get_gene_seqs",
"(",
"database_path",
",",
"gene",
")",
":",
"gene_path",
"=",
"database_path",
"+",
"\"/\"",
"+",
"gene",
"+",
"\".fsa\"",
"gene_seq",
"=",
"\"\"",
"# Open fasta file",
"with",
"open",
"(",
"gene_path",
")",
"as",
"gene_file",
":",
"... | 33.5 | 12.785714 |
def __deprecate_defaults(
self,
new_func: str,
bg_blend: Any,
alignment: Any = ...,
clear: Any = ...,
) -> None:
"""Return the parameters needed to recreate the current default state.
"""
if not __debug__:
return
fg = self.default_... | [
"def",
"__deprecate_defaults",
"(",
"self",
",",
"new_func",
":",
"str",
",",
"bg_blend",
":",
"Any",
",",
"alignment",
":",
"Any",
"=",
"...",
",",
"clear",
":",
"Any",
"=",
"...",
",",
")",
"->",
"None",
":",
"if",
"not",
"__debug__",
":",
"return"... | 32.881356 | 15.508475 |
def _format_name_map(self, lon, lat):
''' Return the name of the map in the good format '''
if self.ppd in [4, 16, 64, 128]:
lolaname = '_'.join(['LDEM', str(self.ppd)])
elif self.ppd in [512]:
lolaname = '_'.join(
['LDEM', str(self.ppd), lat[0], lat[1], ... | [
"def",
"_format_name_map",
"(",
"self",
",",
"lon",
",",
"lat",
")",
":",
"if",
"self",
".",
"ppd",
"in",
"[",
"4",
",",
"16",
",",
"64",
",",
"128",
"]",
":",
"lolaname",
"=",
"'_'",
".",
"join",
"(",
"[",
"'LDEM'",
",",
"str",
"(",
"self",
... | 39.111111 | 16.222222 |
def collision_integral_Neufeld_Janzen_Aziz(Tstar, l=1, s=1):
r'''Calculates Lennard-Jones collision integral for any of 16 values of
(l,j) for the wide range of 0.3 < Tstar < 100. Values are accurate to
0.1 % of actual values, but the calculation of actual values is
computationally intensive and so thes... | [
"def",
"collision_integral_Neufeld_Janzen_Aziz",
"(",
"Tstar",
",",
"l",
"=",
"1",
",",
"s",
"=",
"1",
")",
":",
"if",
"(",
"l",
",",
"s",
")",
"not",
"in",
"Neufeld_collision",
":",
"raise",
"Exception",
"(",
"'Input values of l and s are not supported'",
")"... | 33.370968 | 25.951613 |
def linear(self, limits=None, k=5):
"""Returns an ndarray of linear breaks."""
start, stop = limits or (self.minval, self.maxval)
return np.linspace(start, stop, k) | [
"def",
"linear",
"(",
"self",
",",
"limits",
"=",
"None",
",",
"k",
"=",
"5",
")",
":",
"start",
",",
"stop",
"=",
"limits",
"or",
"(",
"self",
".",
"minval",
",",
"self",
".",
"maxval",
")",
"return",
"np",
".",
"linspace",
"(",
"start",
",",
... | 46.25 | 6.25 |
def string_to_timestruct(input_string):
# type: (bytes) -> time.struct_time
'''
A cacheable function to take an input string and decode it into a
time.struct_time from the time module. If the string cannot be decoded
because of an illegal value, then the all-zero time.struct_time will be
return... | [
"def",
"string_to_timestruct",
"(",
"input_string",
")",
":",
"# type: (bytes) -> time.struct_time",
"try",
":",
"timestruct",
"=",
"time",
".",
"strptime",
"(",
"input_string",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"VolumeDescriptorDate",
".",
"TIME_FMT",
")",
... | 43.8 | 26.92 |
def watchpoint_info(self, handle=0, index=-1):
"""Returns information about the specified watchpoint.
Note:
Either ``handle`` or ``index`` can be specified. If the ``index``
is not provided, the ``handle`` must be set, and vice-versa. If
both ``index`` and ``handle`` are... | [
"def",
"watchpoint_info",
"(",
"self",
",",
"handle",
"=",
"0",
",",
"index",
"=",
"-",
"1",
")",
":",
"if",
"index",
"<",
"0",
"and",
"handle",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Handle must be provided if index is not set.'",
")",
"wp",
"=",
... | 38.394737 | 24 |
def pop_all(self):
"""
NON-BLOCKING POP ALL IN QUEUE, IF ANY
"""
with self.lock:
if self.please_stop:
return [THREAD_STOP]
if self.db.status.end == self.start:
return []
output = []
for i in range(self.start... | [
"def",
"pop_all",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"please_stop",
":",
"return",
"[",
"THREAD_STOP",
"]",
"if",
"self",
".",
"db",
".",
"status",
".",
"end",
"==",
"self",
".",
"start",
":",
"return",
"[",... | 27.8125 | 13.6875 |
def letter_score(letter):
"""Returns the Scrabble score of a letter.
Args:
letter: a single character string
Raises:
TypeError if a non-Scrabble character is supplied
"""
score_map = {
1: ["a", "e", "i", "o", "u", "l", "n", "r", "s", "t"],
2: ["d", "g"],
3:... | [
"def",
"letter_score",
"(",
"letter",
")",
":",
"score_map",
"=",
"{",
"1",
":",
"[",
"\"a\"",
",",
"\"e\"",
",",
"\"i\"",
",",
"\"o\"",
",",
"\"u\"",
",",
"\"l\"",
",",
"\"n\"",
",",
"\"r\"",
",",
"\"s\"",
",",
"\"t\"",
"]",
",",
"2",
":",
"[",
... | 24 | 19.48 |
def normalize_cpp_function(self, function, line):
"""Normalizes a single cpp frame with a function"""
# Drop member function cv/ref qualifiers like const, const&, &, and &&
for ref in ('const', 'const&', '&&', '&'):
if function.endswith(ref):
function = function[:-len... | [
"def",
"normalize_cpp_function",
"(",
"self",
",",
"function",
",",
"line",
")",
":",
"# Drop member function cv/ref qualifiers like const, const&, &, and &&",
"for",
"ref",
"in",
"(",
"'const'",
",",
"'const&'",
",",
"'&&'",
",",
"'&'",
")",
":",
"if",
"function",
... | 35.137255 | 19.156863 |
def unwrap(klass, value):
"""Unpack a Value into an augmented python type (selected from the 'value' field)
"""
assert isinstance(value, Value), value
V = value.value
try:
T = klass.typeMap[type(V)]
except KeyError:
raise ValueError("Can't unwrap v... | [
"def",
"unwrap",
"(",
"klass",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"Value",
")",
",",
"value",
"V",
"=",
"value",
".",
"value",
"try",
":",
"T",
"=",
"klass",
".",
"typeMap",
"[",
"type",
"(",
"V",
")",
"]",
"except... | 40.461538 | 16.769231 |
def _check_output(self, command):
"""Wrap the call to subprocess.check_output() to raise customized exceptions and always return strings."""
try:
if sys.version_info[0] > 2:
return check_output(self.base_command + command, stderr=STDOUT).decode('utf8')
else:
... | [
"def",
"_check_output",
"(",
"self",
",",
"command",
")",
":",
"try",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"return",
"check_output",
"(",
"self",
".",
"base_command",
"+",
"command",
",",
"stderr",
"=",
"STDOUT",
")",
... | 55.222222 | 20.111111 |
def explain(self, *args, **kwargs):
'''Return a string that describes how these args are interpreted'''
args = self.get(*args, **kwargs)
results = ['%s = %s' % (name, value) for name, value in args.required]
results.extend(['%s = %s (overridden)' % (
name, value) for name, va... | [
"def",
"explain",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"self",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"results",
"=",
"[",
"'%s = %s'",
"%",
"(",
"name",
",",
"value",
")",
"for",
... | 51.230769 | 17.538462 |
def loads(s, single=False, version=_default_version,
strict=False, errors='warn'):
"""
Deserialize SimpleMRS string representations
Args:
s (str): a SimpleMRS string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unles... | [
"def",
"loads",
"(",
"s",
",",
"single",
"=",
"False",
",",
"version",
"=",
"_default_version",
",",
"strict",
"=",
"False",
",",
"errors",
"=",
"'warn'",
")",
":",
"ms",
"=",
"deserialize",
"(",
"s",
",",
"version",
"=",
"version",
",",
"strict",
"=... | 29.5 | 18.875 |
def _aggregate(self, instanceId, container, value, subKey = None):
"""Performs stat aggregation."""
# Get the aggregator.
if instanceId not in self._aggregators:
self._aggregators[instanceId] = _Stats.getAggregator(instanceId, self.__name)
aggregator = self._aggregators[instanceId]
# If we a... | [
"def",
"_aggregate",
"(",
"self",
",",
"instanceId",
",",
"container",
",",
"value",
",",
"subKey",
"=",
"None",
")",
":",
"# Get the aggregator.",
"if",
"instanceId",
"not",
"in",
"self",
".",
"_aggregators",
":",
"self",
".",
"_aggregators",
"[",
"instance... | 37.3125 | 19.4375 |
def acquire(self, **kwargs):
"""
Copy the file and return its path
Returns
-------
str or None
The path of the file in BatchUp's temporary directory or None if
the copy failed.
"""
if self.source_path is None:
source_path = kwa... | [
"def",
"acquire",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"source_path",
"is",
"None",
":",
"source_path",
"=",
"kwargs",
"[",
"self",
".",
"arg_name",
"]",
"else",
":",
"source_path",
"=",
"self",
".",
"source_path",
"return... | 30.6 | 16.6 |
def remove_room_alias(self, room_alias):
"""Remove mapping of an alias
Args:
room_alias(str): The alias to be removed.
Returns:
bool: True if the alias is removed, False otherwise.
"""
try:
self.api.remove_room_alias(room_alias)
r... | [
"def",
"remove_room_alias",
"(",
"self",
",",
"room_alias",
")",
":",
"try",
":",
"self",
".",
"api",
".",
"remove_room_alias",
"(",
"room_alias",
")",
"return",
"True",
"except",
"MatrixRequestError",
":",
"return",
"False"
] | 26.928571 | 17.5 |
def find_matches(strings, words, length_hoped):
""" Used by default property excerpt """
lower_words = [w.lower() for w in words]
def has_match(string):
""" Do any of the words match within the string """
lower_string = string.lower()
for test_word in lower_w... | [
"def",
"find_matches",
"(",
"strings",
",",
"words",
",",
"length_hoped",
")",
":",
"lower_words",
"=",
"[",
"w",
".",
"lower",
"(",
")",
"for",
"w",
"in",
"words",
"]",
"def",
"has_match",
"(",
"string",
")",
":",
"\"\"\" Do any of the words match within th... | 35.4 | 15.04 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.