text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_results(self, title_prefix="", title_override="", rnd_dig=2):
"""
Constructs a summary of the results as an array, which might be
useful for writing the results of multiple algorithms to a table.
NOTE- This method must be called AFTER "roll_mc".
:param title_prefix... | [
"def",
"get_results",
"(",
"self",
",",
"title_prefix",
"=",
"\"\"",
",",
"title_override",
"=",
"\"\"",
",",
"rnd_dig",
"=",
"2",
")",
":",
"# Check that roll_mc has been called\r",
"if",
"not",
"self",
".",
"arr_res",
":",
"raise",
"ValueError",
"(",
"\"Call... | 51.34375 | 0.002389 |
def normalize(self):
"""
Adapt self.model so that amplitudes are positive and phases are in [0,360) as per convention
"""
for i, (_, amplitude, phase) in enumerate(self.model):
if amplitude < 0:
self.model['amplitude'][i] = -amplitude
self.model['phase'][i] = phase + 180.0
self.model['phase'][i] =... | [
"def",
"normalize",
"(",
"self",
")",
":",
"for",
"i",
",",
"(",
"_",
",",
"amplitude",
",",
"phase",
")",
"in",
"enumerate",
"(",
"self",
".",
"model",
")",
":",
"if",
"amplitude",
"<",
"0",
":",
"self",
".",
"model",
"[",
"'amplitude'",
"]",
"[... | 38.888889 | 0.030726 |
def pad(self, string):
"""
Add some lorem ipsum text to the end of string to simulate more verbose languages (like German).
Padding factor extrapolated by guidelines at http://www.w3.org/International/articles/article-text-size.en
"""
size = len(string)
target = size * (4... | [
"def",
"pad",
"(",
"self",
",",
"string",
")",
":",
"size",
"=",
"len",
"(",
"string",
")",
"target",
"=",
"size",
"*",
"(",
"4.75",
"-",
"size",
"**",
"0.27",
")",
"pad_len",
"=",
"int",
"(",
"target",
")",
"-",
"size",
"return",
"string",
"+",
... | 46.555556 | 0.009368 |
def is_same_nick(self, left, right):
""" Check if given nicknames are equal in the server's case mapping. """
return self.normalize(left) == self.normalize(right) | [
"def",
"is_same_nick",
"(",
"self",
",",
"left",
",",
"right",
")",
":",
"return",
"self",
".",
"normalize",
"(",
"left",
")",
"==",
"self",
".",
"normalize",
"(",
"right",
")"
] | 58.666667 | 0.016854 |
def use_comparative_vault_view(self):
"""Pass through to provider AuthorizationVaultSession.use_comparative_vault_view"""
self._vault_view = COMPARATIVE
# self._get_provider_session('authorization_vault_session') # To make sure the session is tracked
for session in self._get_provider_ses... | [
"def",
"use_comparative_vault_view",
"(",
"self",
")",
":",
"self",
".",
"_vault_view",
"=",
"COMPARATIVE",
"# self._get_provider_session('authorization_vault_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
"(",
"... | 49.555556 | 0.008811 |
def _component_default(self):
""" Trait initialiser.
"""
component = Container(fit_window=False, auto_size=True,
bgcolor="green")#, position=list(self.pos) )
component.tools.append( MoveTool(component) )
# component.tools.append( TraitsTool(component) )
return ... | [
"def",
"_component_default",
"(",
"self",
")",
":",
"component",
"=",
"Container",
"(",
"fit_window",
"=",
"False",
",",
"auto_size",
"=",
"True",
",",
"bgcolor",
"=",
"\"green\"",
")",
"#, position=list(self.pos) )",
"component",
".",
"tools",
".",
"append",
... | 40.25 | 0.021277 |
def send(self, *args, **kwargs):
"""Send messages to another service that is connected to the currently
running service via the recipe. The 'send' method will either use a
default channel name, set via the set_default_channel method, or an
unnamed output definition.
"""
i... | [
"def",
"send",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"transport",
":",
"raise",
"ValueError",
"(",
"\"This RecipeWrapper object does not contain \"",
"\"a reference to a transport object.\"",
")",
"if",
"not",
... | 40.064516 | 0.002358 |
def read_range(filepath, range_expr, sheet=None, dict_generator=None):
"""Read values from an Excel range into a dictionary.
`range_expr` ie either a range address string, such as "A1", "$C$3:$E$5",
or a defined name string for a range, such as "NamedRange1".
If a range address is provided, `sheet` arg... | [
"def",
"read_range",
"(",
"filepath",
",",
"range_expr",
",",
"sheet",
"=",
"None",
",",
"dict_generator",
"=",
"None",
")",
":",
"def",
"default_generator",
"(",
"cells",
")",
":",
"for",
"row_ind",
",",
"row",
"in",
"enumerate",
"(",
"cells",
")",
":",... | 41.358491 | 0.002228 |
def p_ConstValue_integer(p):
"""ConstValue : INTEGER"""
p[0] = model.Value(type=model.Value.INTEGER, value=p[1]) | [
"def",
"p_ConstValue_integer",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Value",
"(",
"type",
"=",
"model",
".",
"Value",
".",
"INTEGER",
",",
"value",
"=",
"p",
"[",
"1",
"]",
")"
] | 38 | 0.025862 |
def show_lbaas_l7policy(self, l7policy, **_params):
"""Fetches information of a certain listener's L7 policy."""
return self.get(self.lbaas_l7policy_path % l7policy,
params=_params) | [
"def",
"show_lbaas_l7policy",
"(",
"self",
",",
"l7policy",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"lbaas_l7policy_path",
"%",
"l7policy",
",",
"params",
"=",
"_params",
")"
] | 54.5 | 0.00905 |
def complete_links(self, text):
'''return list of links'''
try:
ret = [ m.address for m in self.mpstate.mav_master ]
for m in self.mpstate.mav_master:
ret.append(m.address)
if hasattr(m, 'label'):
ret.append(m.label)
... | [
"def",
"complete_links",
"(",
"self",
",",
"text",
")",
":",
"try",
":",
"ret",
"=",
"[",
"m",
".",
"address",
"for",
"m",
"in",
"self",
".",
"mpstate",
".",
"mav_master",
"]",
"for",
"m",
"in",
"self",
".",
"mpstate",
".",
"mav_master",
":",
"ret"... | 36.636364 | 0.009685 |
def launch(self):
''' Determines the commands to be run and compares them with the existing running commands.
Then starts new ones required and kills old ones no longer required.
'''
with self.process_lock:
current_commands = dict(map((lambda process: (process.name, process.command)),
... | [
"def",
"launch",
"(",
"self",
")",
":",
"with",
"self",
".",
"process_lock",
":",
"current_commands",
"=",
"dict",
"(",
"map",
"(",
"(",
"lambda",
"process",
":",
"(",
"process",
".",
"name",
",",
"process",
".",
"command",
")",
")",
",",
"self",
"."... | 53.208333 | 0.012308 |
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("LocationRef", dict(LocationOID=str(self.oid)))
builder.end("LocationRef") | [
"def",
"build",
"(",
"self",
",",
"builder",
")",
":",
"builder",
".",
"start",
"(",
"\"LocationRef\"",
",",
"dict",
"(",
"LocationOID",
"=",
"str",
"(",
"self",
".",
"oid",
")",
")",
")",
"builder",
".",
"end",
"(",
"\"LocationRef\"",
")"
] | 31.833333 | 0.010204 |
def visualize():
"""Trigger a visualization via the REST API
Takes a single image and generates the visualization data, returning the
output exactly as given by the target visualization.
"""
session['settings'] = {}
image_uid = request.args.get('image')
vis_name = request.args.get('visual... | [
"def",
"visualize",
"(",
")",
":",
"session",
"[",
"'settings'",
"]",
"=",
"{",
"}",
"image_uid",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'image'",
")",
"vis_name",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'visualizer'",
")",
"vis",
"=",... | 36.852941 | 0.001555 |
def get_coord_box(centre_x, centre_y, distance):
"""Get the square boundary coordinates for a given centre and distance"""
"""Todo: return coordinates inside a circle, rather than a square"""
return {
'top_left': (centre_x - distance, centre_y + distance),
'top_right': (centre_x + distance, ... | [
"def",
"get_coord_box",
"(",
"centre_x",
",",
"centre_y",
",",
"distance",
")",
":",
"\"\"\"Todo: return coordinates inside a circle, rather than a square\"\"\"",
"return",
"{",
"'top_left'",
":",
"(",
"centre_x",
"-",
"distance",
",",
"centre_y",
"+",
"distance",
")",
... | 52.666667 | 0.002075 |
def response_change(self, request, obj, **kwargs):
"""Redirects to the appropriate items' 'add' page on item change.
As we administer tree items within tree itself, we
should make some changes to redirection process.
"""
return self._redirect(request, super(TreeItemAdmin, self)... | [
"def",
"response_change",
"(",
"self",
",",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_redirect",
"(",
"request",
",",
"super",
"(",
"TreeItemAdmin",
",",
"self",
")",
".",
"response_change",
"(",
"request",
",",
... | 43 | 0.008547 |
def save_model(self, request, obj, form, change):
"""
Clear menu cache when changing menu structure
"""
if 'config.menu_structure' in form.changed_data:
from menus.menu_pool import menu_pool
menu_pool.clear(all=True)
return super(BlogConfigAdmin, self).sav... | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"if",
"'config.menu_structure'",
"in",
"form",
".",
"changed_data",
":",
"from",
"menus",
".",
"menu_pool",
"import",
"menu_pool",
"menu_pool",
".",
"clear",
... | 43.5 | 0.008451 |
def parse_plugin_metadata(content):
"""Parse summary metadata to a Python object.
Arguments:
content: The `content` field of a `SummaryMetadata` proto
corresponding to the pr_curves plugin.
Returns:
A `PrCurvesPlugin` protobuf object.
"""
if not isinstance(content, bytes):
raise TypeError(... | [
"def",
"parse_plugin_metadata",
"(",
"content",
")",
":",
"if",
"not",
"isinstance",
"(",
"content",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"'Content type must be bytes'",
")",
"result",
"=",
"plugin_data_pb2",
".",
"PrCurvePluginData",
".",
"FromStrin... | 32 | 0.008671 |
def obj(x):
"""Two Dimensional Shubert Function"""
j = np.arange(1, 6)
tmp1 = np.dot(j, np.cos((j+1)*x[0] + j))
tmp2 = np.dot(j, np.cos((j+1)*x[1] + j))
return tmp1 * tmp2 | [
"def",
"obj",
"(",
"x",
")",
":",
"j",
"=",
"np",
".",
"arange",
"(",
"1",
",",
"6",
")",
"tmp1",
"=",
"np",
".",
"dot",
"(",
"j",
",",
"np",
".",
"cos",
"(",
"(",
"j",
"+",
"1",
")",
"*",
"x",
"[",
"0",
"]",
"+",
"j",
")",
")",
"tm... | 27.142857 | 0.010204 |
def _pinyin_generator(chars, format):
"""Generate pinyin for chars, if char is not chinese character,
itself will be returned.
Chars must be unicode list.
"""
for char in chars:
key = "%X" % ord(char)
pinyin = pinyin_dict.get(key, char)
tone = pinyin_tone.get(key, 0)
... | [
"def",
"_pinyin_generator",
"(",
"chars",
",",
"format",
")",
":",
"for",
"char",
"in",
"chars",
":",
"key",
"=",
"\"%X\"",
"%",
"ord",
"(",
"char",
")",
"pinyin",
"=",
"pinyin_dict",
".",
"get",
"(",
"key",
",",
"char",
")",
"tone",
"=",
"pinyin_ton... | 38.8 | 0.001006 |
def macro2micro(self, macro_indices):
"""Return all micro indices which compose the elements specified by
``macro_indices``.
"""
def from_partition(partition, macro_indices):
micro_indices = itertools.chain.from_iterable(
partition[i] for i in macro_indices)
... | [
"def",
"macro2micro",
"(",
"self",
",",
"macro_indices",
")",
":",
"def",
"from_partition",
"(",
"partition",
",",
"macro_indices",
")",
":",
"micro_indices",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"partition",
"[",
"i",
"]",
"for",
"i",
... | 47.052632 | 0.002193 |
def build_trees(self):
"Build an unrooted consensus tree from filtered clade counts."
# storage
nodes = {}
idxarr = np.arange(len(self.fclade_counts[0][0]))
queue = []
## create dict of clade counts and set keys
countdict = defaultdict(int)
for clade, co... | [
"def",
"build_trees",
"(",
"self",
")",
":",
"# storage",
"nodes",
"=",
"{",
"}",
"idxarr",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"self",
".",
"fclade_counts",
"[",
"0",
"]",
"[",
"0",
"]",
")",
")",
"queue",
"=",
"[",
"]",
"## create dict of ... | 35.31746 | 0.002186 |
def fluxfrac(*mags):
"""Returns fraction of total flux in first argument, assuming all are magnitudes.
"""
Ftot = 0
for mag in mags:
Ftot += 10**(-0.4*mag)
F1 = 10**(-0.4*mags[0])
return F1/Ftot | [
"def",
"fluxfrac",
"(",
"*",
"mags",
")",
":",
"Ftot",
"=",
"0",
"for",
"mag",
"in",
"mags",
":",
"Ftot",
"+=",
"10",
"**",
"(",
"-",
"0.4",
"*",
"mag",
")",
"F1",
"=",
"10",
"**",
"(",
"-",
"0.4",
"*",
"mags",
"[",
"0",
"]",
")",
"return",... | 27.375 | 0.00885 |
def print_table(document, *columns):
""" Print json document as table """
headers = []
for _, header in columns:
headers.append(header)
table = []
for element in document:
row = []
for item, _ in columns:
if item in element:
row.append(element[item... | [
"def",
"print_table",
"(",
"document",
",",
"*",
"columns",
")",
":",
"headers",
"=",
"[",
"]",
"for",
"_",
",",
"header",
"in",
"columns",
":",
"headers",
".",
"append",
"(",
"header",
")",
"table",
"=",
"[",
"]",
"for",
"element",
"in",
"document",... | 28.666667 | 0.002252 |
def basic_publish(self, msg, exchange='', routing_key='',
mandatory=False, immediate=False, ticket=None):
"""
publish a message
This method publishes a message to a specific exchange. The
message will be routed to queues as defined by the exchange
configuration and distr... | [
"def",
"basic_publish",
"(",
"self",
",",
"msg",
",",
"exchange",
"=",
"''",
",",
"routing_key",
"=",
"''",
",",
"mandatory",
"=",
"False",
",",
"immediate",
"=",
"False",
",",
"ticket",
"=",
"None",
")",
":",
"args",
"=",
"AMQPWriter",
"(",
")",
"if... | 33.741935 | 0.000929 |
def unsigned_request(self, path, payload=None):
"""
generic bitpay usigned wrapper
passing a payload will do a POST, otherwise a GET
"""
headers = {"content-type": "application/json", "accept": "application/json", "X-accept-version": "2.0.0"}
try:
if payload:
response = requests.po... | [
"def",
"unsigned_request",
"(",
"self",
",",
"path",
",",
"payload",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"\"content-type\"",
":",
"\"application/json\"",
",",
"\"accept\"",
":",
"\"application/json\"",
",",
"\"X-accept-version\"",
":",
"\"2.0.0\"",
"}",
... | 42.285714 | 0.01157 |
def protein_subsequences_around_mutations(effects, padding_around_mutation):
"""
From each effect get a mutant protein sequence and pull out a subsequence
around the mutation (based on the given padding). Returns a dictionary
of subsequences and a dictionary of subsequence start offsets.
"""
pro... | [
"def",
"protein_subsequences_around_mutations",
"(",
"effects",
",",
"padding_around_mutation",
")",
":",
"protein_subsequences",
"=",
"{",
"}",
"protein_subsequence_start_offsets",
"=",
"{",
"}",
"for",
"effect",
"in",
"effects",
":",
"protein_sequence",
"=",
"effect",... | 50 | 0.000613 |
def get_all_storage_keys(self):
"""Returns the keys to be removed by `clear` in aggressive mode
For the parameters, see BaseIndex.get_all_storage_keys
"""
parts1 = [
self.model._name,
self.field.name,
]
parts2 = parts1 + ['*'] # for indexes ta... | [
"def",
"get_all_storage_keys",
"(",
"self",
")",
":",
"parts1",
"=",
"[",
"self",
".",
"model",
".",
"_name",
",",
"self",
".",
"field",
".",
"name",
",",
"]",
"parts2",
"=",
"parts1",
"+",
"[",
"'*'",
"]",
"# for indexes taking args, like for hashfields",
... | 24.9375 | 0.002413 |
def copy_file_data(src_file, dst_file, chunk_size=None):
# type: (IO, IO, Optional[int]) -> None
"""Copy data from one file object to another.
Arguments:
src_file (io.IOBase): File open for reading.
dst_file (io.IOBase): File open for writing.
chunk_size (int): Number of bytes to co... | [
"def",
"copy_file_data",
"(",
"src_file",
",",
"dst_file",
",",
"chunk_size",
"=",
"None",
")",
":",
"# type: (IO, IO, Optional[int]) -> None",
"_chunk_size",
"=",
"1024",
"*",
"1024",
"if",
"chunk_size",
"is",
"None",
"else",
"chunk_size",
"read",
"=",
"src_file"... | 38 | 0.001511 |
def frange(start, end, inc=1.0):
"""
A range function, that accepts float increments and reversed direction.
See also numpy.linspace()
"""
start = 1.0*start
end = 1.0*end
inc = 1.0*inc
# if we got a dumb increment
if not inc: return _n.array([start,end])
# if the incremen... | [
"def",
"frange",
"(",
"start",
",",
"end",
",",
"inc",
"=",
"1.0",
")",
":",
"start",
"=",
"1.0",
"*",
"start",
"end",
"=",
"1.0",
"*",
"end",
"inc",
"=",
"1.0",
"*",
"inc",
"# if we got a dumb increment",
"if",
"not",
"inc",
":",
"return",
"_n",
"... | 22.727273 | 0.009597 |
def aes_b64_decrypt(value, secret, block_size=AES.block_size):
""" AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | [
"def",
"aes_b64_decrypt",
"(",
"value",
",",
"secret",
",",
"block_size",
"=",
"AES",
".",
"block_size",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"iv",
"=",
"value",
"[",
":",
"block_size",
"]",
"cipher",
"=",
"AES",
".",
"new",
"(",
"secre... | 40.136364 | 0.001106 |
def parse_color(color):
""" Parses color into a vtk friendly rgb list """
if color is None:
color = rcParams['color']
if isinstance(color, str):
return vtki.string_to_rgb(color)
elif len(color) == 3:
return color
else:
raise Exception("""
Invalid color input
M... | [
"def",
"parse_color",
"(",
"color",
")",
":",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"rcParams",
"[",
"'color'",
"]",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
":",
"return",
"vtki",
".",
"string_to_rgb",
"(",
"color",
")",
"elif",
... | 28.5 | 0.002123 |
def get_kde_contour(self, xax="area_um", yax="deform", xacc=None,
yacc=None, kde_type="histogram", kde_kwargs={},
xscale="linear", yscale="linear"):
"""Evaluate the kernel density estimate for contour plots
Parameters
----------
xax: str
... | [
"def",
"get_kde_contour",
"(",
"self",
",",
"xax",
"=",
"\"area_um\"",
",",
"yax",
"=",
"\"deform\"",
",",
"xacc",
"=",
"None",
",",
"yacc",
"=",
"None",
",",
"kde_type",
"=",
"\"histogram\"",
",",
"kde_kwargs",
"=",
"{",
"}",
",",
"xscale",
"=",
"\"li... | 33.21519 | 0.00148 |
def p_identifier(self, tree):
''' V ::= IDENTIFIER '''
tree.value = tree.attr
tree.svalue = tree.attr | [
"def",
"p_identifier",
"(",
"self",
",",
"tree",
")",
":",
"tree",
".",
"value",
"=",
"tree",
".",
"attr",
"tree",
".",
"svalue",
"=",
"tree",
".",
"attr"
] | 31.25 | 0.015625 |
def active_subscriptions(self):
"""
Returns active subscriptions (subscriptions with an active status that end in the future).
"""
return self.subscriptions.filter(
status=enums.SubscriptionStatus.active, current_period_end__gt=timezone.now()
) | [
"def",
"active_subscriptions",
"(",
"self",
")",
":",
"return",
"self",
".",
"subscriptions",
".",
"filter",
"(",
"status",
"=",
"enums",
".",
"SubscriptionStatus",
".",
"active",
",",
"current_period_end__gt",
"=",
"timezone",
".",
"now",
"(",
")",
")"
] | 35.857143 | 0.038911 |
async def fetchval(self, query, *args, column=0, timeout=None):
"""Run a query and return a value in the first row.
:param str query: Query text.
:param args: Query arguments.
:param int column: Numeric index within the record of the value to
return (defaults ... | [
"async",
"def",
"fetchval",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"column",
"=",
"0",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_check_open",
"(",
")",
"data",
"=",
"await",
"self",
".",
"_execute",
"(",
"query",
",",
"args",... | 44.35 | 0.002208 |
def cv_factory(data=None, folds=5, repeat=1, reporters=[], metrics=None,
cv_runner=None, **kwargs):
"""Shortcut to iterate and cross-validate models.
All ModelDefinition kwargs should be iterables that can be
passed to model_definition_factory.
Parameters:
___________
data:
... | [
"def",
"cv_factory",
"(",
"data",
"=",
"None",
",",
"folds",
"=",
"5",
",",
"repeat",
"=",
"1",
",",
"reporters",
"=",
"[",
"]",
",",
"metrics",
"=",
"None",
",",
"cv_runner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cv_runner",
"=",
"cv_... | 32.782609 | 0.000644 |
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will b... | [
"def",
"_merge_tops_merge",
"(",
"self",
",",
"tops",
")",
":",
"top",
"=",
"DefaultOrderedDict",
"(",
"OrderedDict",
")",
"# Check base env first as it is authoritative",
"base_tops",
"=",
"tops",
".",
"pop",
"(",
"'base'",
",",
"DefaultOrderedDict",
"(",
"OrderedD... | 46.9 | 0.001671 |
def deriv(self, x: str, ctype: ContentType) -> SchemaPattern:
"""Return derivative of the receiver."""
return (Empty() if
self.name == x and self._active(ctype)
else NotAllowed()) | [
"def",
"deriv",
"(",
"self",
",",
"x",
":",
"str",
",",
"ctype",
":",
"ContentType",
")",
"->",
"SchemaPattern",
":",
"return",
"(",
"Empty",
"(",
")",
"if",
"self",
".",
"name",
"==",
"x",
"and",
"self",
".",
"_active",
"(",
"ctype",
")",
"else",
... | 44.6 | 0.008811 |
def picard_merge(picard, in_files, out_file=None,
merge_seq_dicts=False):
"""Merge multiple BAM files together with Picard.
"""
if out_file is None:
out_file = "%smerge.bam" % os.path.commonprefix(in_files)
if not file_exists(out_file):
with tx_tmpdir(picard._config) as ... | [
"def",
"picard_merge",
"(",
"picard",
",",
"in_files",
",",
"out_file",
"=",
"None",
",",
"merge_seq_dicts",
"=",
"False",
")",
":",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
"\"%smerge.bam\"",
"%",
"os",
".",
"path",
".",
"commonprefix",
"(",
... | 45.842105 | 0.001125 |
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem hu... | [
"def",
"saltmem",
"(",
"human_readable",
"=",
"False",
")",
":",
"# psutil.Process defaults to current process (`os.getpid()`)",
"p",
"=",
"psutil",
".",
"Process",
"(",
")",
"# Use oneshot to get a snapshot",
"with",
"p",
".",
"oneshot",
"(",
")",
":",
"mem",
"=",
... | 21.222222 | 0.001669 |
def state(self):
"""Returns a new JIT state. You have to clean up by calling .destroy()
afterwards.
"""
return Emitter(weakref.proxy(self.lib), self.lib.jit_new_state()) | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"Emitter",
"(",
"weakref",
".",
"proxy",
"(",
"self",
".",
"lib",
")",
",",
"self",
".",
"lib",
".",
"jit_new_state",
"(",
")",
")"
] | 39.4 | 0.00995 |
def fill(metrics_headers=()):
"""Add the metrics headers known to GAX.
Return an OrderedDict with all of the metrics headers provided to
this function, as well as the metrics known to GAX (such as its own
version, the GRPC version, etc.).
"""
# Create an ordered dictionary with the Python versi... | [
"def",
"fill",
"(",
"metrics_headers",
"=",
"(",
")",
")",
":",
"# Create an ordered dictionary with the Python version, which",
"# should go first.",
"answer",
"=",
"collections",
".",
"OrderedDict",
"(",
"(",
"(",
"'gl-python'",
",",
"platform",
".",
"python_version",... | 34.777778 | 0.001036 |
def drawdown_idx(self):
"""Drawdown index; TSeries of drawdown from running HWM.
Returns
-------
TSeries
"""
ri = self.ret_idx()
return ri / np.maximum(ri.cummax(), 1.0) - 1.0 | [
"def",
"drawdown_idx",
"(",
"self",
")",
":",
"ri",
"=",
"self",
".",
"ret_idx",
"(",
")",
"return",
"ri",
"/",
"np",
".",
"maximum",
"(",
"ri",
".",
"cummax",
"(",
")",
",",
"1.0",
")",
"-",
"1.0"
] | 22.4 | 0.008584 |
def check_uniqe(self, obj_class, error_msg=_('Must be unique'), **kwargs):
""" check if this object is unique """
if obj_class.objects.filter(**kwargs).exclude(pk=self.instance.pk):
raise forms.ValidationError(error_msg) | [
"def",
"check_uniqe",
"(",
"self",
",",
"obj_class",
",",
"error_msg",
"=",
"_",
"(",
"'Must be unique'",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"obj_class",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"kwargs",
")",
".",
"exclude",
"(",
"pk... | 61.25 | 0.008065 |
def extract_key_value(line, environ):
"""Return key, value from given line if present, else return None.
"""
segments = line.split("=", 1)
if len(segments) < 2:
return None
key, value = segments
# foo passes through as-is (with spaces stripped)
# '{foo}' passes through literally
... | [
"def",
"extract_key_value",
"(",
"line",
",",
"environ",
")",
":",
"segments",
"=",
"line",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"if",
"len",
"(",
"segments",
")",
"<",
"2",
":",
"return",
"None",
"key",
",",
"value",
"=",
"segments",
"# foo pa... | 34 | 0.001506 |
def merge_parameter_lists(*parameter_definitions):
"""
Merge multiple lists of parameters into a single list. If there are any
duplicate definitions, the last write wins.
"""
merged_parameters = {}
for parameter_list in parameter_definitions:
for parameter in parameter_list:
... | [
"def",
"merge_parameter_lists",
"(",
"*",
"parameter_definitions",
")",
":",
"merged_parameters",
"=",
"{",
"}",
"for",
"parameter_list",
"in",
"parameter_definitions",
":",
"for",
"parameter",
"in",
"parameter_list",
":",
"key",
"=",
"(",
"parameter",
"[",
"'name... | 39.818182 | 0.002232 |
def _evolve(self, state, qargs=None):
"""Evolve a quantum state by the QuantumChannel.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Retu... | [
"def",
"_evolve",
"(",
"self",
",",
"state",
",",
"qargs",
"=",
"None",
")",
":",
"# If subsystem evolution we use the SuperOp representation",
"if",
"qargs",
"is",
"not",
"None",
":",
"return",
"SuperOp",
"(",
"self",
")",
".",
"_evolve",
"(",
"state",
",",
... | 42.075 | 0.002323 |
def _addPartitionId(self, index, partitionId=None):
"""
Adds partition id for pattern index
"""
if partitionId is None:
self._partitionIdList.append(numpy.inf)
else:
self._partitionIdList.append(partitionId)
indices = self._partitionIdMap.get(partitionId, [])
indices.append(i... | [
"def",
"_addPartitionId",
"(",
"self",
",",
"index",
",",
"partitionId",
"=",
"None",
")",
":",
"if",
"partitionId",
"is",
"None",
":",
"self",
".",
"_partitionIdList",
".",
"append",
"(",
"numpy",
".",
"inf",
")",
"else",
":",
"self",
".",
"_partitionId... | 33.181818 | 0.016 |
def needle(reference, query, gap_open=-15, gap_extend=0,
matrix=submat.DNA_SIMPLE):
'''Do a Needleman-Wunsch alignment.
:param reference: Reference sequence.
:type reference: coral.DNA
:param query: Sequence to align against the reference.
:type query: coral.DNA
:param gapopen: Penal... | [
"def",
"needle",
"(",
"reference",
",",
"query",
",",
"gap_open",
"=",
"-",
"15",
",",
"gap_extend",
"=",
"0",
",",
"matrix",
"=",
"submat",
".",
"DNA_SIMPLE",
")",
":",
"# Align using cython Needleman-Wunsch",
"aligned_ref",
",",
"aligned_res",
"=",
"aligner"... | 41.30303 | 0.000717 |
def getlang_by_name(name):
"""
Try to lookup a Language object by name, e.g. 'English', in internal language list.
Returns None if lookup by language name fails in resources/languagelookup.json.
"""
direct_match = _iget(name, _LANGUAGE_NAME_LOOKUP)
if direct_match:
return direct_match
... | [
"def",
"getlang_by_name",
"(",
"name",
")",
":",
"direct_match",
"=",
"_iget",
"(",
"name",
",",
"_LANGUAGE_NAME_LOOKUP",
")",
"if",
"direct_match",
":",
"return",
"direct_match",
"else",
":",
"simple_name",
"=",
"name",
".",
"split",
"(",
"','",
")",
"[",
... | 45 | 0.009074 |
def evaluate(data_file, pred_file):
'''
Evaluate.
'''
expected_version = '1.1'
with open(data_file) as dataset_file:
dataset_json = json.load(dataset_file)
if dataset_json['version'] != expected_version:
print('Evaluation expects v-' + expected_version +
... | [
"def",
"evaluate",
"(",
"data_file",
",",
"pred_file",
")",
":",
"expected_version",
"=",
"'1.1'",
"with",
"open",
"(",
"data_file",
")",
"as",
"dataset_file",
":",
"dataset_json",
"=",
"json",
".",
"load",
"(",
"dataset_file",
")",
"if",
"dataset_json",
"["... | 40.166667 | 0.001351 |
def bresenham(x0, y0, x1, y1):
"""Yield integer coordinates on the line from (x0, y0) to (x1, y1).
Input coordinates should be integers.
The result will contain both the start and the end point.
"""
dx = x1 - x0
dy = y1 - y0
xsign = 1 if dx > 0 else -1
ysign = 1 if dy > 0 else -1
... | [
"def",
"bresenham",
"(",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
")",
":",
"dx",
"=",
"x1",
"-",
"x0",
"dy",
"=",
"y1",
"-",
"y0",
"xsign",
"=",
"1",
"if",
"dx",
">",
"0",
"else",
"-",
"1",
"ysign",
"=",
"1",
"if",
"dy",
">",
"0",
"else",
... | 20.774194 | 0.001484 |
def check_extract_from_egg(pth, todir=None):
r"""
Check if path points to a file inside a python egg file, extract the
file from the egg to a cache directory (following pkg_resources
convention) and return [(extracted path, egg file path, relative path
inside egg file)].
Otherwise, just return [... | [
"def",
"check_extract_from_egg",
"(",
"pth",
",",
"todir",
"=",
"None",
")",
":",
"rv",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"altsep",
":",
"pth",
"=",
"pth",
".",
"replace",
"(",
"os",
".",
"path",
".",
"altsep",
",",
"os",
".",
"path",
... | 46.803922 | 0.000821 |
def _Notify(username, notification_type, message, object_reference):
"""Schedules a new-style REL_DB user notification."""
# Do not try to notify system users (e.g. Cron).
if username in aff4_users.GRRUser.SYSTEM_USERS:
return
if object_reference:
uc = object_reference.UnionCast()
if hasattr(uc, "... | [
"def",
"_Notify",
"(",
"username",
",",
"notification_type",
",",
"message",
",",
"object_reference",
")",
":",
"# Do not try to notify system users (e.g. Cron).",
"if",
"username",
"in",
"aff4_users",
".",
"GRRUser",
".",
"SYSTEM_USERS",
":",
"return",
"if",
"object_... | 33.421053 | 0.012251 |
def set_ro(ro):
"""
NAME:
set_ro
PURPOSE:
set the global configuration value of ro (distance scale)
INPUT:
ro - scale in kpc or astropy Quantity
OUTPUT:
(none)
HISTORY:
2016-01-05 - Written - Bovy (UofT)
"""
if _APY_LOADED and isinstance(ro,units.Quanti... | [
"def",
"set_ro",
"(",
"ro",
")",
":",
"if",
"_APY_LOADED",
"and",
"isinstance",
"(",
"ro",
",",
"units",
".",
"Quantity",
")",
":",
"ro",
"=",
"ro",
".",
"to",
"(",
"units",
".",
"kpc",
")",
".",
"value",
"__config__",
".",
"set",
"(",
"'normalizat... | 24.5625 | 0.012255 |
def setRti(self, rti):
""" Updates the current VisItem from the contents of the repo tree item.
Is a slot but the signal is usually connected to the Collector, which then calls
this function directly.
"""
check_class(rti, BaseRti)
#assert rti.isSliceable, "RTI mu... | [
"def",
"setRti",
"(",
"self",
",",
"rti",
")",
":",
"check_class",
"(",
"rti",
",",
"BaseRti",
")",
"#assert rti.isSliceable, \"RTI must be sliceable\" # TODO: maybe later",
"self",
".",
"_rti",
"=",
"rti",
"self",
".",
"_updateWidgets",
"(",
")",
"self",
".",
"... | 35.833333 | 0.011338 |
def message_info(exchange, routing_key, properties):
"""Return info about a message using the same conditional constructs
:param str exchange: The exchange the message was published to
:param str routing_key: The routing key used
:param properties: The AMQP message properties
:type properties: pika... | [
"def",
"message_info",
"(",
"exchange",
",",
"routing_key",
",",
"properties",
")",
":",
"output",
"=",
"[",
"]",
"if",
"properties",
".",
"message_id",
":",
"output",
".",
"append",
"(",
"properties",
".",
"message_id",
")",
"if",
"properties",
".",
"corr... | 35.571429 | 0.001304 |
def make_root(self, name): # noqa: D302
r"""
Make a sub-node the root node of the tree.
All nodes not belonging to the sub-tree are deleted
:param name: New root node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
... | [
"def",
"make_root",
"(",
"self",
",",
"name",
")",
":",
"# noqa: D302",
"if",
"self",
".",
"_validate_node_name",
"(",
"name",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Argument `name` is not valid\"",
")",
"if",
"(",
"name",
"!=",
"self",
".",
"root_name",
... | 31.695652 | 0.001331 |
def move_item(self, token, item_id, src_folder_id, dest_folder_id):
"""
Move an item from the source folder to the destination folder.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item to be moved
:type item_id: ... | [
"def",
"move_item",
"(",
"self",
",",
"token",
",",
"item_id",
",",
"src_folder_id",
",",
"dest_folder_id",
")",
":",
"parameters",
"=",
"dict",
"(",
")",
"parameters",
"[",
"'token'",
"]",
"=",
"token",
"parameters",
"[",
"'id'",
"]",
"=",
"item_id",
"p... | 41.652174 | 0.002041 |
def all_events(cls):
"""
Return all events that all subclasses have so far registered to publish.
"""
all_evts = set()
for cls, evts in cls.__all_events__.items():
all_evts.update(evts)
return all_evts | [
"def",
"all_events",
"(",
"cls",
")",
":",
"all_evts",
"=",
"set",
"(",
")",
"for",
"cls",
",",
"evts",
"in",
"cls",
".",
"__all_events__",
".",
"items",
"(",
")",
":",
"all_evts",
".",
"update",
"(",
"evts",
")",
"return",
"all_evts"
] | 31.75 | 0.011494 |
def acquire_lock(self):
"""
Acquire the lock. Blocks indefinitely until lock is available
unless `lock_timeout` was supplied. If the lock_timeout elapses,
raises LockTimeout.
"""
# first ensure that a record exists for this session id
try:
self.collection.insert_one(dict(_id=self.id))
except pymongo.... | [
"def",
"acquire_lock",
"(",
"self",
")",
":",
"# first ensure that a record exists for this session id",
"try",
":",
"self",
".",
"collection",
".",
"insert_one",
"(",
"dict",
"(",
"_id",
"=",
"self",
".",
"id",
")",
")",
"except",
"pymongo",
".",
"errors",
".... | 31.148148 | 0.032295 |
def verify_signature(message, key, signature):
"""
This function will verify the authenticity of a digital signature.
For security purposes, Nylas includes a digital signature in the headers
of every webhook notification, so that clients can verify that the
webhook request came from Nylas and no one... | [
"def",
"verify_signature",
"(",
"message",
",",
"key",
",",
"signature",
")",
":",
"digest",
"=",
"hmac",
".",
"new",
"(",
"key",
",",
"msg",
"=",
"message",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
")",
".",
"hexdigest",
"(",
")",
"return",
... | 51.4 | 0.001912 |
def pipe_strregex(context=None, _INPUT=None, conf=None, **kwargs):
"""A string module that replaces text using regexes. Each has the general
format: "In [field] replace [regex pattern] with [text]". Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : iterable of items or s... | [
"def",
"pipe_strregex",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"splits",
"=",
"get_splits",
"(",
"_INPUT",
",",
"conf",
"[",
"'RULE'",
"]",
",",
"*",
"*",
"cdicts",
"(",... | 30.52 | 0.001271 |
async def rewrite_middleware(server, request):
'''
Sanic middleware that utilizes a security class's "rewrite" method to
check
'''
if singletons.settings.SECURITY is not None:
security_class = singletons.settings.load('SECURITY')
else:
security_class = DummySecurity
security ... | [
"async",
"def",
"rewrite_middleware",
"(",
"server",
",",
"request",
")",
":",
"if",
"singletons",
".",
"settings",
".",
"SECURITY",
"is",
"not",
"None",
":",
"security_class",
"=",
"singletons",
".",
"settings",
".",
"load",
"(",
"'SECURITY'",
")",
"else",
... | 30.944444 | 0.001742 |
def is_list_of_matching_dicts(list_of_dicts, expected_keys=None):
"""Comprueba que una lista esté compuesta únicamente por diccionarios,
que comparten exactamente las mismas claves.
Args:
list_of_dicts (list): Lista de diccionarios a comparar.
expected_keys (set): Conjunto de las claves que... | [
"def",
"is_list_of_matching_dicts",
"(",
"list_of_dicts",
",",
"expected_keys",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"list_of_dicts",
",",
"list",
")",
"and",
"len",
"(",
"list_of_dicts",
")",
"==",
"0",
":",
"return",
"False",
"is_not_list_msg",
"=... | 38.34375 | 0.000795 |
def _pivoting(tableau, pivot, pivot_row):
"""
Perform a pivoting step. Modify `tableau` in place.
Parameters
----------
tableau : ndarray(float, ndim=2)
Array containing the tableau.
pivot : scalar(int)
Pivot.
pivot_row : scalar(int)
Pivot row index.
Returns
... | [
"def",
"_pivoting",
"(",
"tableau",
",",
"pivot",
",",
"pivot_row",
")",
":",
"nrows",
",",
"ncols",
"=",
"tableau",
".",
"shape",
"pivot_elt",
"=",
"tableau",
"[",
"pivot_row",
",",
"pivot",
"]",
"for",
"j",
"in",
"range",
"(",
"ncols",
")",
":",
"t... | 21.405405 | 0.001208 |
def register_operators(*operators):
"""
Registers one or multiple operators in the test engine.
"""
def validate(operator):
if isoperator(operator):
return True
raise NotImplementedError('invalid operator: {}'.format(operator))
def register(operator):
# Register... | [
"def",
"register_operators",
"(",
"*",
"operators",
")",
":",
"def",
"validate",
"(",
"operator",
")",
":",
"if",
"isoperator",
"(",
"operator",
")",
":",
"return",
"True",
"raise",
"NotImplementedError",
"(",
"'invalid operator: {}'",
".",
"format",
"(",
"ope... | 35.076923 | 0.001067 |
def recursive_dirname(f):
"""Given a relative path like 'a/b/c/d', yield all ascending path components like:
'a/b/c/d'
'a/b/c'
'a/b'
'a'
''
"""
prev = None
while f != prev:
yield f
prev = f
f = os.path.dirname(f)
yield '' | [
"def",
"recursive_dirname",
"(",
"f",
")",
":",
"prev",
"=",
"None",
"while",
"f",
"!=",
"prev",
":",
"yield",
"f",
"prev",
"=",
"f",
"f",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"f",
")",
"yield",
"''"
] | 18 | 0.021127 |
def merge_entity(self, entity, if_match='*'):
'''
Adds a merge entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.merge_entity` for more
information on merges.
The operation will not be executed until the batch is committed.
... | [
"def",
"merge_entity",
"(",
"self",
",",
"entity",
",",
"if_match",
"=",
"'*'",
")",
":",
"request",
"=",
"_merge_entity",
"(",
"entity",
",",
"if_match",
")",
"self",
".",
"_add_to_batch",
"(",
"entity",
"[",
"'PartitionKey'",
"]",
",",
"entity",
"[",
"... | 53 | 0.010475 |
def for_type(self, typ, func):
"""Add a format function for a given type.
Parameters
-----------
typ : class
The class of the object that will be formatted using `func`.
func : callable
The callable that will be called to compute the format data. The
... | [
"def",
"for_type",
"(",
"self",
",",
"typ",
",",
"func",
")",
":",
"oldfunc",
"=",
"self",
".",
"type_printers",
".",
"get",
"(",
"typ",
",",
"None",
")",
"if",
"func",
"is",
"not",
"None",
":",
"# To support easy restoration of old printers, we need to ignore... | 40.05 | 0.002439 |
def get(self, value):
"""Returns the VRF configuration as a resource dict.
Args:
value (string): The vrf name to retrieve from the
running configuration.
Returns:
A Python dict object containing the VRF attributes as
key/value pairs.
... | [
"def",
"get",
"(",
"self",
",",
"value",
")",
":",
"config",
"=",
"self",
".",
"get_block",
"(",
"'vrf definition %s'",
"%",
"value",
")",
"if",
"not",
"config",
":",
"return",
"None",
"response",
"=",
"dict",
"(",
"vrf_name",
"=",
"value",
")",
"respo... | 31.966667 | 0.002024 |
def s1n(self):
"""Return 1 neutron separation energy"""
M_N = 8.0713171 # neutron mass excess in MeV
f = lambda parent, daugther: -parent + daugther + M_N
return self.derived('s1n', (0, -1), f) | [
"def",
"s1n",
"(",
"self",
")",
":",
"M_N",
"=",
"8.0713171",
"# neutron mass excess in MeV",
"f",
"=",
"lambda",
"parent",
",",
"daugther",
":",
"-",
"parent",
"+",
"daugther",
"+",
"M_N",
"return",
"self",
".",
"derived",
"(",
"'s1n'",
",",
"(",
"0",
... | 45.8 | 0.012876 |
def list_backups(self, encrypted=None, compressed=None, content_type=None,
database=None, servername=None):
"""
List stored files except given filter. If filter is None, it won't be
used. ``content_type`` must be ``'db'`` for database backups or
``'media'`` for media... | [
"def",
"list_backups",
"(",
"self",
",",
"encrypted",
"=",
"None",
",",
"compressed",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"database",
"=",
"None",
",",
"servername",
"=",
"None",
")",
":",
"if",
"content_type",
"not",
"in",
"(",
"'db'",
... | 40 | 0.002122 |
def plot(self,**kwargs):
""" get a cheap plot of the Vario2d
Parameters
----------
**kwargs : (dict)
keyword arguments to use for plotting
Returns
-------
ax : matplotlib.pyplot.axis
Note
----
optional arguments in kwargs inc... | [
"def",
"plot",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"\"error importing matplotlib: {0}\"",
".",
"format",
"(",
"str... | 26.193548 | 0.010689 |
def _main():
"""Parse options and run checks on Python source."""
import signal
# Handle "Broken pipe" gracefully
try:
signal.signal(signal.SIGPIPE, lambda signum, frame: sys.exit(1))
except AttributeError:
pass # not supported on Windows
style_guide = StyleGuide(parse_argv=... | [
"def",
"_main",
"(",
")",
":",
"import",
"signal",
"# Handle \"Broken pipe\" gracefully",
"try",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGPIPE",
",",
"lambda",
"signum",
",",
"frame",
":",
"sys",
".",
"exit",
"(",
"1",
")",
")",
"except",
"A... | 26.6875 | 0.00113 |
def isdir(self, path):
"""
Is the parameter S3 path a directory?
"""
(bucket, key) = self._path_to_bucket_and_key(path)
s3_bucket = self.s3.Bucket(bucket)
# root is a directory
if self._is_root(key):
return True
for suffix in (S3_DIRECTORY_M... | [
"def",
"isdir",
"(",
"self",
",",
"path",
")",
":",
"(",
"bucket",
",",
"key",
")",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"path",
")",
"s3_bucket",
"=",
"self",
".",
"s3",
".",
"Bucket",
"(",
"bucket",
")",
"# root is a directory",
"if",
"s... | 30.935484 | 0.002022 |
def serialize(objects=None):
"""A simple wrapper of Django's serializer with defaults
for JSON and natural keys.
Note: use_natural_primary_keys is False as once
a pk is set, it should not be changed throughout the
distributed data.
"""
return serializers.serialize(
"json",
... | [
"def",
"serialize",
"(",
"objects",
"=",
"None",
")",
":",
"return",
"serializers",
".",
"serialize",
"(",
"\"json\"",
",",
"objects",
",",
"ensure_ascii",
"=",
"True",
",",
"use_natural_foreign_keys",
"=",
"True",
",",
"use_natural_primary_keys",
"=",
"False",
... | 26.5625 | 0.002273 |
def note_to_int(note):
"""Convert notes in the form of C, C#, Cb, C##, etc. to an integer in the
range of 0-11.
Throw a NoteFormatError exception if the note format is not recognised.
"""
if is_valid_note(note):
val = _note_dict[note[0]]
else:
raise NoteFormatError("Unknown note... | [
"def",
"note_to_int",
"(",
"note",
")",
":",
"if",
"is_valid_note",
"(",
"note",
")",
":",
"val",
"=",
"_note_dict",
"[",
"note",
"[",
"0",
"]",
"]",
"else",
":",
"raise",
"NoteFormatError",
"(",
"\"Unknown note format '%s'\"",
"%",
"note",
")",
"# Check f... | 27.833333 | 0.001931 |
def interface(self, iface_name):
"""
Returns the interface with the given name, or raises RpcException if no interface matches
"""
if self.has_interface(iface_name):
return self.interfaces[iface_name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown i... | [
"def",
"interface",
"(",
"self",
",",
"iface_name",
")",
":",
"if",
"self",
".",
"has_interface",
"(",
"iface_name",
")",
":",
"return",
"self",
".",
"interfaces",
"[",
"iface_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_PARAMS",
",",
... | 42.625 | 0.011494 |
def add_dat_file(filename, settings, container=None, **kwargs):
""" Read a RES2DINV-style file produced by the ABEM export program.
"""
# each type is read by a different function
importers = {
# general array type
11: _read_general_type,
}
file_type, content = _read_file(filena... | [
"def",
"add_dat_file",
"(",
"filename",
",",
"settings",
",",
"container",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# each type is read by a different function",
"importers",
"=",
"{",
"# general array type",
"11",
":",
"_read_general_type",
",",
"}",
"fil... | 26.068966 | 0.001276 |
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen... | [
"def",
"call",
"(",
"self",
",",
"low",
",",
"chunks",
"=",
"None",
",",
"running",
"=",
"None",
",",
"retries",
"=",
"1",
")",
":",
"use_uptime",
"=",
"False",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"'/proc/uptime'",
")",
":",
"use_uptime",
... | 46.790984 | 0.002487 |
def to_result(self, iface_name, func_name, resp):
"""
Takes a JSON-RPC response and checks for an "error" slot. If it exists,
a RpcException is raised. If no "error" slot exists, the "result" slot is
returned.
If validate_response==True on the Client constructor, the result is... | [
"def",
"to_result",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"resp",
")",
":",
"if",
"resp",
".",
"has_key",
"(",
"\"error\"",
")",
":",
"e",
"=",
"resp",
"[",
"\"error\"",
"]",
"data",
"=",
"None",
"if",
"e",
".",
"has_key",
"(",
"\"... | 34.9 | 0.009294 |
def forwards(self, orm):
"Write your forwards methods here."
orm['avocado.DataField'].objects.get_or_create(app_name='samples', model_name='batch', field_name='id',
defaults=dict(published=True, name='Batch', name_plural='Batches')) | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"orm",
"[",
"'avocado.DataField'",
"]",
".",
"objects",
".",
"get_or_create",
"(",
"app_name",
"=",
"'samples'",
",",
"model_name",
"=",
"'batch'",
",",
"field_name",
"=",
"'id'",
",",
"defaults",
"=",
... | 65.25 | 0.018939 |
def send_request(url, method, data,
args, params, headers, cookies, timeout, is_json, verify_cert):
"""
Forge and send HTTP request.
"""
## Parse url args
for p in args:
url = url.replace(':' + p, str(args[p]))
try:
if data:
if is_json:
headers['Content-Type'] = 'application/json'
data = json.du... | [
"def",
"send_request",
"(",
"url",
",",
"method",
",",
"data",
",",
"args",
",",
"params",
",",
"headers",
",",
"cookies",
",",
"timeout",
",",
"is_json",
",",
"verify_cert",
")",
":",
"## Parse url args",
"for",
"p",
"in",
"args",
":",
"url",
"=",
"ur... | 21.627119 | 0.047976 |
def normalize_scheme(path, ext):
"""
Normalize scheme for paths related to hdfs
"""
path = addextension(path, ext)
parsed = urlparse(path)
if parsed.scheme:
# this appears to already be a fully-qualified URI
return path
else:
# this looks like a local path spec
... | [
"def",
"normalize_scheme",
"(",
"path",
",",
"ext",
")",
":",
"path",
"=",
"addextension",
"(",
"path",
",",
"ext",
")",
"parsed",
"=",
"urlparse",
"(",
"path",
")",
"if",
"parsed",
".",
"scheme",
":",
"# this appears to already be a fully-qualified URI",
"ret... | 30.947368 | 0.00165 |
def release(self, path, fh):
"Run after a read or write operation has finished. This is where we upload on writes"
#print "release! inpath:", path in self.__newfiles.keys()
# if the path exists in self.__newfiles.keys(), we have a new version to upload
try:
f = self.__newfile... | [
"def",
"release",
"(",
"self",
",",
"path",
",",
"fh",
")",
":",
"#print \"release! inpath:\", path in self.__newfiles.keys()",
"# if the path exists in self.__newfiles.keys(), we have a new version to upload",
"try",
":",
"f",
"=",
"self",
".",
"__newfiles",
"[",
"path",
"... | 43.533333 | 0.013493 |
def _netflowv9_defragment_packet(pkt, definitions, definitions_opts, ignored):
"""Used internally to process a single packet during defragmenting"""
# Dataflowset definitions
if NetflowFlowsetV9 in pkt:
current = pkt
while NetflowFlowsetV9 in current:
current = current[NetflowFlo... | [
"def",
"_netflowv9_defragment_packet",
"(",
"pkt",
",",
"definitions",
",",
"definitions_opts",
",",
"ignored",
")",
":",
"# Dataflowset definitions",
"if",
"NetflowFlowsetV9",
"in",
"pkt",
":",
"current",
"=",
"pkt",
"while",
"NetflowFlowsetV9",
"in",
"current",
":... | 37.697917 | 0.000269 |
def _handshake(self):
"""
Perform an initial TLS handshake
"""
self._ssl = None
self._rbio = None
self._wbio = None
try:
self._ssl = libssl.SSL_new(self._session._ssl_ctx)
if is_null(self._ssl):
self._ssl = None
... | [
"def",
"_handshake",
"(",
"self",
")",
":",
"self",
".",
"_ssl",
"=",
"None",
"self",
".",
"_rbio",
"=",
"None",
"self",
".",
"_wbio",
"=",
"None",
"try",
":",
"self",
".",
"_ssl",
"=",
"libssl",
".",
"SSL_new",
"(",
"self",
".",
"_session",
".",
... | 40.915254 | 0.000708 |
def define_residues_for_plotting_traj(self, analysis_cutoff):
"""
Since plotting all residues that have made contact with the ligand over a lenghty
simulation is not always feasible or desirable. Therefore, only the residues that
have been in contact with ligand for a long amount of time... | [
"def",
"define_residues_for_plotting_traj",
"(",
"self",
",",
"analysis_cutoff",
")",
":",
"self",
".",
"residue_counts_fraction",
"=",
"{",
"}",
"#Calculate the fraction of time a residue spends in each simulation",
"for",
"traj",
"in",
"self",
".",
"residue_counts",
":",
... | 65.424242 | 0.012323 |
def get_routing_attributes(obj, modify_doc=False, keys=None):
"""
Loops through the provided object (using the dir() function) and
finds any callables which match the name signature (e.g.
get_foo()) AND has a docstring beginning with a path-like char
string.
This does process things in alphabeti... | [
"def",
"get_routing_attributes",
"(",
"obj",
",",
"modify_doc",
"=",
"False",
",",
"keys",
"=",
"None",
")",
":",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"dir",
"(",
"obj",
")",
"for",
"val",
",",
"method_str",
"in",
"_find_routeable_attributes",
"... | 34.566667 | 0.000938 |
def put(self, file_obj, full_path, overwrite = False):
"""Upload a file.
>>> nd.put('./flower.png','/Picture/flower.png')
>>> nd.put(open('./flower.png','r'),'/Picture/flower.png')
:param file_obj: A file-like object to check whether possible to upload. You can pass a string as... | [
"def",
"put",
"(",
"self",
",",
"file_obj",
",",
"full_path",
",",
"overwrite",
"=",
"False",
")",
":",
"try",
":",
"file_obj",
"=",
"open",
"(",
"file_obj",
",",
"'r'",
")",
"except",
":",
"file_obj",
"=",
"file_obj",
"# do nothing",
"content",
"=",
"... | 36.25 | 0.008394 |
def page_load_time(self):
"""
The average total load time for all runs (not weighted).
"""
load_times = self.get_load_times('page')
return round(mean(load_times), self.decimal_precision) | [
"def",
"page_load_time",
"(",
"self",
")",
":",
"load_times",
"=",
"self",
".",
"get_load_times",
"(",
"'page'",
")",
"return",
"round",
"(",
"mean",
"(",
"load_times",
")",
",",
"self",
".",
"decimal_precision",
")"
] | 36.833333 | 0.00885 |
def save(self, path, name, save_meta=True):
'''Saves model as a sequence of files in the format:
{path}/{name}_{'dec', 'disc', 'dec_opt',
'disc_opt', 'meta'}.h5
Parameters
----------
path : str
The directory of the file you wish to save the model to.
... | [
"def",
"save",
"(",
"self",
",",
"path",
",",
"name",
",",
"save_meta",
"=",
"True",
")",
":",
"_save_model",
"(",
"self",
".",
"dec",
",",
"str",
"(",
"path",
")",
",",
"\"%s_dec\"",
"%",
"str",
"(",
"name",
")",
")",
"_save_model",
"(",
"self",
... | 44.227273 | 0.002012 |
def random(self, n: Optional[int] = None) -> Union[List[float], float]:
""" Similar to :py:func:`randint` """
return self._generate_randoms(self._request_randoms, max_n=self.config.MAX_NUMBER_OF_FLOATS,
n=n) | [
"def",
"random",
"(",
"self",
",",
"n",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"Union",
"[",
"List",
"[",
"float",
"]",
",",
"float",
"]",
":",
"return",
"self",
".",
"_generate_randoms",
"(",
"self",
".",
"_request_randoms",
",",
... | 64.5 | 0.011494 |
def type(self):
"""
Retrieve the Type (if any) of the entity pointed at by the cursor.
"""
if not hasattr(self, '_type'):
self._type = conf.lib.clang_getCursorType(self)
return self._type | [
"def",
"type",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_type'",
")",
":",
"self",
".",
"_type",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorType",
"(",
"self",
")",
"return",
"self",
".",
"_type"
] | 29.125 | 0.008333 |
def log_file_handler(self, logpath, **kwargs): # noqa: E501
"""log_file_handler # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.log_file_handler(logpath, async_req=True)
>>>... | [
"def",
"log_file_handler",
"(",
"self",
",",
"logpath",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"log_fi... | 42.35 | 0.002309 |
def _insert_tree(cursor, tree, parent_id=None, index=0, is_collated=False):
"""Inserts a binder tree into the archive."""
if isinstance(tree, dict):
if tree['id'] == 'subcol':
document_id = None
title = tree['title']
else:
cursor.execute("""\
SELEC... | [
"def",
"_insert_tree",
"(",
"cursor",
",",
"tree",
",",
"parent_id",
"=",
"None",
",",
"index",
"=",
"0",
",",
"is_collated",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"tree",
",",
"dict",
")",
":",
"if",
"tree",
"[",
"'id'",
"]",
"==",
"'su... | 44.472222 | 0.000611 |
def print_peak_memory(func,stream = None):
"""
Print peak memory usage (in MB) of a function call
:param func: Function to be called
:param stream: Stream to write peak memory usage (defaults to stdout)
https://stackoverflow.com/questions/9850995/tracking-maximum-memory-usage-by-a-python... | [
"def",
"print_peak_memory",
"(",
"func",
",",
"stream",
"=",
"None",
")",
":",
"import",
"time",
"import",
"psutil",
"import",
"os",
"memory_denominator",
"=",
"1024",
"**",
"2",
"memory_usage_refresh",
"=",
"0.05",
"def",
"wrapper",
"(",
"*",
"args",
",",
... | 36.621622 | 0.010065 |
def _get_imsize(self, im_name):
"""
get image size info
Returns:
----------
tuple of (height, width)
"""
img = cv2.imread(im_name)
return (img.shape[0], img.shape[1]) | [
"def",
"_get_imsize",
"(",
"self",
",",
"im_name",
")",
":",
"img",
"=",
"cv2",
".",
"imread",
"(",
"im_name",
")",
"return",
"(",
"img",
".",
"shape",
"[",
"0",
"]",
",",
"img",
".",
"shape",
"[",
"1",
"]",
")"
] | 24.666667 | 0.008696 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.