text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _line_opt(self):
"""Perform a line search along the current direction"""
direction = self.search_direction.direction
if self.constraints is not None:
try:
direction = self.constraints.project(self.x, direction)
except ConstraintError:
s... | [
"def",
"_line_opt",
"(",
"self",
")",
":",
"direction",
"=",
"self",
".",
"search_direction",
".",
"direction",
"if",
"self",
".",
"constraints",
"is",
"not",
"None",
":",
"try",
":",
"direction",
"=",
"self",
".",
"constraints",
".",
"project",
"(",
"se... | 40.638298 | 0.001534 |
def plot_monthly_returns_heatmap(returns, ax=None, **kwargs):
"""
Plots a heatmap of returns by month.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
... | [
"def",
"plot_monthly_returns_heatmap",
"(",
"returns",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"monthly_ret_table",
"=",
"ep",
".",
"aggregate_returns",
"(",
"ret... | 24.9 | 0.000966 |
def load(filepath=None, filecontent=None):
""" Read the json file located at `filepath`
If `filecontent` is specified, its content will be json decoded
and loaded instead.
Usage:
config.load(filepath=None, filecontent=None):
Provide either a filepath or a json string
"""
conf =... | [
"def",
"load",
"(",
"filepath",
"=",
"None",
",",
"filecontent",
"=",
"None",
")",
":",
"conf",
"=",
"DotDict",
"(",
")",
"assert",
"filepath",
"or",
"filecontent",
"if",
"not",
"filecontent",
":",
"with",
"io",
".",
"FileIO",
"(",
"filepath",
")",
"as... | 29.421053 | 0.001733 |
def user_search_results(self):
""" Add [member] to a user title if user is a member
of current workspace
"""
results = super(SharingView, self).user_search_results()
ws = IWorkspace(self.context)
roles_mapping = ws.available_groups
roles = roles_mapping.get(self.c... | [
"def",
"user_search_results",
"(",
"self",
")",
":",
"results",
"=",
"super",
"(",
"SharingView",
",",
"self",
")",
".",
"user_search_results",
"(",
")",
"ws",
"=",
"IWorkspace",
"(",
"self",
".",
"context",
")",
"roles_mapping",
"=",
"ws",
".",
"available... | 38.727273 | 0.002291 |
def generate_parser():
"""Returns a parser configured with sub-commands and arguments."""
parser = argparse.ArgumentParser(
description=constants.TACL_DESCRIPTION,
formatter_class=ParagraphFormatter)
subparsers = parser.add_subparsers(title='subcommands')
generate_align_subparser(subpars... | [
"def",
"generate_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"constants",
".",
"TACL_DESCRIPTION",
",",
"formatter_class",
"=",
"ParagraphFormatter",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(... | 42.73913 | 0.000995 |
def createPolyline(self, points, strokewidth=1, stroke='black'):
"""
Creates a Polyline
@type points: string in the form "x1,y1 x2,y2 x3,y3"
@param points: all points relevant to the polygon
@type strokewidth: string or int
@param strokewidth: width of the pen used to... | [
"def",
"createPolyline",
"(",
"self",
",",
"points",
",",
"strokewidth",
"=",
"1",
",",
"stroke",
"=",
"'black'",
")",
":",
"style_dict",
"=",
"{",
"'fill'",
":",
"'none'",
",",
"'stroke-width'",
":",
"strokewidth",
",",
"'stroke'",
":",
"stroke",
"}",
"... | 46.4375 | 0.009235 |
def find_window_id(pattern, method='mru', error='raise'):
"""
xprop -id 0x00a00007 | grep "WM_CLASS(STRING)"
"""
import utool as ut
winid_candidates = XCtrl.findall_window_ids(pattern)
if len(winid_candidates) == 0:
if error == 'raise':
availab... | [
"def",
"find_window_id",
"(",
"pattern",
",",
"method",
"=",
"'mru'",
",",
"error",
"=",
"'raise'",
")",
":",
"import",
"utool",
"as",
"ut",
"winid_candidates",
"=",
"XCtrl",
".",
"findall_window_ids",
"(",
"pattern",
")",
"if",
"len",
"(",
"winid_candidates... | 42.772727 | 0.002079 |
def is_sensor(self, sensorid, child_id=None):
"""Return True if a sensor and its child exist."""
ret = sensorid in self.sensors
if not ret:
_LOGGER.warning('Node %s is unknown', sensorid)
if ret and child_id is not None:
ret = child_id in self.sensors[sensorid].ch... | [
"def",
"is_sensor",
"(",
"self",
",",
"sensorid",
",",
"child_id",
"=",
"None",
")",
":",
"ret",
"=",
"sensorid",
"in",
"self",
".",
"sensors",
"if",
"not",
"ret",
":",
"_LOGGER",
".",
"warning",
"(",
"'Node %s is unknown'",
",",
"sensorid",
")",
"if",
... | 47.421053 | 0.002176 |
def plot(self,t=0.,min=-15.,max=15,ns=21,savefilename=None):
"""
NAME:
plot
PURPOSE:
plot the potential
INPUT:
t - time to evaluate the potential at
min - minimum x
max - maximum x
ns - grid in x
savefi... | [
"def",
"plot",
"(",
"self",
",",
"t",
"=",
"0.",
",",
"min",
"=",
"-",
"15.",
",",
"max",
"=",
"15",
",",
"ns",
"=",
"21",
",",
"savefilename",
"=",
"None",
")",
":",
"if",
"not",
"savefilename",
"==",
"None",
"and",
"os",
".",
"path",
".",
"... | 26.176471 | 0.018773 |
def _preallocate_samples(self):
"""Preallocate samples for faster adaptive sampling.
"""
self.prealloc_samples_ = []
for i in range(self.num_prealloc_samples_):
self.prealloc_samples_.append(self.sample()) | [
"def",
"_preallocate_samples",
"(",
"self",
")",
":",
"self",
".",
"prealloc_samples_",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_prealloc_samples_",
")",
":",
"self",
".",
"prealloc_samples_",
".",
"append",
"(",
"self",
".",
"sampl... | 40.666667 | 0.008032 |
def create_without_data(cls, id_):
"""
根据 objectId 创建一个 leancloud.Object,代表一个服务器上已经存在的对象。可以调用 fetch 方法来获取服务器上的数据
:param id_: 对象的 objectId
:type id_: string_types
:return: 没有数据的对象
:rtype: Object
"""
if cls is Object:
raise RuntimeError('can not... | [
"def",
"create_without_data",
"(",
"cls",
",",
"id_",
")",
":",
"if",
"cls",
"is",
"Object",
":",
"raise",
"RuntimeError",
"(",
"'can not call create_without_data on leancloud.Object'",
")",
"obj",
"=",
"cls",
"(",
")",
"obj",
".",
"id",
"=",
"id_",
"return",
... | 29.571429 | 0.009368 |
def on_copy_local(self, pair):
"""Called when the local resource should be copied to remote."""
status = pair.remote_classification
self._log_action("copy", status, ">", pair.local) | [
"def",
"on_copy_local",
"(",
"self",
",",
"pair",
")",
":",
"status",
"=",
"pair",
".",
"remote_classification",
"self",
".",
"_log_action",
"(",
"\"copy\"",
",",
"status",
",",
"\">\"",
",",
"pair",
".",
"local",
")"
] | 50.5 | 0.009756 |
def dig(obj, *keys):
"""
Return obj[key_1][key_2][...] for each key in keys, or None if any key
in the chain is not found
So, given this `obj`:
{
"banana": {
"cream": "pie"
}
}
dig(obj, "banana") -> {"cream": "pie"}
dig(obj, "banana", "cream") -> "pie"
... | [
"def",
"dig",
"(",
"obj",
",",
"*",
"keys",
")",
":",
"for",
"key",
"in",
"keys",
":",
"if",
"not",
"obj",
"or",
"key",
"not",
"in",
"obj",
":",
"return",
"None",
"obj",
"=",
"obj",
"[",
"key",
"]",
"return",
"obj"
] | 21.782609 | 0.001912 |
def plot_meshes(self, ax=None, marker='+', color='blue', outlines=False,
**kwargs):
"""
Plot the low-resolution mesh boxes on a matplotlib Axes
instance.
Parameters
----------
ax : `matplotlib.axes.Axes` instance, optional
If `None`, then ... | [
"def",
"plot_meshes",
"(",
"self",
",",
"ax",
"=",
"None",
",",
"marker",
"=",
"'+'",
",",
"color",
"=",
"'blue'",
",",
"outlines",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"kwargs",
"[",
... | 32.142857 | 0.002157 |
def richTextLabel(self):
"""
Returns the label that is used for drawing the rich text to this button.
:return <QLabel>
"""
if not self._richTextLabel:
self._richTextLabel = QLabel(self)
self._richTextLabel.installEventFilter(self)
... | [
"def",
"richTextLabel",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_richTextLabel",
":",
"self",
".",
"_richTextLabel",
"=",
"QLabel",
"(",
"self",
")",
"self",
".",
"_richTextLabel",
".",
"installEventFilter",
"(",
"self",
")",
"self",
".",
"_richT... | 35.272727 | 0.01005 |
def provides(self, call_name):
"""Provide a call.
The call acts as a stub -- no error is raised if it is not called.::
>>> session = Fake('session').provides('open').provides('close')
>>> import fudge
>>> fudge.clear_expectations() # from any previously declared fak... | [
"def",
"provides",
"(",
"self",
",",
"call_name",
")",
":",
"if",
"call_name",
"in",
"self",
".",
"_declared_calls",
":",
"return",
"self",
".",
"next_call",
"(",
"for_method",
"=",
"call_name",
")",
"self",
".",
"_last_declared_call_name",
"=",
"call_name",
... | 34.956522 | 0.002421 |
def save_model(self):
'''
Saves all of the de-trending information to disk in an `npz` file
and saves the DVS as a `pdf`.
'''
# Save the data
log.info("Saving data to '%s.npz'..." % self.name)
d = dict(self.__dict__)
d.pop('_weights', None)
d.pop... | [
"def",
"save_model",
"(",
"self",
")",
":",
"# Save the data",
"log",
".",
"info",
"(",
"\"Saving data to '%s.npz'...\"",
"%",
"self",
".",
"name",
")",
"d",
"=",
"dict",
"(",
"self",
".",
"__dict__",
")",
"d",
".",
"pop",
"(",
"'_weights'",
",",
"None",... | 31.029412 | 0.001838 |
def get_translations(self, locale):
"""
Get translation dictionary
Returns a dictionary for locale or raises an exception if such can't
be located. If a dictionary for locale was previously loaded returns
that, otherwise goes through registered locations and merges any
fo... | [
"def",
"get_translations",
"(",
"self",
",",
"locale",
")",
":",
"locale",
"=",
"self",
".",
"normalize_locale",
"(",
"locale",
")",
"if",
"locale",
"in",
"self",
".",
"translations",
":",
"return",
"self",
".",
"translations",
"[",
"locale",
"]",
"transla... | 36.717949 | 0.001361 |
def _message_to_entity(msg, modelclass):
"""Recursive helper for _to_base_type() to convert a message to an entity.
Args:
msg: A Message instance.
modelclass: A Model subclass.
Returns:
An instance of modelclass.
"""
ent = modelclass()
for prop_name, prop in modelclass._properties.iteritems():... | [
"def",
"_message_to_entity",
"(",
"msg",
",",
"modelclass",
")",
":",
"ent",
"=",
"modelclass",
"(",
")",
"for",
"prop_name",
",",
"prop",
"in",
"modelclass",
".",
"_properties",
".",
"iteritems",
"(",
")",
":",
"if",
"prop",
".",
"_code_name",
"==",
"'b... | 33.590909 | 0.010526 |
def tabular(client, records):
"""Format dataset files with a tabular output.
:param client: LocalClient instance.
:param records: Filtered collection.
"""
from renku.models._tabulate import tabulate
echo_via_pager(
tabulate(
records,
headers=OrderedDict((
... | [
"def",
"tabular",
"(",
"client",
",",
"records",
")",
":",
"from",
"renku",
".",
"models",
".",
"_tabulate",
"import",
"tabulate",
"echo_via_pager",
"(",
"tabulate",
"(",
"records",
",",
"headers",
"=",
"OrderedDict",
"(",
"(",
"(",
"'added'",
",",
"None",... | 25.157895 | 0.002016 |
def tt_qr(X, left_to_right=True):
"""
Orthogonalizes a TT tensor from left to right or
from right to left.
:param: X - thensor to orthogonalise
:param: direction - direction. May be 'lr/LR' or 'rl/RL'
for left/right orthogonalization
:return: X_orth, R - orthogonal tensor and right (... | [
"def",
"tt_qr",
"(",
"X",
",",
"left_to_right",
"=",
"True",
")",
":",
"# Get rid of redundant ranks (they cause technical difficulties).",
"X",
"=",
"X",
".",
"round",
"(",
"eps",
"=",
"0",
")",
"numDims",
"=",
"X",
".",
"d",
"coresX",
"=",
"tt",
".",
"te... | 35.979592 | 0.001657 |
def ingest(resource, xpath=".//tei:cRefPattern"):
""" Ingest a resource and store data in its instance
:param resource: XML node cRefPattern or list of them in ASC hierarchy order (deepest to highest, eg. lines to poem to book)
:type resource: [lxml.etree._Element]
:param xpath: XPath t... | [
"def",
"ingest",
"(",
"resource",
",",
"xpath",
"=",
"\".//tei:cRefPattern\"",
")",
":",
"if",
"len",
"(",
"resource",
")",
"==",
"0",
"and",
"isinstance",
"(",
"resource",
",",
"list",
")",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"resource",
"... | 36.242424 | 0.002443 |
def get_qiniu_config(name, default=None):
"""
Get configuration variable from environment variable
or django setting.py
"""
config = os.environ.get(name, getattr(settings, name, default))
if config is not None:
if isinstance(config, six.string_types):
return config.strip()
... | [
"def",
"get_qiniu_config",
"(",
"name",
",",
"default",
"=",
"None",
")",
":",
"config",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
",",
"getattr",
"(",
"settings",
",",
"name",
",",
"default",
")",
")",
"if",
"config",
"is",
"not",
"None",
... | 33.333333 | 0.001946 |
def _urlparse_qs(url):
"""
Parse a URL query string and return the components as a dictionary.
Based on the cgi.parse_qs method.This is a utility function provided
with urlparse so that users need not use cgi module for
parsing the url query string.
Arguments:
:type url: str
:param ur... | [
"def",
"_urlparse_qs",
"(",
"url",
")",
":",
"# Extract the query part from the URL.",
"querystring",
"=",
"urlparse",
"(",
"url",
")",
"[",
"4",
"]",
"# Split the query into name/value pairs.",
"pairs",
"=",
"[",
"s2",
"for",
"s1",
"in",
"querystring",
".",
"spli... | 28.78125 | 0.00105 |
def load(path, shuffle=True):
"""
Note:
If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader
and run deserialization as a mapper in parallel.
"""
df = LMDBData(path, shuffle=shuffle)
return MapData(df, lambda dp: l... | [
"def",
"load",
"(",
"path",
",",
"shuffle",
"=",
"True",
")",
":",
"df",
"=",
"LMDBData",
"(",
"path",
",",
"shuffle",
"=",
"shuffle",
")",
"return",
"MapData",
"(",
"df",
",",
"lambda",
"dp",
":",
"loads",
"(",
"dp",
"[",
"1",
"]",
")",
")"
] | 40.625 | 0.009036 |
def get_deposits(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#list-deposits"""
response = self._get('v2', 'accounts', account_id, 'deposits', params=params)
return self._make_api_object(response, Deposit) | [
"def",
"get_deposits",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"params",
")",
":",
"response",
"=",
"self",
".",
"_get",
"(",
"'v2'",
",",
"'accounts'",
",",
"account_id",
",",
"'deposits'",
",",
"params",
"=",
"params",
")",
"return",
"self",
"... | 62.75 | 0.011811 |
def cube(target, pore_diameter='pore.diameter', throat_area='throat.area'):
r"""
Calculates internal surface area of pore bodies assuming they are cubes
then subtracts the area of the neighboring throats.
Parameters
----------
target : OpenPNM Object
The object for which these values ar... | [
"def",
"cube",
"(",
"target",
",",
"pore_diameter",
"=",
"'pore.diameter'",
",",
"throat_area",
"=",
"'throat.area'",
")",
":",
"network",
"=",
"target",
".",
"project",
".",
"network",
"D",
"=",
"target",
"[",
"pore_diameter",
"]",
"Tn",
"=",
"network",
"... | 39.08 | 0.000999 |
def ssn(self, min_age=18, max_age=90):
"""
Returns a 10 digit Swedish SSN, "Personnummer".
It consists of 10 digits in the form YYMMDD-SSGQ, where
YYMMDD is the date of birth, SSS is a serial number
and Q is a control character (Luhn checksum).
http://en.wikipedia.org/w... | [
"def",
"ssn",
"(",
"self",
",",
"min_age",
"=",
"18",
",",
"max_age",
"=",
"90",
")",
":",
"def",
"_luhn_checksum",
"(",
"number",
")",
":",
"def",
"digits_of",
"(",
"n",
")",
":",
"return",
"[",
"int",
"(",
"d",
")",
"for",
"d",
"in",
"str",
"... | 39.142857 | 0.001425 |
def main(from_lang, to_lang, provider, secret_access_key, output_only, text):
"""
Python command line tool to make on line translations
\b
Example:
\b
\t $ translate-cli -t zh the book is on the table
\t 碗是在桌子上。
\b
Available languages:
\b
\t https://en.wikipedia.org/wiki/IS... | [
"def",
"main",
"(",
"from_lang",
",",
"to_lang",
",",
"provider",
",",
"secret_access_key",
",",
"output_only",
",",
"text",
")",
":",
"text",
"=",
"' '",
".",
"join",
"(",
"text",
")",
"kwargs",
"=",
"dict",
"(",
"from_lang",
"=",
"from_lang",
",",
"t... | 27.694444 | 0.000969 |
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
... | [
"def",
"image_meta_set",
"(",
"self",
",",
"image_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0103",
"nt_ks",
"=",
"self",
".",
"compute_conn",
"if",
"name",
":",
"for",
"image",
"in",
"nt_ks",
".",
... | 35.875 | 0.008489 |
def get_palette(samples, options, return_mask=False, kmeans_iter=40):
'''Extract the palette for the set of sampled RGB values. The first
palette entry is always the background color; the rest are determined
from foreground pixels by running K-means clustering. Returns the
palette, as well as a mask corresponding ... | [
"def",
"get_palette",
"(",
"samples",
",",
"options",
",",
"return_mask",
"=",
"False",
",",
"kmeans_iter",
"=",
"40",
")",
":",
"if",
"not",
"options",
".",
"quiet",
":",
"print",
"(",
"' getting palette...'",
")",
"bg_color",
"=",
"get_bg_color",
"(",
"... | 30.5 | 0.001222 |
def prepare_subprocess_cmd(subprocess_cmd):
"""Prepares a subprocess command by running --helpfull and masking flags.
Args:
subprocess_cmd: List[str], what would be passed into subprocess.call()
i.e. ['python', 'train.py', '--flagfile=flags']
Returns:
['python', 'train.py', '--... | [
"def",
"prepare_subprocess_cmd",
"(",
"subprocess_cmd",
")",
":",
"help_cmd",
"=",
"subprocess_cmd",
"+",
"[",
"'--helpfull'",
"]",
"help_output",
"=",
"subprocess",
".",
"run",
"(",
"help_cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"stdout"... | 42.047619 | 0.001107 |
def escape_latex(text):
r"""Escape characters of given text.
This function takes the given text and escapes characters
that have a special meaning in LaTeX: # $ % ^ & _ { } ~ \
"""
text = unicode(text.decode('utf-8'))
CHARS = {
'&': r'\&',
'%': r'\%',
'$': r'\$',
... | [
"def",
"escape_latex",
"(",
"text",
")",
":",
"text",
"=",
"unicode",
"(",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"CHARS",
"=",
"{",
"'&'",
":",
"r'\\&'",
",",
"'%'",
":",
"r'\\%'",
",",
"'$'",
":",
"r'\\$'",
",",
"'#'",
":",
"r'\\#'",
... | 26.47619 | 0.001736 |
def p_top(self, p):
"top : objectlist"
if DEBUG:
self.print_p(p)
p[0] = self.objectlist_flat(p[1], True) | [
"def",
"p_top",
"(",
"self",
",",
"p",
")",
":",
"if",
"DEBUG",
":",
"self",
".",
"print_p",
"(",
"p",
")",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"objectlist_flat",
"(",
"p",
"[",
"1",
"]",
",",
"True",
")"
] | 27.2 | 0.014286 |
def list(self):
"""Get a list of the names of the functions stored in this database."""
return [x["_id"] for x in self._db.system.js.find(projection=["_id"])] | [
"def",
"list",
"(",
"self",
")",
":",
"return",
"[",
"x",
"[",
"\"_id\"",
"]",
"for",
"x",
"in",
"self",
".",
"_db",
".",
"system",
".",
"js",
".",
"find",
"(",
"projection",
"=",
"[",
"\"_id\"",
"]",
")",
"]"
] | 57.333333 | 0.011494 |
def write_text(filename, tracklisting):
"""Handle writing tracklisting to text."""
print("Saving text file.")
try:
write_listing_to_textfile(filename + '.txt', tracklisting)
except IOError:
# if all else fails, just print listing
print("Cannot write text file to path: {}".format(... | [
"def",
"write_text",
"(",
"filename",
",",
"tracklisting",
")",
":",
"print",
"(",
"\"Saving text file.\"",
")",
"try",
":",
"write_listing_to_textfile",
"(",
"filename",
"+",
"'.txt'",
",",
"tracklisting",
")",
"except",
"IOError",
":",
"# if all else fails, just p... | 45 | 0.001815 |
def f_to_dict(self, copy=True):
"""Returns annotations as dictionary.
:param copy: Whether to return a shallow copy or the real thing (aka _dict).
"""
if copy:
return self._dict.copy()
else:
return self._dict | [
"def",
"f_to_dict",
"(",
"self",
",",
"copy",
"=",
"True",
")",
":",
"if",
"copy",
":",
"return",
"self",
".",
"_dict",
".",
"copy",
"(",
")",
"else",
":",
"return",
"self",
".",
"_dict"
] | 26.5 | 0.010949 |
def inputs(eval_data, data_dir, batch_size):
"""Construct input for CIFAR evaluation using the Reader ops.
Args:
eval_data: bool, indicating if one should use the train or eval data set.
data_dir: Path to the CIFAR-10 data directory.
batch_size: Number of images per batch.
Returns:
images: Image... | [
"def",
"inputs",
"(",
"eval_data",
",",
"data_dir",
",",
"batch_size",
")",
":",
"if",
"not",
"eval_data",
":",
"filenames",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"'data_batch_%d.bin'",
"%",
"i",
")",
"for",
"i",
"in",
"xrange... | 38.327273 | 0.012026 |
def use_comparative_gradebook_view(self):
"""Pass through to provider GradeSystemGradebookSession.use_comparative_gradebook_view"""
self._gradebook_view = COMPARATIVE
# self._get_provider_session('grade_system_gradebook_session') # To make sure the session is tracked
for session in self.... | [
"def",
"use_comparative_gradebook_view",
"(",
"self",
")",
":",
"self",
".",
"_gradebook_view",
"=",
"COMPARATIVE",
"# self._get_provider_session('grade_system_gradebook_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",... | 51.888889 | 0.008421 |
def default_value(self, type_name):
'''
Obtain the default value for some *type name*.
'''
uname = type_name.upper()
if uname == 'BOOLEAN':
return False
elif uname == 'INTEGER':
return 0
elif uname == 'REAL':
... | [
"def",
"default_value",
"(",
"self",
",",
"type_name",
")",
":",
"uname",
"=",
"type_name",
".",
"upper",
"(",
")",
"if",
"uname",
"==",
"'BOOLEAN'",
":",
"return",
"False",
"elif",
"uname",
"==",
"'INTEGER'",
":",
"return",
"0",
"elif",
"uname",
"==",
... | 27.083333 | 0.010401 |
def shelf_from_config(config, **default_init):
"""Get a `Shelf` instance dynamically based on config.
`config` is a dictionary containing ``shelf_*`` keys as defined in
:mod:`birding.config`.
"""
shelf_cls = import_name(config['shelf_class'], default_ns='birding.shelf')
init = {}
init.updat... | [
"def",
"shelf_from_config",
"(",
"config",
",",
"*",
"*",
"default_init",
")",
":",
"shelf_cls",
"=",
"import_name",
"(",
"config",
"[",
"'shelf_class'",
"]",
",",
"default_ns",
"=",
"'birding.shelf'",
")",
"init",
"=",
"{",
"}",
"init",
".",
"update",
"("... | 38.428571 | 0.001815 |
def _CurrentAuditLog():
"""Get the rdfurn of the current audit log."""
now_sec = rdfvalue.RDFDatetime.Now().AsSecondsSinceEpoch()
rollover_seconds = AUDIT_ROLLOVER_TIME.seconds
# This gives us a filename that only changes every
# AUDIT_ROLLOVER_TIfilME seconds, but is still a valid timestamp.
current_log = ... | [
"def",
"_CurrentAuditLog",
"(",
")",
":",
"now_sec",
"=",
"rdfvalue",
".",
"RDFDatetime",
".",
"Now",
"(",
")",
".",
"AsSecondsSinceEpoch",
"(",
")",
"rollover_seconds",
"=",
"AUDIT_ROLLOVER_TIME",
".",
"seconds",
"# This gives us a filename that only changes every",
... | 51 | 0.019277 |
def network_create_func(self, net):
"""Create network in database and dcnm
:param net: network dictionary
"""
net_id = net['id']
net_name = net.get('name')
network_db_elem = self.get_network(net_id)
# Check if the source of network creation is FW and if yes, skip
... | [
"def",
"network_create_func",
"(",
"self",
",",
"net",
")",
":",
"net_id",
"=",
"net",
"[",
"'id'",
"]",
"net_name",
"=",
"net",
".",
"get",
"(",
"'name'",
")",
"network_db_elem",
"=",
"self",
".",
"get_network",
"(",
"net_id",
")",
"# Check if the source ... | 45.371134 | 0.000445 |
def load_aggregate(args):
"""Load YAML and JSON configs and begin creating / updating , aggregating
and pushing the repos (deprecated in favor or run())"""
repos = load_config(args.config, args.expand_env)
dirmatch = args.dirmatch
for repo_dict in repos:
r = Repo(**repo_dict)
logger.... | [
"def",
"load_aggregate",
"(",
"args",
")",
":",
"repos",
"=",
"load_config",
"(",
"args",
".",
"config",
",",
"args",
".",
"expand_env",
")",
"dirmatch",
"=",
"args",
".",
"dirmatch",
"for",
"repo_dict",
"in",
"repos",
":",
"r",
"=",
"Repo",
"(",
"*",
... | 35.428571 | 0.001965 |
def from_independent_strains(cls, strains, stresses, eq_stress=None,
vasp=False, tol=1e-10):
"""
Constructs the elastic tensor least-squares fit of independent strains
Args:
strains (list of Strains): list of strain objects to fit
stresses... | [
"def",
"from_independent_strains",
"(",
"cls",
",",
"strains",
",",
"stresses",
",",
"eq_stress",
"=",
"None",
",",
"vasp",
"=",
"False",
",",
"tol",
"=",
"1e-10",
")",
":",
"strain_states",
"=",
"[",
"tuple",
"(",
"ss",
")",
"for",
"ss",
"in",
"np",
... | 52.606061 | 0.001697 |
def get_participants_for_section(section, person=None):
"""
Returns a list of gradebook participants for the passed section and person.
"""
section_label = encode_section_label(section.section_label())
url = "/rest/gradebook/v1/section/{}/participants".format(section_label)
headers = {}
if ... | [
"def",
"get_participants_for_section",
"(",
"section",
",",
"person",
"=",
"None",
")",
":",
"section_label",
"=",
"encode_section_label",
"(",
"section",
".",
"section_label",
"(",
")",
")",
"url",
"=",
"\"/rest/gradebook/v1/section/{}/participants\"",
".",
"format",... | 30.5 | 0.001767 |
def offsets(self):
""" Returns the offsets values of x, y, z as a numpy array
"""
return np.array([self.x_offset, self.y_offset, self.z_offset]) | [
"def",
"offsets",
"(",
"self",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"self",
".",
"x_offset",
",",
"self",
".",
"y_offset",
",",
"self",
".",
"z_offset",
"]",
")"
] | 41.25 | 0.011905 |
def pdf(self, x_test):
"""
Computes the probability density function at all x_test
"""
N,D = self.data.shape
x_test = np.asfortranarray(x_test)
x_test = x_test.reshape([-1, D])
pdfs = self._individual_pdfs(x_test)
#import pdb; pdb.set_trace()
# combine values based on fully_dimensional!
if self.... | [
"def",
"pdf",
"(",
"self",
",",
"x_test",
")",
":",
"N",
",",
"D",
"=",
"self",
".",
"data",
".",
"shape",
"x_test",
"=",
"np",
".",
"asfortranarray",
"(",
"x_test",
")",
"x_test",
"=",
"x_test",
".",
"reshape",
"(",
"[",
"-",
"1",
",",
"D",
"]... | 40.888889 | 0.034529 |
def _process_content_streams(*, pdf, container, shorthand=None):
"""Find all individual instances of images drawn in the container
Usually the container is a page, but it may also be a Form XObject.
On a typical page images are stored inline or as regular images
in an XObject.
Form XObjects may i... | [
"def",
"_process_content_streams",
"(",
"*",
",",
"pdf",
",",
"container",
",",
"shorthand",
"=",
"None",
")",
":",
"if",
"container",
".",
"get",
"(",
"'/Type'",
")",
"==",
"'/Page'",
"and",
"'/Contents'",
"in",
"container",
":",
"initial_shorthand",
"=",
... | 42.444444 | 0.001024 |
def getlist(self, key: 'Entity') -> Sequence[object]:
r"""Return all values associated to the given ``key`` property
in sequence.
:param key: The property entity.
:type key: :class:`Entity`
:return: A sequence of all values associated to the given ``key``
proper... | [
"def",
"getlist",
"(",
"self",
",",
"key",
":",
"'Entity'",
")",
"->",
"Sequence",
"[",
"object",
"]",
":",
"if",
"not",
"(",
"isinstance",
"(",
"key",
",",
"type",
"(",
"self",
")",
")",
"and",
"key",
".",
"type",
"is",
"EntityType",
".",
"propert... | 45.185185 | 0.001605 |
def parse_response(self, response, header=None):
"""Parses the response message.
The following graph shows the structure of response messages.
::
+----------+
+--+ data sep +<-+
... | [
"def",
"parse_response",
"(",
"self",
",",
"response",
",",
"header",
"=",
"None",
")",
":",
"response",
"=",
"response",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"if",
"header",
":",
"header",
"=",
"\"\"",
".",
"join",
"(",
"(",
"self",
"."... | 52.83871 | 0.001199 |
def set_ip_port(self, ip, port):
'''set ip and port'''
self.address = ip
self.port = port
self.stop()
self.start() | [
"def",
"set_ip_port",
"(",
"self",
",",
"ip",
",",
"port",
")",
":",
"self",
".",
"address",
"=",
"ip",
"self",
".",
"port",
"=",
"port",
"self",
".",
"stop",
"(",
")",
"self",
".",
"start",
"(",
")"
] | 24.833333 | 0.012987 |
def backup_file(*, file, host):
"""
Backup a file on S3
:param file: full path to the file to be backed up
:param host: this will be used to locate the file on S3
:raises TypeError: if an argument in kwargs does not have the type expected
:raises ValueError: if an argument within kwargs has an ... | [
"def",
"backup_file",
"(",
"*",
",",
"file",
",",
"host",
")",
":",
"# This driver won't do a thing unless it has been properly initialised",
"# via load()",
"if",
"not",
"_has_init",
":",
"raise",
"RuntimeError",
"(",
"\"This driver has not been properly initialised!\"",
")"... | 37.021739 | 0.000572 |
def _format_pr(pr_):
'''
Helper function to format API return information into a more manageable
and useful dictionary for pull request information.
pr_
The pull request to format.
'''
ret = {'id': pr_.get('id'),
'pr_number': pr_.get('number'),
'state': pr_.get('st... | [
"def",
"_format_pr",
"(",
"pr_",
")",
":",
"ret",
"=",
"{",
"'id'",
":",
"pr_",
".",
"get",
"(",
"'id'",
")",
",",
"'pr_number'",
":",
"pr_",
".",
"get",
"(",
"'number'",
")",
",",
"'state'",
":",
"pr_",
".",
"get",
"(",
"'state'",
")",
",",
"'... | 30.058824 | 0.001898 |
def resend_dcv(gandi, resource):
""" Resend the DCV mail.
Resource can be a CN or an ID
"""
ids = gandi.certificate.usable_ids(resource)
if len(ids) > 1:
gandi.echo('Will not update, %s is not precise enough.' % resource)
gandi.echo(' * cert : ' +
'\n * cert : ... | [
"def",
"resend_dcv",
"(",
"gandi",
",",
"resource",
")",
":",
"ids",
"=",
"gandi",
".",
"certificate",
".",
"usable_ids",
"(",
"resource",
")",
"if",
"len",
"(",
"ids",
")",
">",
"1",
":",
"gandi",
".",
"echo",
"(",
"'Will not update, %s is not precise eno... | 29.34375 | 0.001031 |
def parse_set_header(value, on_update=None):
"""Parse a set-like header and return a
:class:`~werkzeug.datastructures.HeaderSet` object:
>>> hs = parse_set_header('token, "quoted value"')
The return value is an object that treats the items case-insensitively
and keeps the order of the items:
... | [
"def",
"parse_set_header",
"(",
"value",
",",
"on_update",
"=",
"None",
")",
":",
"if",
"not",
"value",
":",
"return",
"HeaderSet",
"(",
"None",
",",
"on_update",
")",
"return",
"HeaderSet",
"(",
"parse_list_header",
"(",
"value",
")",
",",
"on_update",
")... | 33.321429 | 0.001042 |
def _get_format(format, fname, inp=None):
"""Try to guess markup format of given input.
Args:
format: explicit format override to use
fname: name of file, if a file was used to read `inp`
inp: optional bytestring to guess format of (can be None, if markup
format is to be gue... | [
"def",
"_get_format",
"(",
"format",
",",
"fname",
",",
"inp",
"=",
"None",
")",
":",
"fmt",
"=",
"None",
"err",
"=",
"True",
"if",
"format",
"is",
"not",
"None",
":",
"if",
"format",
"in",
"fmt_to_exts",
":",
"fmt",
"=",
"format",
"err",
"=",
"Fal... | 31.93617 | 0.000646 |
async def release(
self, *, comment: str = None, erase: bool = None,
secure_erase: bool = None, quick_erase: bool = None,
wait: bool = False, wait_interval: int = 5):
"""
Release the machine.
:param comment: Reason machine was released.
:type comment:... | [
"async",
"def",
"release",
"(",
"self",
",",
"*",
",",
"comment",
":",
"str",
"=",
"None",
",",
"erase",
":",
"bool",
"=",
"None",
",",
"secure_erase",
":",
"bool",
"=",
"None",
",",
"quick_erase",
":",
"bool",
"=",
"None",
",",
"wait",
":",
"bool"... | 41.438596 | 0.000827 |
def mean_interval(data, alpha=_alpha):
"""
Interval assuming gaussian posterior.
"""
mean =np.mean(data)
sigma = np.std(data)
scale = scipy.stats.norm.ppf(1-alpha/2.)
return interval(mean,mean-scale*sigma,mean+scale*sigma) | [
"def",
"mean_interval",
"(",
"data",
",",
"alpha",
"=",
"_alpha",
")",
":",
"mean",
"=",
"np",
".",
"mean",
"(",
"data",
")",
"sigma",
"=",
"np",
".",
"std",
"(",
"data",
")",
"scale",
"=",
"scipy",
".",
"stats",
".",
"norm",
".",
"ppf",
"(",
"... | 30.375 | 0.016 |
def get_tour(index):
"""
This function generates a list of tours.
The index argument is used to retrieve a particular tour. If None is
passed, it will return the full list of tours. If instead -1 is given,
this function will return a test tour
To add more tours a new variable needs... | [
"def",
"get_tour",
"(",
"index",
")",
":",
"sw",
"=",
"SpyderWidgets",
"qtconsole_link",
"=",
"\"https://qtconsole.readthedocs.io/en/stable/index.html\"",
"# This test should serve as example of keys to use in the tour frame dics\r",
"test",
"=",
"[",
"{",
"'title'",
":",
"\"We... | 48.979592 | 0.001736 |
def Set(self, value, context=None):
"""Receives a value for the object and some context on its source."""
if self.has_error: return
if self.value is None:
self.value = value
self._context["old_value"] = value
self._context.update({"old_" + k: v for k, v in context.items()})
elif self.v... | [
"def",
"Set",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"has_error",
":",
"return",
"if",
"self",
".",
"value",
"is",
"None",
":",
"self",
".",
"value",
"=",
"value",
"self",
".",
"_context",
"[",
"\"old_v... | 42.272727 | 0.016842 |
def wait(self, sensor_name, condition_or_value, timeout=5.0, quorum=None,
max_grace_period=1.0):
"""Wait for sensor present on all group clients to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_... | [
"def",
"wait",
"(",
"self",
",",
"sensor_name",
",",
"condition_or_value",
",",
"timeout",
"=",
"5.0",
",",
"quorum",
"=",
"None",
",",
"max_grace_period",
"=",
"1.0",
")",
":",
"if",
"quorum",
"is",
"None",
":",
"quorum",
"=",
"len",
"(",
"self",
".",... | 49.08642 | 0.000986 |
def get_alert_log(self,
current=0,
minimum=0,
maximum=100,
header="",
action_key=None):
"""Get the alert log."""
return self.get_alert(current=current,
minimum=mini... | [
"def",
"get_alert_log",
"(",
"self",
",",
"current",
"=",
"0",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"100",
",",
"header",
"=",
"\"\"",
",",
"action_key",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_alert",
"(",
"current",
"=",
"curre... | 38.230769 | 0.013752 |
def skopeo_pull(self):
""" Pull image from Docker to local Docker daemon using skopeo
:return: pulled image
"""
return self.copy(self.name, self.tag,
SkopeoTransport.DOCKER, SkopeoTransport.DOCKER_DAEMON)\
.using_transport(SkopeoTransport.DOCKER_DAEM... | [
"def",
"skopeo_pull",
"(",
"self",
")",
":",
"return",
"self",
".",
"copy",
"(",
"self",
".",
"name",
",",
"self",
".",
"tag",
",",
"SkopeoTransport",
".",
"DOCKER",
",",
"SkopeoTransport",
".",
"DOCKER_DAEMON",
")",
".",
"using_transport",
"(",
"SkopeoTra... | 39.5 | 0.009288 |
def filter(self, u):
"""Filter the valid identities for this matcher.
:param u: unique identity which stores the identities to filter
:returns: a list of identities valid to work with this matcher.
:raises ValueError: when the unique identity is not an instance
of UniqueId... | [
"def",
"filter",
"(",
"self",
",",
"u",
")",
":",
"if",
"not",
"isinstance",
"(",
"u",
",",
"UniqueIdentity",
")",
":",
"raise",
"ValueError",
"(",
"\"<u> is not an instance of UniqueIdentity\"",
")",
"filtered",
"=",
"[",
"]",
"for",
"id_",
"in",
"u",
"."... | 30.15625 | 0.002008 |
def convex_cardinality_relaxed(f, epsilon=1e-5):
"""Transform L1-norm optimization function into cardinality optimization.
The given function must optimize a convex problem with
a weighted L1-norm as the objective. The transformed function
will apply the iterated weighted L1 heuristic to approximately
... | [
"def",
"convex_cardinality_relaxed",
"(",
"f",
",",
"epsilon",
"=",
"1e-5",
")",
":",
"def",
"convex_cardinality_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"dict_result",
"(",
"r",
")",
":",
"if",
"isinstance",
"(",
"r",
",",
... | 38.788462 | 0.000484 |
def create_user(self, user_name, initial_password):
"""Create a new user with an initial password via provisioning API.
It is not an error, if the user already existed before.
If you get back an error 999, then the provisioning API is not enabled.
:param user_name: name of user to be c... | [
"def",
"create_user",
"(",
"self",
",",
"user_name",
",",
"initial_password",
")",
":",
"res",
"=",
"self",
".",
"_make_ocs_request",
"(",
"'POST'",
",",
"self",
".",
"OCS_SERVICE_CLOUD",
",",
"'users'",
",",
"data",
"=",
"{",
"'password'",
":",
"initial_pas... | 37.24 | 0.002094 |
def reset_training_state(self, dones, batch_info):
""" A hook for a model to react when during training episode is finished """
for idx, done in enumerate(dones):
if done > 0.5:
self.processes[idx].reset() | [
"def",
"reset_training_state",
"(",
"self",
",",
"dones",
",",
"batch_info",
")",
":",
"for",
"idx",
",",
"done",
"in",
"enumerate",
"(",
"dones",
")",
":",
"if",
"done",
">",
"0.5",
":",
"self",
".",
"processes",
"[",
"idx",
"]",
".",
"reset",
"(",
... | 49 | 0.012048 |
def matrix_exponent(M):
"""
The function computes matrix exponent and handles some special cases
"""
if (M.shape[0] == 1): # 1*1 matrix
Mexp = np.array( ((np.exp(M[0,0]) ,),) )
else: # matrix is larger
method = None
try:
Mexp = linalg.expm(M)
method ... | [
"def",
"matrix_exponent",
"(",
"M",
")",
":",
"if",
"(",
"M",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
")",
":",
"# 1*1 matrix",
"Mexp",
"=",
"np",
".",
"array",
"(",
"(",
"(",
"np",
".",
"exp",
"(",
"M",
"[",
"0",
",",
"0",
"]",
")",
",",
... | 29.222222 | 0.008589 |
def getent(refresh=False, root=None):
'''
Return info on all groups
refresh
Force a refresh of group information
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' group.getent
'''
if 'group.getent' in __context__ and not refresh:
... | [
"def",
"getent",
"(",
"refresh",
"=",
"False",
",",
"root",
"=",
"None",
")",
":",
"if",
"'group.getent'",
"in",
"__context__",
"and",
"not",
"refresh",
":",
"return",
"__context__",
"[",
"'group.getent'",
"]",
"ret",
"=",
"[",
"]",
"if",
"root",
"is",
... | 21.103448 | 0.001563 |
def rename_attributes(element, attrs):
"""
Renames the attributes of the element. Accepts the element and a dictionary
of string values. The keys are the original names, and their values will be
the altered names. This method treats all attributes as optional and will
not fail on missing attributes.... | [
"def",
"rename_attributes",
"(",
"element",
",",
"attrs",
")",
":",
"for",
"name",
"in",
"attrs",
".",
"keys",
"(",
")",
":",
"if",
"name",
"not",
"in",
"element",
".",
"attrib",
":",
"continue",
"else",
":",
"element",
".",
"attrib",
"[",
"attrs",
"... | 40.666667 | 0.002004 |
def element_name_and_type_by_href(href):
"""
Retrieve the element name and type of element based on the href.
You may have a href that is within another element reference and
want more information on that reference.
:param str href: href of element
:return: tuple (name, type)
"""
if hre... | [
"def",
"element_name_and_type_by_href",
"(",
"href",
")",
":",
"if",
"href",
":",
"element",
"=",
"fetch_json_by_href",
"(",
"href",
")",
"if",
"element",
".",
"json",
":",
"for",
"entries",
"in",
"element",
".",
"json",
".",
"get",
"(",
"'link'",
")",
"... | 33.277778 | 0.001623 |
def target_range(self):
"""Get the range covered on the target/reference strand
:returns: Genomic range of the target strand
:rtype: GenomicRange
"""
a = self.alignment_ranges
return GenomicRange(a[0][0].chr,a[0][0].start,a[-1][0].end) | [
"def",
"target_range",
"(",
"self",
")",
":",
"a",
"=",
"self",
".",
"alignment_ranges",
"return",
"GenomicRange",
"(",
"a",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"chr",
",",
"a",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"start",
",",
"a",
"[",
"-",
"... | 28.111111 | 0.011494 |
def read(cls, source, names=None, format=None, **kwargs):
"""Read segments from file into a `DataQualityDict`
Parameters
----------
source : `str`
path of file to read
format : `str`, optional
source format identifier. If not given, the format will be
... | [
"def",
"read",
"(",
"cls",
",",
"source",
",",
"names",
"=",
"None",
",",
"format",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"on_missing",
"=",
"kwargs",
".",
"pop",
"(",
"'on_missing'",
",",
"'error'",
")",
"coalesce",
"=",
"kwargs",
".",
"... | 37.236111 | 0.000727 |
def paint( self, painter, option, widget ):
"""
Paints this item on the painter.
:param painter | <QPainter>
option | <QStyleOptionGraphicsItem>
widget | <QWidget>
"""
if ( self._rebuildRequired ):
self.... | [
"def",
"paint",
"(",
"self",
",",
"painter",
",",
"option",
",",
"widget",
")",
":",
"if",
"(",
"self",
".",
"_rebuildRequired",
")",
":",
"self",
".",
"rebuild",
"(",
")",
"# set the coloring options\r",
"painter",
".",
"setPen",
"(",
"self",
".",
"bord... | 31.4 | 0.015004 |
def get_all_access_keys(user_name, marker=None, max_items=None,
region=None, key=None, keyid=None, profile=None):
'''
Get all access keys from a user.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_all_access_keys myuser
... | [
"def",
"get_all_access_keys",
"(",
"user_name",
",",
"marker",
"=",
"None",
",",
"max_items",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
... | 31.8 | 0.001527 |
def applet_list_projects(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/listProjects API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects
"""
return DXHTTPRequest('/%s/listProjec... | [
"def",
"applet_list_projects",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/listProjects'",
"%",
"object_id",
",",
"input_params",
",",
"always_... | 54.428571 | 0.010336 |
def handle_request(path):
"""
Return the current status.
"""
accept = bottle.request.get_header("accept", default="text/plain")
bottle.response.status = 200
try:
if "text/html" in accept:
ret = CURRENT_STATE.as_html(path=path)
bottle.response.content_type = "te... | [
"def",
"handle_request",
"(",
"path",
")",
":",
"accept",
"=",
"bottle",
".",
"request",
".",
"get_header",
"(",
"\"accept\"",
",",
"default",
"=",
"\"text/plain\"",
")",
"bottle",
".",
"response",
".",
"status",
"=",
"200",
"try",
":",
"if",
"\"text/html\... | 29.433333 | 0.001096 |
def lxqstr(string, qchar, first):
"""
Lex (scan) a quoted string.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lxqstr_c.html
:param string: String to be scanned.
:type string: str
:param qchar: Quote delimiter character.
:type qchar: char (string of one char)
:param first: C... | [
"def",
"lxqstr",
"(",
"string",
",",
"qchar",
",",
"first",
")",
":",
"string",
"=",
"stypes",
".",
"stringToCharP",
"(",
"string",
")",
"qchar",
"=",
"ctypes",
".",
"c_char",
"(",
"qchar",
".",
"encode",
"(",
"encoding",
"=",
"'UTF-8'",
")",
")",
"f... | 32.391304 | 0.001304 |
def _get_date(data, position, dummy, opts):
"""Decode a BSON datetime to python datetime.datetime."""
end = position + 8
millis = _UNPACK_LONG(data[position:end])[0]
diff = ((millis % 1000) + 1000) % 1000
seconds = (millis - diff) / 1000
micros = diff * 1000
if opts.tz_aware:
return ... | [
"def",
"_get_date",
"(",
"data",
",",
"position",
",",
"dummy",
",",
"opts",
")",
":",
"end",
"=",
"position",
"+",
"8",
"millis",
"=",
"_UNPACK_LONG",
"(",
"data",
"[",
"position",
":",
"end",
"]",
")",
"[",
"0",
"]",
"diff",
"=",
"(",
"(",
"mil... | 39.230769 | 0.001916 |
def savgol_fit_magseries(times, mags, errs, period,
windowlength=None,
polydeg=2,
sigclip=30.0,
plotfit=False,
magsarefluxes=False,
verbose=True):
'''Fit a Savitzky-... | [
"def",
"savgol_fit_magseries",
"(",
"times",
",",
"mags",
",",
"errs",
",",
"period",
",",
"windowlength",
"=",
"None",
",",
"polydeg",
"=",
"2",
",",
"sigclip",
"=",
"30.0",
",",
"plotfit",
"=",
"False",
",",
"magsarefluxes",
"=",
"False",
",",
"verbose... | 40.196262 | 0.002496 |
def create(self, name, **kwargs):
"""
Create new role
http://www.keycloak.org/docs-api/3.4/rest-api/index.html
#_roles_resource
:param str name: Name for the role
:param str description: (optional)
:param str id: (optional)
:param bool client_role: (opti... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"OrderedDict",
"(",
"name",
"=",
"name",
")",
"for",
"key",
"in",
"ROLE_KWARGS",
":",
"if",
"key",
"in",
"kwargs",
":",
"payload",
"[",
"to_camel_case",
"("... | 31.933333 | 0.002026 |
def list_subnetpools(self, retrieve_all=True, **_params):
"""Fetches a list of all subnetpools for a project."""
return self.list('subnetpools', self.subnetpools_path, retrieve_all,
**_params) | [
"def",
"list_subnetpools",
"(",
"self",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"list",
"(",
"'subnetpools'",
",",
"self",
".",
"subnetpools_path",
",",
"retrieve_all",
",",
"*",
"*",
"_params",
")"
] | 57.5 | 0.008584 |
def showGridRows( self ):
"""
Returns whether or not this delegate should draw rows when rendering \
the grid.
:return <bool>
"""
delegate = self.itemDelegate()
if ( isinstance(delegate, XTreeWidgetDelegate) ):
return delegate.sho... | [
"def",
"showGridRows",
"(",
"self",
")",
":",
"delegate",
"=",
"self",
".",
"itemDelegate",
"(",
")",
"if",
"(",
"isinstance",
"(",
"delegate",
",",
"XTreeWidgetDelegate",
")",
")",
":",
"return",
"delegate",
".",
"showGridRows",
"(",
")",
"return",
"None"... | 31.090909 | 0.022727 |
def check_archive(schema, rev_id, namespace=None, title=None, timestamp=None,
radius=defaults.RADIUS,
before=None, window=None):
"""
Checks the revert status of an archived revision (from a deleted page).
With this method, you can determine whether an edit is a 'reverting... | [
"def",
"check_archive",
"(",
"schema",
",",
"rev_id",
",",
"namespace",
"=",
"None",
",",
"title",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"radius",
"=",
"defaults",
".",
"RADIUS",
",",
"before",
"=",
"None",
",",
"window",
"=",
"None",
")",
... | 40.753086 | 0.000296 |
def data_corners(data, data_filter = None):
"""!
@brief Finds maximum and minimum corner in each dimension of the specified data.
@param[in] data (list): List of points that should be analysed.
@param[in] data_filter (list): List of indexes of the data that should be analysed,
... | [
"def",
"data_corners",
"(",
"data",
",",
"data_filter",
"=",
"None",
")",
":",
"dimensions",
"=",
"len",
"(",
"data",
"[",
"0",
"]",
")",
"bypass",
"=",
"data_filter",
"if",
"bypass",
"is",
"None",
":",
"bypass",
"=",
"range",
"(",
"len",
"(",
"data"... | 40.466667 | 0.01609 |
def parse(duration, context=None):
"""
parse the duration string which contains a human readable duration and
return a datetime.timedelta object representing that duration
arguments:
duration - the duration string following a notation like so:
"1 hour"
"1 m... | [
"def",
"parse",
"(",
"duration",
",",
"context",
"=",
"None",
")",
":",
"matcher",
"=",
"_PATTERN",
".",
"match",
"(",
"duration",
")",
"if",
"matcher",
"is",
"None",
"or",
"matcher",
".",
"end",
"(",
")",
"<",
"len",
"(",
"duration",
")",
":",
"ra... | 36.161538 | 0.000207 |
def parse_home_face_offs(self):
"""
Parse only the home faceoffs
:returns: ``self`` on success, ``None`` otherwise
"""
self.__set_team_docs()
self.face_offs['home'] = FaceOffRep.__read_team_doc(self.__home_doc)
return self | [
"def",
"parse_home_face_offs",
"(",
"self",
")",
":",
"self",
".",
"__set_team_docs",
"(",
")",
"self",
".",
"face_offs",
"[",
"'home'",
"]",
"=",
"FaceOffRep",
".",
"__read_team_doc",
"(",
"self",
".",
"__home_doc",
")",
"return",
"self"
] | 31 | 0.010453 |
def auto_authorize(scope, password=[None]):
"""
Executes a command on the remote host that causes an authorization
procedure to be started, then authorizes using the given password
in the same way in which authorize() works.
Depending on the detected operating system of the remote host the
follo... | [
"def",
"auto_authorize",
"(",
"scope",
",",
"password",
"=",
"[",
"None",
"]",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"password",
"=",
"password",
"[",
"0",
"]",
"if",
"password",
"is",
"None",
":",
"conn",
".",
"au... | 33 | 0.001339 |
def query_sum(queryset, field):
"""
Let the DBMS perform a sum on a queryset
"""
return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s'] | [
"def",
"query_sum",
"(",
"queryset",
",",
"field",
")",
":",
"return",
"queryset",
".",
"aggregate",
"(",
"s",
"=",
"models",
".",
"functions",
".",
"Coalesce",
"(",
"models",
".",
"Sum",
"(",
"field",
")",
",",
"0",
")",
")",
"[",
"'s'",
"]"
] | 34.8 | 0.011236 |
def synonyms(self):
"""A ranked list of all the names associated with this Compound.
Requires an extra request. Result is cached.
"""
if self.cid:
results = get_json(self.cid, operation='synonyms')
return results['InformationList']['Information'][0]['Synonym'] if... | [
"def",
"synonyms",
"(",
"self",
")",
":",
"if",
"self",
".",
"cid",
":",
"results",
"=",
"get_json",
"(",
"self",
".",
"cid",
",",
"operation",
"=",
"'synonyms'",
")",
"return",
"results",
"[",
"'InformationList'",
"]",
"[",
"'Information'",
"]",
"[",
... | 41.125 | 0.008929 |
def timebinlc_worker(task):
'''
This is a parallel worker for the function below.
Parameters
----------
task : tuple
This is of the form::
task[0] = lcfile
task[1] = binsizesec
task[3] = {'outdir','lcformat','lcformatdir',
'timeco... | [
"def",
"timebinlc_worker",
"(",
"task",
")",
":",
"lcfile",
",",
"binsizesec",
",",
"kwargs",
"=",
"task",
"try",
":",
"binnedlc",
"=",
"timebinlc",
"(",
"lcfile",
",",
"binsizesec",
",",
"*",
"*",
"kwargs",
")",
"LOGINFO",
"(",
"'%s binned using %s sec -> %... | 25.852941 | 0.002193 |
def tile_id_in_direction(from_tile_id, direction):
"""
Variant on direction_to_tile. Returns None if there's no tile there.
:param from_tile_id: tile identifier, int
:param direction: str
:return: tile identifier, int or None
"""
coord_from = tile_id_to_coord(from_tile_id)
for offset, d... | [
"def",
"tile_id_in_direction",
"(",
"from_tile_id",
",",
"direction",
")",
":",
"coord_from",
"=",
"tile_id_to_coord",
"(",
"from_tile_id",
")",
"for",
"offset",
",",
"dirn",
"in",
"_tile_tile_offsets",
".",
"items",
"(",
")",
":",
"if",
"dirn",
"==",
"directi... | 35.266667 | 0.001842 |
def update_shipment(self, resource_id, data):
"""Update the tracking information of a shipment."""
return Shipments(self.client).on(self).update(resource_id, data) | [
"def",
"update_shipment",
"(",
"self",
",",
"resource_id",
",",
"data",
")",
":",
"return",
"Shipments",
"(",
"self",
".",
"client",
")",
".",
"on",
"(",
"self",
")",
".",
"update",
"(",
"resource_id",
",",
"data",
")"
] | 59 | 0.011173 |
def get_send_command(self, send):
"""Internal helper function to get command that's really sent
"""
shutit_global.shutit_global_object.yield_to_draw()
if send is None:
return send
cmd_arr = send.split()
if cmd_arr and cmd_arr[0] in ('md5sum','sed','head'):
newcmd = self.get_command(cmd_arr[0])
send... | [
"def",
"get_send_command",
"(",
"self",
",",
"send",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"if",
"send",
"is",
"None",
":",
"return",
"send",
"cmd_arr",
"=",
"send",
".",
"split",
"(",
")",
"if",
"cmd_arr",... | 32.545455 | 0.040761 |
def get_dataset(catalog, identifier=None, title=None):
"""Devuelve un Dataset del catálogo."""
msg = "Se requiere un 'identifier' o 'title' para buscar el dataset."
assert identifier or title, msg
catalog = read_catalog_obj(catalog)
# búsqueda optimizada por identificador
if identifier:
... | [
"def",
"get_dataset",
"(",
"catalog",
",",
"identifier",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"msg",
"=",
"\"Se requiere un 'identifier' o 'title' para buscar el dataset.\"",
"assert",
"identifier",
"or",
"title",
",",
"msg",
"catalog",
"=",
"read_catal... | 36.606061 | 0.000806 |
def get_tree(self, list_of_keys):
""" gettree will extract the value from a nested tree
INPUT
list_of_keys: a list of keys ie. ['key1', 'key2']
USAGE
>>> # Access the value for key2 within the nested dictionary
>>> adv_dict({'key1': {'key2': 'value'}}).gettree(['key1', 'key... | [
"def",
"get_tree",
"(",
"self",
",",
"list_of_keys",
")",
":",
"cur_obj",
"=",
"self",
"for",
"key",
"in",
"list_of_keys",
":",
"cur_obj",
"=",
"cur_obj",
".",
"get",
"(",
"key",
")",
"if",
"not",
"cur_obj",
":",
"break",
"return",
"cur_obj"
] | 31.6 | 0.020492 |
def _fetch_remote_json(service_url, params=None, use_http_post=False):
"""Retrieves a JSON object from a URL."""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
if six.PY3:
str_response = response.read().decode('utf-8')
return... | [
"def",
"_fetch_remote_json",
"(",
"service_url",
",",
"params",
"=",
"None",
",",
"use_http_post",
"=",
"False",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"request_url",
",",
"response",
"=",
"_fetch_remote",
"(",
"service_url",
",",
"... | 43.9 | 0.002232 |
def parse_annotations(
self, annotation_file, genes, db_sel='UniProtKB',
select_evidence=None, exclude_evidence=None,
exclude_ref=None, strip_species=False, ignore_case=False):
"""Parse a GO annotation file (in GAF 2.0 format).
GO annotation files can be downloaded f... | [
"def",
"parse_annotations",
"(",
"self",
",",
"annotation_file",
",",
"genes",
",",
"db_sel",
"=",
"'UniProtKB'",
",",
"select_evidence",
"=",
"None",
",",
"exclude_evidence",
"=",
"None",
",",
"exclude_ref",
"=",
"None",
",",
"strip_species",
"=",
"False",
",... | 38.838235 | 0.000615 |
def ransohoff_snap_off(target,
shape_factor=2.0,
wavelength=5e-6,
require_pair=False,
surface_tension='pore.surface_tension',
contact_angle='pore.contact_angle',
diameter='throat.dia... | [
"def",
"ransohoff_snap_off",
"(",
"target",
",",
"shape_factor",
"=",
"2.0",
",",
"wavelength",
"=",
"5e-6",
",",
"require_pair",
"=",
"False",
",",
"surface_tension",
"=",
"'pore.surface_tension'",
",",
"contact_angle",
"=",
"'pore.contact_angle'",
",",
"diameter",... | 41.061947 | 0.000421 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.