text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def hue(stream, **kwargs):
"""Modify the hue and/or the saturation of the input.
Args:
h: Specify the hue angle as a number of degrees. It accepts an expression, and defaults to "0".
s: Specify the saturation in the [-10,10] range. It accepts an expression and defaults to "1".
H: Specif... | [
"def",
"hue",
"(",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FilterNode",
"(",
"stream",
",",
"hue",
".",
"__name__",
",",
"kwargs",
"=",
"kwargs",
")",
".",
"stream",
"(",
")"
] | 54.666667 | 0.008996 |
def _populate_trie(self, values: List[str]) -> CharTrie:
"""Takes a list and inserts its elements into a new trie and returns it"""
if self._default_tokenizer:
return reduce(self._populate_trie_reducer, iter(values), CharTrie())
return reduce(self._populate_trie_reducer_regex, iter(v... | [
"def",
"_populate_trie",
"(",
"self",
",",
"values",
":",
"List",
"[",
"str",
"]",
")",
"->",
"CharTrie",
":",
"if",
"self",
".",
"_default_tokenizer",
":",
"return",
"reduce",
"(",
"self",
".",
"_populate_trie_reducer",
",",
"iter",
"(",
"values",
")",
... | 67 | 0.014749 |
def connect(self, username=None, passcode=None, wait=False, headers=None, **keyword_headers):
"""
:param str username:
:param str passcode:
:param bool wait:
:param dict headers:
:param keyword_headers:
"""
self.transport.start() | [
"def",
"connect",
"(",
"self",
",",
"username",
"=",
"None",
",",
"passcode",
"=",
"None",
",",
"wait",
"=",
"False",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"keyword_headers",
")",
":",
"self",
".",
"transport",
".",
"start",
"(",
")"
] | 31.666667 | 0.010239 |
def randomtable(numflds=5, numrows=100, wait=0, seed=None):
"""
Construct a table with random numerical data. Use `numflds` and `numrows` to
specify the number of fields and rows respectively. Set `wait` to a float
greater than zero to simulate a delay on each row generation (number of
seconds per r... | [
"def",
"randomtable",
"(",
"numflds",
"=",
"5",
",",
"numrows",
"=",
"100",
",",
"wait",
"=",
"0",
",",
"seed",
"=",
"None",
")",
":",
"return",
"RandomTable",
"(",
"numflds",
",",
"numrows",
",",
"wait",
"=",
"wait",
",",
"seed",
"=",
"seed",
")"
... | 53.096774 | 0.001193 |
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 with the same API as Django's existing
implementation, using cryptography.
:type password: any
:type salt: any
:type iterations: int
:type dklen: int
:type digest: cryptography.hazmat.primitives.hashes.H... | [
"def",
"pbkdf2",
"(",
"password",
",",
"salt",
",",
"iterations",
",",
"dklen",
"=",
"0",
",",
"digest",
"=",
"None",
")",
":",
"if",
"digest",
"is",
"None",
":",
"digest",
"=",
"settings",
".",
"CRYPTOGRAPHY_DIGEST",
"if",
"not",
"dklen",
":",
"dklen"... | 29.333333 | 0.001376 |
def get_fields(catalog, filter_in=None, filter_out=None, meta_field=None,
only_time_series=False, distribution_identifier=None):
"""Devuelve lista de campos del catálogo o de uno de sus metadatos.
Args:
catalog (dict, str or DataJson): Representación externa/interna de un
cat... | [
"def",
"get_fields",
"(",
"catalog",
",",
"filter_in",
"=",
"None",
",",
"filter_out",
"=",
"None",
",",
"meta_field",
"=",
"None",
",",
"only_time_series",
"=",
"False",
",",
"distribution_identifier",
"=",
"None",
")",
":",
"filter_in",
"=",
"filter_in",
"... | 44.907895 | 0.000287 |
def normalize(self, renorm_val, band=None, wavelengths=None, force=False,
area=None, vegaspec=None):
"""Renormalize the spectrum to the given Quantity and band.
.. warning::
Redshift attribute (``z``) is reset to 0 in the normalized
spectrum even if ``self.z``... | [
"def",
"normalize",
"(",
"self",
",",
"renorm_val",
",",
"band",
"=",
"None",
",",
"wavelengths",
"=",
"None",
",",
"force",
"=",
"False",
",",
"area",
"=",
"None",
",",
"vegaspec",
"=",
"None",
")",
":",
"warndict",
"=",
"{",
"}",
"if",
"band",
"i... | 37.647799 | 0.000488 |
def getIPString():
""" return comma delimited string of all the system IPs"""
if not(NetInfo.systemip):
NetInfo.systemip = ",".join(NetInfo.getSystemIps())
return NetInfo.systemip | [
"def",
"getIPString",
"(",
")",
":",
"if",
"not",
"(",
"NetInfo",
".",
"systemip",
")",
":",
"NetInfo",
".",
"systemip",
"=",
"\",\"",
".",
"join",
"(",
"NetInfo",
".",
"getSystemIps",
"(",
")",
")",
"return",
"NetInfo",
".",
"systemip"
] | 42.2 | 0.009302 |
def _unpack_batch_response(response):
"""Convert requests.Response -> [(headers, payload)].
Creates a generator of tuples of emulating the responses to
:meth:`requests.Session.request`.
:type response: :class:`requests.Response`
:param response: HTTP response / headers from a request.
"""
... | [
"def",
"_unpack_batch_response",
"(",
"response",
")",
":",
"parser",
"=",
"Parser",
"(",
")",
"message",
"=",
"_generate_faux_mime_message",
"(",
"parser",
",",
"response",
")",
"if",
"not",
"isinstance",
"(",
"message",
".",
"_payload",
",",
"list",
")",
"... | 36.34375 | 0.000838 |
def parse_arguments(
argv: Optional[Sequence[str]] = None) -> argparse.Namespace:
"""
Parse the command line arguments.
Args:
argv:
If not ``None``, use the provided command line arguments for
parsing. Otherwise, extract them automatically.
Returns:
The ... | [
"def",
"parse_arguments",
"(",
"argv",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"argparse",
".",
"Namespace",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Git credential helper using p... | 33.45 | 0.000726 |
def load_dict(self, dct):
"""Load a dictionary of configuration values."""
for k, v in dct.items():
setattr(self, k, v) | [
"def",
"load_dict",
"(",
"self",
",",
"dct",
")",
":",
"for",
"k",
",",
"v",
"in",
"dct",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")"
] | 36 | 0.013605 |
def get_inventory(self):
""" Request the api endpoint to retrieve information about the inventory
:return: Main Collection
:rtype: Collection
"""
if self._inventory is not None:
return self._inventory
self._inventory = self.resolver.getMetadata()
ret... | [
"def",
"get_inventory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_inventory",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_inventory",
"self",
".",
"_inventory",
"=",
"self",
".",
"resolver",
".",
"getMetadata",
"(",
")",
"return",
"self",
".",
... | 29.909091 | 0.00885 |
def getEntityType(self, found = None):
'''
Method to recover the value of the entity in case it may vary.
:param found: The expression to be analysed.
:return: The entity type returned will be an s'i3visio.email' for foo@bar.com and an 'i3visio.text' for foo[at]bar[dot]... | [
"def",
"getEntityType",
"(",
"self",
",",
"found",
"=",
"None",
")",
":",
"# character may be '@' or '.'",
"for",
"character",
"in",
"self",
".",
"substitutionValues",
".",
"keys",
"(",
")",
":",
"for",
"value",
"in",
"self",
".",
"substitutionValues",
"[",
... | 51.923077 | 0.010189 |
def escape_javascript_string(
text,
escape_for_html=True,
escape_quote_for_html=False,
escape_CDATA=True,
escape_script_tag_with_quote='"'):
"""
Escape text in order to be used as Javascript string in various
context.
Examples::
>>> text = '''"Are you a Munch... | [
"def",
"escape_javascript_string",
"(",
"text",
",",
"escape_for_html",
"=",
"True",
",",
"escape_quote_for_html",
"=",
"False",
",",
"escape_CDATA",
"=",
"True",
",",
"escape_script_tag_with_quote",
"=",
"'\"'",
")",
":",
"if",
"escape_quote_for_html",
":",
"text",... | 42.808989 | 0.001539 |
def set_in_selected(self, key, value):
"""Set the (key, value) for the selected server in the list."""
# Static list then dynamic one
if self.screen.active_server >= len(self.static_server.get_servers_list()):
self.autodiscover_server.set_server(
self.screen.active_se... | [
"def",
"set_in_selected",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# Static list then dynamic one",
"if",
"self",
".",
"screen",
".",
"active_server",
">=",
"len",
"(",
"self",
".",
"static_server",
".",
"get_servers_list",
"(",
")",
")",
":",
"self... | 53.888889 | 0.010142 |
def stats_to_list(stats_dict, localize=pytz):
"""
Parse the output of ``SESConnection.get_send_statistics()`` in to an
ordered list of 15-minute summaries.
"""
result = stats_dict['GetSendStatisticsResponse']['GetSendStatisticsResult']
# Make a copy, so we don't change the original stats_dict.
... | [
"def",
"stats_to_list",
"(",
"stats_dict",
",",
"localize",
"=",
"pytz",
")",
":",
"result",
"=",
"stats_dict",
"[",
"'GetSendStatisticsResponse'",
"]",
"[",
"'GetSendStatisticsResult'",
"]",
"# Make a copy, so we don't change the original stats_dict.",
"result",
"=",
"co... | 35.708333 | 0.001136 |
def get_cash_asset_class(self) -> AssetClass:
""" Find the cash asset class by name. """
for ac in self.asset_classes:
if ac.name.lower() == "cash":
return ac
return None | [
"def",
"get_cash_asset_class",
"(",
"self",
")",
"->",
"AssetClass",
":",
"for",
"ac",
"in",
"self",
".",
"asset_classes",
":",
"if",
"ac",
".",
"name",
".",
"lower",
"(",
")",
"==",
"\"cash\"",
":",
"return",
"ac",
"return",
"None"
] | 36.166667 | 0.009009 |
def htmlNodeDumpFormatOutput(self, doc, cur, encoding, format):
"""Dump an HTML node, recursive behaviour,children are printed
too. """
if doc is None: doc__o = None
else: doc__o = doc._o
if cur is None: cur__o = None
else: cur__o = cur._o
libxml2mod.htmlNodeDu... | [
"def",
"htmlNodeDumpFormatOutput",
"(",
"self",
",",
"doc",
",",
"cur",
",",
"encoding",
",",
"format",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"if",
"cur",
"is",
"None",
":",
"... | 46.25 | 0.018568 |
def edges_to_path(edges,
vertices,
**kwargs):
"""
Given an edge list of indices and associated vertices
representing lines, generate kwargs for a Path object.
Parameters
-----------
edges : (n, 2) int
Vertex indices of line segments
vertices : (m, d... | [
"def",
"edges_to_path",
"(",
"edges",
",",
"vertices",
",",
"*",
"*",
"kwargs",
")",
":",
"# sequence of ordered traversals",
"dfs",
"=",
"graph",
".",
"traversals",
"(",
"edges",
",",
"mode",
"=",
"'dfs'",
")",
"# make sure every consecutive index in DFS",
"# tra... | 29.866667 | 0.001081 |
def create_user_profile(sender, instance, created, **kwargs):
"""Create the UserProfile when a new User is saved"""
if created:
profile = UserProfile.objects.get_or_create(user=instance)[0]
profile.hash_pass = create_htpasswd(instance.hash_pass)
profile.save()
else:
# update ... | [
"def",
"create_user_profile",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
":",
"profile",
"=",
"UserProfile",
".",
"objects",
".",
"get_or_create",
"(",
"user",
"=",
"instance",
")",
"[",
"0",
"]",
... | 37.142857 | 0.001876 |
def addStep(self,key):
"""
Add information about a new step to the dict of steps
The value 'ptime' is the output from '_ptime()' containing
both the formatted and unformatted time for the start of the
step.
"""
ptime = _ptime()
print('==== Processing Step ... | [
"def",
"addStep",
"(",
"self",
",",
"key",
")",
":",
"ptime",
"=",
"_ptime",
"(",
")",
"print",
"(",
"'==== Processing Step '",
",",
"key",
",",
"' started at '",
",",
"ptime",
"[",
"0",
"]",
")",
"self",
".",
"steps",
"[",
"key",
"]",
"=",
"{",
"'... | 37.545455 | 0.016548 |
def create_readme_with_long_description():
'''Try to convert content of README.md into rst format using pypandoc,
write it into README and return it.
If pypandoc cannot be imported write content of README.md unchanged into
README and return it.
'''
this_dir = os.path.abspath(os.path.dirname(__f... | [
"def",
"create_readme_with_long_description",
"(",
")",
":",
"this_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"readme_md",
"=",
"os",
".",
"path",
".",
"join",
"(",
"this_dir",
",",
... | 34.125 | 0.00089 |
def user_factory(self):
"""Retrieve the current user (or None) from the database."""
if this.user_id is None:
return None
return self.user_model.objects.get(pk=this.user_id) | [
"def",
"user_factory",
"(",
"self",
")",
":",
"if",
"this",
".",
"user_id",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"user_model",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"this",
".",
"user_id",
")"
] | 41 | 0.009569 |
def length_plots(array, name, path, title=None, n50=None, color="#4CB391", figformat="png"):
"""Create histogram of normal and log transformed read lengths."""
logging.info("Nanoplotter: Creating length plots for {}.".format(name))
maxvalx = np.amax(array)
if n50:
logging.info("Nanoplotter: Usin... | [
"def",
"length_plots",
"(",
"array",
",",
"name",
",",
"path",
",",
"title",
"=",
"None",
",",
"n50",
"=",
"None",
",",
"color",
"=",
"\"#4CB391\"",
",",
"figformat",
"=",
"\"png\"",
")",
":",
"logging",
".",
"info",
"(",
"\"Nanoplotter: Creating length pl... | 42.789474 | 0.002104 |
def maybe_infer_tz(tz, inferred_tz):
"""
If a timezone is inferred from data, check that it is compatible with
the user-provided timezone, if any.
Parameters
----------
tz : tzinfo or None
inferred_tz : tzinfo or None
Returns
-------
tz : tzinfo or None
Raises
------
... | [
"def",
"maybe_infer_tz",
"(",
"tz",
",",
"inferred_tz",
")",
":",
"if",
"tz",
"is",
"None",
":",
"tz",
"=",
"inferred_tz",
"elif",
"inferred_tz",
"is",
"None",
":",
"pass",
"elif",
"not",
"timezones",
".",
"tz_compare",
"(",
"tz",
",",
"inferred_tz",
")"... | 26.185185 | 0.001364 |
def set_xlim(self, xlim):
'''set new X bounds'''
if self.xlim_pipe is not None and self.xlim != xlim:
#print("send0: ", graph_count, xlim)
try:
self.xlim_pipe[0].send(xlim)
except IOError:
return False
self.xlim = xlim
... | [
"def",
"set_xlim",
"(",
"self",
",",
"xlim",
")",
":",
"if",
"self",
".",
"xlim_pipe",
"is",
"not",
"None",
"and",
"self",
".",
"xlim",
"!=",
"xlim",
":",
"#print(\"send0: \", graph_count, xlim)",
"try",
":",
"self",
".",
"xlim_pipe",
"[",
"0",
"]",
".",... | 32.5 | 0.008982 |
def _ensureHtmlAttribute(self):
'''
_ensureHtmlAttribute - INTERNAL METHOD.
Ensure the "style" attribute is present in the html attributes when
is has a value, and absent when it does not.
This requires speci... | [
"def",
"_ensureHtmlAttribute",
"(",
"self",
")",
":",
"tag",
"=",
"self",
".",
"tag",
"if",
"tag",
":",
"styleDict",
"=",
"self",
".",
"_styleDict",
"tagAttributes",
"=",
"tag",
".",
"_attributes",
"# If this is called before we have _attributes setup",
"if",
"not... | 40.5 | 0.009045 |
def get_athlete_stats(self, athlete_id=None):
"""
Returns Statistics for the athlete.
athlete_id must be the id of the authenticated athlete or left blank.
If it is left blank two requests will be made - first to get the
authenticated athlete's id and second to get the Stats.
... | [
"def",
"get_athlete_stats",
"(",
"self",
",",
"athlete_id",
"=",
"None",
")",
":",
"if",
"athlete_id",
"is",
"None",
":",
"athlete_id",
"=",
"self",
".",
"get_athlete",
"(",
")",
".",
"id",
"raw",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/athle... | 39.95 | 0.002445 |
def prepare_params(modeline, fileconfig, options):
"""Prepare and merge a params from modelines and configs.
:return dict:
"""
params = dict(skip=False, ignore=[], select=[], linters=[])
if options:
params['ignore'] = list(options.ignore)
params['select'] = list(options.select)
... | [
"def",
"prepare_params",
"(",
"modeline",
",",
"fileconfig",
",",
"options",
")",
":",
"params",
"=",
"dict",
"(",
"skip",
"=",
"False",
",",
"ignore",
"=",
"[",
"]",
",",
"select",
"=",
"[",
"]",
",",
"linters",
"=",
"[",
"]",
")",
"if",
"options"... | 33.590909 | 0.001316 |
def c32ToB58(c32string, version=-1):
"""
>>> c32ToB58('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7')
'1FzTxL9Mxnm2fdmnQEArfhzJHevwbvcH6d'
>>> c32ToB58('SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G')
'3GgUssdoWh5QkoUDXKqT6LMESBDf8aqp2y'
>>> c32ToB58('ST2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQYAC0RQ')
'mv... | [
"def",
"c32ToB58",
"(",
"c32string",
",",
"version",
"=",
"-",
"1",
")",
":",
"addr_version",
",",
"addr_hash160",
"=",
"c32addressDecode",
"(",
"c32string",
")",
"bitcoin_version",
"=",
"None",
"if",
"version",
"<",
"0",
":",
"bitcoin_version",
"=",
"addr_v... | 41.225806 | 0.001529 |
def _ixor(self, other):
"""Set self to the symmetric difference between the sets.
if isinstance(other, _basebag):
This runs in O(other.num_unique_elements())
else:
This runs in O(len(other))
"""
if isinstance(other, _basebag):
for elem, other_count in other.counts():
count = abs(self.count(elem)... | [
"def",
"_ixor",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"_basebag",
")",
":",
"for",
"elem",
",",
"other_count",
"in",
"other",
".",
"counts",
"(",
")",
":",
"count",
"=",
"abs",
"(",
"self",
".",
"count",
"(",
... | 31.913043 | 0.030423 |
def data_received(self, data):
"""Data received over websocket.
First received data will allways be handshake accepting connection.
We need to check how big the header is so we can send event data
as a proper json object.
"""
if self.state == STATE_STARTING:
... | [
"def",
"data_received",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"state",
"==",
"STATE_STARTING",
":",
"self",
".",
"state",
"=",
"STATE_RUNNING",
"_LOGGER",
".",
"debug",
"(",
"'Websocket handshake: %s'",
",",
"data",
".",
"decode",
"(",
")"... | 37.894737 | 0.009485 |
def email_recipient(self, subject, content, **kwargs):
'''
This method allows for direct emailing of an object's recipient(s)
(default or manually specified), with both object-specific context
provided using the get_email_context() method. This is used, for example,
to emai... | [
"def",
"email_recipient",
"(",
"self",
",",
"subject",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"email_kwargs",
"=",
"{",
"}",
"for",
"list_arg",
"in",
"[",
"'to'",
",",
"'cc'",
",",
"'bcc'",
",",
"]",
":",
"email_kwargs",
"[",
"list_arg",
... | 43.592105 | 0.011511 |
def send_feature_report(self, data):
"""Send input/output/feature report ID = report_id, data should be a
c_byte object with included the required report data
"""
assert( self.is_opened() )
#make sure we have c_ubyte array storage
if not ( isinstance(data, ctypes.Ar... | [
"def",
"send_feature_report",
"(",
"self",
",",
"data",
")",
":",
"assert",
"(",
"self",
".",
"is_opened",
"(",
")",
")",
"#make sure we have c_ubyte array storage\r",
"if",
"not",
"(",
"isinstance",
"(",
"data",
",",
"ctypes",
".",
"Array",
")",
"and",
"iss... | 41.411765 | 0.015278 |
def _multiline(self, value, infile, cur_index, maxline):
"""Extract the value, where we are in a multiline situation."""
quot = value[:3]
newvalue = value[3:]
single_line = self._triple_quote[quot][0]
multi_line = self._triple_quote[quot][1]
mat = single_line.match(value)... | [
"def",
"_multiline",
"(",
"self",
",",
"value",
",",
"infile",
",",
"cur_index",
",",
"maxline",
")",
":",
"quot",
"=",
"value",
"[",
":",
"3",
"]",
"newvalue",
"=",
"value",
"[",
"3",
":",
"]",
"single_line",
"=",
"self",
".",
"_triple_quote",
"[",
... | 35.212121 | 0.001675 |
def parse_args_and_create_context(self, args):
"""
Helper method that will parse the args into options and
remaining args as well as create an initial
:py:class:`swiftly.cli.context.CLIContext`.
The new context will be a copy of
:py:attr:`swiftly.cli.cli.CLI.context` wit... | [
"def",
"parse_args_and_create_context",
"(",
"self",
",",
"args",
")",
":",
"original_args",
"=",
"args",
"try",
":",
"options",
",",
"args",
"=",
"self",
".",
"option_parser",
".",
"parse_args",
"(",
"args",
")",
"except",
"UnboundLocalError",
":",
"# Happens... | 44.62 | 0.000877 |
def uninstall(self, unique_id, configs=None):
"""uninstall the service. If the deployer has not started a service with
`unique_id` this will raise a DeploymentError. This considers one config:
'additional_directories': a list of directories to remove in addition to those provided in the constructor plus
... | [
"def",
"uninstall",
"(",
"self",
",",
"unique_id",
",",
"configs",
"=",
"None",
")",
":",
"# the following is necessay to set the configs for this function as the combination of the",
"# default configurations and the parameter with the parameter superceding the defaults but",
"# not mod... | 51.787879 | 0.00919 |
def create_api_ipv6(self):
"""Get an instance of Api IPv6 services facade."""
return ApiIPv6(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_api_ipv6",
"(",
"self",
")",
":",
"return",
"ApiIPv6",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | 26.75 | 0.00905 |
def get_master(
self,
index,
data=None,
raster=None,
record_offset=0,
record_count=None,
copy_master=True,
):
""" returns master channel samples for given group
Parameters
----------
index : int
group index
... | [
"def",
"get_master",
"(",
"self",
",",
"index",
",",
"data",
"=",
"None",
",",
"raster",
"=",
"None",
",",
"record_offset",
"=",
"0",
",",
"record_count",
"=",
"None",
",",
"copy_master",
"=",
"True",
",",
")",
":",
"original_data",
"=",
"data",
"fragm... | 33.091463 | 0.000894 |
def buildLegend(legend=None, text=None, regex=None, key=lambda v: v):
''' Helper method to build or extend a legend from a text. The given regex
will be used to find legend inside the text.
:param dict legend: Initial legend data
:param str text: Text from which should legend information ex... | [
"def",
"buildLegend",
"(",
"legend",
"=",
"None",
",",
"text",
"=",
"None",
",",
"regex",
"=",
"None",
",",
"key",
"=",
"lambda",
"v",
":",
"v",
")",
":",
"if",
"legend",
"is",
"None",
":",
"legend",
"=",
"{",
"}",
"if",
"text",
"is",
"not",
"N... | 47.631579 | 0.001083 |
def _make_definition(self, svg_dict, instruction_id):
"""Create a symbol out of the supplied :paramref:`svg_dict`.
:param dict svg_dict: dictionary containing the SVG for the
instruction currently processed
:param str instruction_id: id that will be assigned to the symbol
"""
... | [
"def",
"_make_definition",
"(",
"self",
",",
"svg_dict",
",",
"instruction_id",
")",
":",
"instruction_def",
"=",
"svg_dict",
"[",
"\"svg\"",
"]",
"blacklisted_elements",
"=",
"[",
"\"sodipodi:namedview\"",
",",
"\"metadata\"",
"]",
"whitelisted_attributes",
"=",
"[... | 47.166667 | 0.002309 |
def type_and_model_to_query(self, request):
"""
Return JSON for an individual Model instance
If the required parameters are wrong, return 400 Bad Request
If the parameters are correct but there is no data, return empty JSON
"""
try:
content_type_id = request... | [
"def",
"type_and_model_to_query",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"content_type_id",
"=",
"request",
".",
"GET",
"[",
"\"content_type_id\"",
"]",
"object_id",
"=",
"request",
".",
"GET",
"[",
"\"object_id\"",
"]",
"except",
"KeyError",
":",
... | 34 | 0.002384 |
def sparse_mean_var(data):
"""
Calculates the variance for each row of a sparse matrix,
using the relationship Var = E[x^2] - E[x]^2.
Returns:
pair of matrices mean, variance.
"""
data = sparse.csc_matrix(data)
return sparse_means_var_csc(data.data,
data.indices,
... | [
"def",
"sparse_mean_var",
"(",
"data",
")",
":",
"data",
"=",
"sparse",
".",
"csc_matrix",
"(",
"data",
")",
"return",
"sparse_means_var_csc",
"(",
"data",
".",
"data",
",",
"data",
".",
"indices",
",",
"data",
".",
"indptr",
",",
"data",
".",
"shape",
... | 27 | 0.01023 |
def read(cls, fname):
""" read(fname, fmt)
This classmethod is the entry point for reading OBJ files.
Parameters
----------
fname : str
The name of the file to read.
fmt : str
Can be "obj" or "gz" to specify the file format.
"""
#... | [
"def",
"read",
"(",
"cls",
",",
"fname",
")",
":",
"# Open file",
"fmt",
"=",
"op",
".",
"splitext",
"(",
"fname",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"assert",
"fmt",
"in",
"(",
"'.obj'",
",",
"'.gz'",
")",
"opener",
"=",
"open",
"if",
... | 27.935484 | 0.002232 |
def kill_process_children_unix(pid):
"""Find and kill child processes of a process (maximum two level).
:param pid: PID of parent process (process ID)
:return: Nothing
"""
root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
if not os.path.isfile(root_process_path):
ret... | [
"def",
"kill_process_children_unix",
"(",
"pid",
")",
":",
"root_process_path",
"=",
"\"/proc/{pid}/task/{pid}/children\"",
".",
"format",
"(",
"pid",
"=",
"pid",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"root_process_path",
")",
":",
"return",
... | 35.633333 | 0.000911 |
def make_file_list(upload_path):
""" This function returns list of files in the given dir """
newlist = []
for el in sorted(os.listdir(upload_path)):
if ' ' in el:
raise Exception('Error: Spaces are not allowed in file names!\n')
newlist.append(os.path.normpath(upload_path+'/'+el))
debu... | [
"def",
"make_file_list",
"(",
"upload_path",
")",
":",
"newlist",
"=",
"[",
"]",
"for",
"el",
"in",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"upload_path",
")",
")",
":",
"if",
"' '",
"in",
"el",
":",
"raise",
"Exception",
"(",
"'Error: Spaces are not a... | 40.333333 | 0.026954 |
def fit_transform_poof(self, X, y=None, outpath=None, **kwargs):
"""
Fit the model and transforms and then call poof.
"""
self.fit_transform(X, y, **kwargs)
self.poof(outpath, **kwargs) | [
"def",
"fit_transform_poof",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"outpath",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"fit_transform",
"(",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"poof",
"(",
... | 36.666667 | 0.008889 |
def find_request():
'''
Inspect running environment for request object. There should be one,
but don't rely on it.
'''
frame = inspect.currentframe()
request = None
f = frame
while not request and f:
if 'request' in f.f_locals and isinstance(f.f_locals['request'], HttpRequest):
request = f.f_locals['reque... | [
"def",
"find_request",
"(",
")",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"request",
"=",
"None",
"f",
"=",
"frame",
"while",
"not",
"request",
"and",
"f",
":",
"if",
"'request'",
"in",
"f",
".",
"f_locals",
"and",
"isinstance",
"("... | 22 | 0.040872 |
def search_for(self, query, include_draft=False):
"""
Search for a query text.
:param query: keyword to query
:param include_draft: return draft posts/pages or not
:return: an iterable object of posts and pages (if allowed).
"""
query = query.lower()
if n... | [
"def",
"search_for",
"(",
"self",
",",
"query",
",",
"include_draft",
"=",
"False",
")",
":",
"query",
"=",
"query",
".",
"lower",
"(",
")",
"if",
"not",
"query",
":",
"return",
"[",
"]",
"def",
"contains_query_keyword",
"(",
"post_or_page",
")",
":",
... | 38.32 | 0.002037 |
def _add_module(self, aModule):
"""
Private method to add a module object to the snapshot.
@type aModule: L{Module}
@param aModule: Module object.
"""
## if not isinstance(aModule, Module):
## if hasattr(aModule, '__class__'):
## typename = aMod... | [
"def",
"_add_module",
"(",
"self",
",",
"aModule",
")",
":",
"## if not isinstance(aModule, Module):",
"## if hasattr(aModule, '__class__'):",
"## typename = aModule.__class__.__name__",
"## else:",
"## typename = str(type(aModule))"... | 37.9 | 0.015444 |
def converter_loader(app, entry_points=None, modules=None):
"""Run default converter loader.
:param entry_points: List of entry points providing to Blue.
:param modules: Map of coverters.
.. versionadded: 1.0.0
"""
if entry_points:
for entry_point in entry_points:
for ep in... | [
"def",
"converter_loader",
"(",
"app",
",",
"entry_points",
"=",
"None",
",",
"modules",
"=",
"None",
")",
":",
"if",
"entry_points",
":",
"for",
"entry_point",
"in",
"entry_points",
":",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"en... | 33.6 | 0.001447 |
def get_last_thread(self):
"""
Return the last modified thread
"""
cache_key = '_get_last_thread_cache'
if not hasattr(self, cache_key):
item = None
res = self.thread_set.filter(visible=True).order_by('-modified')[0:1]
if len(res)>0:
... | [
"def",
"get_last_thread",
"(",
"self",
")",
":",
"cache_key",
"=",
"'_get_last_thread_cache'",
"if",
"not",
"hasattr",
"(",
"self",
",",
"cache_key",
")",
":",
"item",
"=",
"None",
"res",
"=",
"self",
".",
"thread_set",
".",
"filter",
"(",
"visible",
"=",
... | 34.333333 | 0.01182 |
def kuhn_munkres(G): # maximum profit bipartite matching in O(n^4)
"""Maximum profit perfect matching
for minimum cost perfect matching just inverse the weights
:param G: squared weight matrix of a complete bipartite graph
:complexity: :math:`O(n^4)`
"""
assert len(G) == len(G[0])
n =... | [
"def",
"kuhn_munkres",
"(",
"G",
")",
":",
"# maximum profit bipartite matching in O(n^4)",
"assert",
"len",
"(",
"G",
")",
"==",
"len",
"(",
"G",
"[",
"0",
"]",
")",
"n",
"=",
"len",
"(",
"G",
")",
"mu",
"=",
"[",
"None",
"]",
"*",
"n",
"# Empty mat... | 35.565217 | 0.00119 |
def add(queue_name, payload=None, content_type=None, source=None, task_id=None,
build_id=None, release_id=None, run_id=None):
"""Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string... | [
"def",
"add",
"(",
"queue_name",
",",
"payload",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"source",
"=",
"None",
",",
"task_id",
"=",
"None",
",",
"build_id",
"=",
"None",
",",
"release_id",
"=",
"None",
",",
"run_id",
"=",
"None",
")",
":... | 37.108696 | 0.000571 |
def validate_create_package(
ctx, opts, owner, repo, package_type, skip_errors, **kwargs
):
"""Check new package parameters via the API."""
click.echo(
"Checking %(package_type)s package upload parameters ... "
% {"package_type": click.style(package_type, bold=True)},
nl=False,
)... | [
"def",
"validate_create_package",
"(",
"ctx",
",",
"opts",
",",
"owner",
",",
"repo",
",",
"package_type",
",",
"skip_errors",
",",
"*",
"*",
"kwargs",
")",
":",
"click",
".",
"echo",
"(",
"\"Checking %(package_type)s package upload parameters ... \"",
"%",
"{",
... | 33.047619 | 0.001401 |
def write_output(self):
"""Write the Playbook output variables.
This method should be overridden with the output variables defined in the install.json
configuration file.
"""
self.tcex.log.info('Writing Output')
self.tcex.playbook.create_output('json.pretty', self.pretty... | [
"def",
"write_output",
"(",
"self",
")",
":",
"self",
".",
"tcex",
".",
"log",
".",
"info",
"(",
"'Writing Output'",
")",
"self",
".",
"tcex",
".",
"playbook",
".",
"create_output",
"(",
"'json.pretty'",
",",
"self",
".",
"pretty_json",
")"
] | 39.875 | 0.009202 |
def getTraitCovarStdErrors(self,term_i):
"""
Returns standard errors on trait covariances from term_i (for the covariance estimate \see getTraitCovar)
Args:
term_i: index of the term we are interested in
"""
assert self.init, 'GP not initialised'
a... | [
"def",
"getTraitCovarStdErrors",
"(",
"self",
",",
"term_i",
")",
":",
"assert",
"self",
".",
"init",
",",
"'GP not initialised'",
"assert",
"self",
".",
"fast",
"==",
"False",
",",
"'Not supported for fast implementation'",
"if",
"self",
".",
"P",
"==",
"1",
... | 45.846154 | 0.013969 |
def set_attribute_xsi_type(self, el, **kw):
'''if typed, set the xsi:type attribute
Paramters:
el -- MessageInterface representing the element
'''
if kw.get('typed', self.typed):
namespaceURI,typeName = kw.get('type', _get_xsitype(self))
if namespaceU... | [
"def",
"set_attribute_xsi_type",
"(",
"self",
",",
"el",
",",
"*",
"*",
"kw",
")",
":",
"if",
"kw",
".",
"get",
"(",
"'typed'",
",",
"self",
".",
"typed",
")",
":",
"namespaceURI",
",",
"typeName",
"=",
"kw",
".",
"get",
"(",
"'type'",
",",
"_get_x... | 46.8 | 0.010482 |
def valid(self):
""" Check to see if we are still active. """
if self.finished is not None:
return False
with self._db_conn() as conn:
row = conn.get('''
SELECT (last_contact > %%(now)s - INTERVAL %%(ttl)s SECOND) AS valid
FROM %s
... | [
"def",
"valid",
"(",
"self",
")",
":",
"if",
"self",
".",
"finished",
"is",
"not",
"None",
":",
"return",
"False",
"with",
"self",
".",
"_db_conn",
"(",
")",
"as",
"conn",
":",
"row",
"=",
"conn",
".",
"get",
"(",
"'''\n SELECT (last_conta... | 35.578947 | 0.010086 |
def find_cmd(cmd):
"""Find absolute path to executable cmd in a cross platform manner.
This function tries to determine the full path to a command line program
using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
time it will use the version that is first on the users `PATH`. If
... | [
"def",
"find_cmd",
"(",
"cmd",
")",
":",
"if",
"cmd",
"==",
"'python'",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"sys",
".",
"executable",
")",
"try",
":",
"path",
"=",
"_find_cmd",
"(",
"cmd",
")",
".",
"rstrip",
"(",
")",
"except",
... | 38.935484 | 0.001617 |
def of_cte(cls, header: Optional[ContentTransferEncodingHeader]) \
-> 'MessageDecoder':
"""Return a decoder from the CTE header value.
There is built-in support for ``7bit``, ``8bit``, ``quoted-printable``,
and ``base64`` CTE header values. Decoders can be added or overridden
... | [
"def",
"of_cte",
"(",
"cls",
",",
"header",
":",
"Optional",
"[",
"ContentTransferEncodingHeader",
"]",
")",
"->",
"'MessageDecoder'",
":",
"if",
"header",
"is",
"None",
":",
"return",
"_NoopDecoder",
"(",
")",
"hdr_str",
"=",
"str",
"(",
"header",
")",
".... | 34.615385 | 0.002162 |
def create_metadata_response(self, uri, http_method='GET', body=None,
headers=None):
"""Create metadata response
"""
headers = {
'Content-Type': 'application/json'
}
return headers, json.dumps(self.claims), 200 | [
"def",
"create_metadata_response",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
"return",
"headers",
",",
... | 36 | 0.010169 |
def main():
"""
Main function.
:return:
None.
"""
try:
# Get the `src` directory's absolute path
src_path = os.path.dirname(
# `aoiklivereload` directory's absolute path
os.path.dirname(
# `demo` directory's absolute path
... | [
"def",
"main",
"(",
")",
":",
"try",
":",
"# Get the `src` directory's absolute path",
"src_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"# `aoiklivereload` directory's absolute path",
"os",
".",
"path",
".",
"dirname",
"(",
"# `demo` directory's absolute path",
... | 23.538462 | 0.000523 |
def next(self):
"""Next point in iteration
"""
x, y = next(self.scan)
ca, sa = math.cos(self.angle), math.sin(self.angle)
xr = ca * x - sa * y
yr = sa * x + ca * y
return xr, yr | [
"def",
"next",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"next",
"(",
"self",
".",
"scan",
")",
"ca",
",",
"sa",
"=",
"math",
".",
"cos",
"(",
"self",
".",
"angle",
")",
",",
"math",
".",
"sin",
"(",
"self",
".",
"angle",
")",
"xr",
"=",
... | 28.25 | 0.008584 |
def ClientFromConfig(engine, config, database, logger=None, verbose=True):
"""
Return new database client from valid [couchdb] or [couchbase]
config section.
engine <str> defines which engine to use, currently supports "couchdb" and "couchbase"
config <dict> [couchdb] or [couchbase] section from config
dat... | [
"def",
"ClientFromConfig",
"(",
"engine",
",",
"config",
",",
"database",
",",
"logger",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"type",
"(",
"config",
")",
"==",
"list",
":",
"config",
"=",
"dict",
"(",
"config",
")",
"if",
"engine... | 28.045455 | 0.009397 |
def consume(self, length):
"""
>>> OutBuffer().add(b"spam").consume(2).getvalue() == b"am"
True
@type length: int
@returns: self
"""
self.buff = io.BytesIO(self.getvalue()[length:])
return self | [
"def",
"consume",
"(",
"self",
",",
"length",
")",
":",
"self",
".",
"buff",
"=",
"io",
".",
"BytesIO",
"(",
"self",
".",
"getvalue",
"(",
")",
"[",
"length",
":",
"]",
")",
"return",
"self"
] | 20.1 | 0.047619 |
def validate(anchors, duplicate_tags, opts):
"""
Client facing validate function. Runs _validate() and returns True if
anchors and duplicate_tags pass all validations. Handles exceptions
automatically if _validate() throws any and exits the program.
:param anchors: Dictionary mapping string file pa... | [
"def",
"validate",
"(",
"anchors",
",",
"duplicate_tags",
",",
"opts",
")",
":",
"try",
":",
"return",
"_validate",
"(",
"anchors",
",",
"duplicate_tags",
",",
"opts",
")",
"except",
"ValidationException",
"as",
"e",
":",
"if",
"str",
"(",
"e",
")",
"=="... | 45.074074 | 0.001609 |
def read_chunk(stream):
"""Ignore whitespace outside of strings. If we hit a string, read it in
its entirety.
"""
chunk = stream.read(1)
while chunk in SKIP:
chunk = stream.read(1)
if chunk == "\"":
chunk += stream.read(1)
while not chunk.endswith("\""):
if ch... | [
"def",
"read_chunk",
"(",
"stream",
")",
":",
"chunk",
"=",
"stream",
".",
"read",
"(",
"1",
")",
"while",
"chunk",
"in",
"SKIP",
":",
"chunk",
"=",
"stream",
".",
"read",
"(",
"1",
")",
"if",
"chunk",
"==",
"\"\\\"\"",
":",
"chunk",
"+=",
"stream"... | 29.266667 | 0.002208 |
def logistic_map(x, steps, r=4):
r"""
Generates a time series of the logistic map.
Characteristics and Background:
The logistic map is among the simplest examples for a time series that can
exhibit chaotic behavior depending on the parameter r. For r between 2 and
3, the series quickly becomes stati... | [
"def",
"logistic_map",
"(",
"x",
",",
"steps",
",",
"r",
"=",
"4",
")",
":",
"for",
"_",
"in",
"range",
"(",
"steps",
")",
":",
"x",
"=",
"r",
"*",
"x",
"*",
"(",
"1",
"-",
"x",
")",
"yield",
"x"
] | 30.633333 | 0.00246 |
def get(self, url):
''' Requests data from database '''
req = r.get(url,
headers = self.headers,
auth = self.auth)
return self.process_request(req) | [
"def",
"get",
"(",
"self",
",",
"url",
")",
":",
"req",
"=",
"r",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"return",
"self",
".",
"process_request",
"(",
"req",
")"
] | 34.833333 | 0.03271 |
def get_audiences(self):
"""
Gets the audiences
:returns: The valid audiences for the SAML Response
:rtype: list
"""
audience_nodes = self.__query_assertion('/saml:Conditions/saml:AudienceRestriction/saml:Audience')
return [OneLogin_Saml2_Utils.element_text(node)... | [
"def",
"get_audiences",
"(",
"self",
")",
":",
"audience_nodes",
"=",
"self",
".",
"__query_assertion",
"(",
"'/saml:Conditions/saml:AudienceRestriction/saml:Audience'",
")",
"return",
"[",
"OneLogin_Saml2_Utils",
".",
"element_text",
"(",
"node",
")",
"for",
"node",
... | 43.888889 | 0.009926 |
def _rehydrate_skeleton_class(skeleton_class, class_dict):
"""Put attributes from `class_dict` back on `skeleton_class`.
See CloudPickler.save_dynamic_class for more info.
"""
registry = None
for attrname, attr in class_dict.items():
if attrname == "_abc_impl":
registry = attr
... | [
"def",
"_rehydrate_skeleton_class",
"(",
"skeleton_class",
",",
"class_dict",
")",
":",
"registry",
"=",
"None",
"for",
"attrname",
",",
"attr",
"in",
"class_dict",
".",
"items",
"(",
")",
":",
"if",
"attrname",
"==",
"\"_abc_impl\"",
":",
"registry",
"=",
"... | 31.5625 | 0.001923 |
def server_poweroff(host=None,
admin_username=None,
admin_password=None,
module=None):
'''
Powers down the managed server.
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
... | [
"def",
"server_poweroff",
"(",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"return",
"__execute_cmd",
"(",
"'serveraction powerdown'",
",",
"host",
"=",
"host",
",",
"admi... | 26.933333 | 0.001195 |
def conf_files(self):
"""
List of configuration files for this module
"""
for attr in dir(self):
field = getattr(self, attr)
if isinstance(field, ConfFile):
yield field | [
"def",
"conf_files",
"(",
"self",
")",
":",
"for",
"attr",
"in",
"dir",
"(",
"self",
")",
":",
"field",
"=",
"getattr",
"(",
"self",
",",
"attr",
")",
"if",
"isinstance",
"(",
"field",
",",
"ConfFile",
")",
":",
"yield",
"field"
] | 29.125 | 0.008333 |
def Initialize(self):
"""Open the delegate object."""
if "r" in self.mode:
delegate = self.Get(self.Schema.DELEGATE)
if delegate:
self.delegate = aff4.FACTORY.Open(
delegate, mode=self.mode, token=self.token, age=self.age_policy) | [
"def",
"Initialize",
"(",
"self",
")",
":",
"if",
"\"r\"",
"in",
"self",
".",
"mode",
":",
"delegate",
"=",
"self",
".",
"Get",
"(",
"self",
".",
"Schema",
".",
"DELEGATE",
")",
"if",
"delegate",
":",
"self",
".",
"delegate",
"=",
"aff4",
".",
"FAC... | 37.571429 | 0.011152 |
def do_reload(bot, target, cmdargs, server_send=None):
"""The reloading magic.
- First, reload handler.py.
- Then make copies of all the handler data we want to keep.
- Create a new handler and restore all the data.
"""
def send(msg):
if server_send is not None:
server_sen... | [
"def",
"do_reload",
"(",
"bot",
",",
"target",
",",
"cmdargs",
",",
"server_send",
"=",
"None",
")",
":",
"def",
"send",
"(",
"msg",
")",
":",
"if",
"server_send",
"is",
"not",
"None",
":",
"server_send",
"(",
"\"%s\\n\"",
"%",
"msg",
")",
"else",
":... | 33.446809 | 0.002472 |
def ping(self, timestamp=None):
"""
ping [timestamp]
Ping the Varnish cache process, keeping the connection alive.
"""
cmd = 'ping'
if timestamp: cmd += ' %s' % timestamp
return tuple(map(float, self.fetch(cmd)[1].split()[1:])) | [
"def",
"ping",
"(",
"self",
",",
"timestamp",
"=",
"None",
")",
":",
"cmd",
"=",
"'ping'",
"if",
"timestamp",
":",
"cmd",
"+=",
"' %s'",
"%",
"timestamp",
"return",
"tuple",
"(",
"map",
"(",
"float",
",",
"self",
".",
"fetch",
"(",
"cmd",
")",
"[",... | 35 | 0.010453 |
def compose(segments, out='out.mp3', padding=0, crossfade=0, layer=False):
'''Stiches together a new audiotrack'''
files = {}
working_segments = []
audio = AudioSegment.empty()
if layer:
total_time = max([s['end'] - s['start'] for s in segments]) * 1000
audio = AudioSegment.silen... | [
"def",
"compose",
"(",
"segments",
",",
"out",
"=",
"'out.mp3'",
",",
"padding",
"=",
"0",
",",
"crossfade",
"=",
"0",
",",
"layer",
"=",
"False",
")",
":",
"files",
"=",
"{",
"}",
"working_segments",
"=",
"[",
"]",
"audio",
"=",
"AudioSegment",
".",... | 29.521739 | 0.001426 |
def template(self, data=None, settings=None):
"""
Python micro-templating, similar to John Resig's implementation.
Underscore templating handles arbitrary delimiters, preserves
whitespace, and correctly escapes quotes within interpolated code.
"""
if settings is None:
... | [
"def",
"template",
"(",
"self",
",",
"data",
"=",
"None",
",",
"settings",
"=",
"None",
")",
":",
"if",
"settings",
"is",
"None",
":",
"settings",
"=",
"{",
"}",
"ts",
"=",
"_",
".",
"templateSettings",
"_",
".",
"defaults",
"(",
"ts",
",",
"self",... | 37.25 | 0.001127 |
def render(self, context):
'''Evaluates the code in the page and returns the result'''
modules = {
}
context['false'] = False
context['true'] = True
new_ctx = eval('dict(%s)'%self.code,modules,context)
context.update(new_ctx)
return '' | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"modules",
"=",
"{",
"}",
"context",
"[",
"'false'",
"]",
"=",
"False",
"context",
"[",
"'true'",
"]",
"=",
"True",
"new_ctx",
"=",
"eval",
"(",
"'dict(%s)'",
"%",
"self",
".",
"code",
",",
"m... | 28.777778 | 0.014981 |
def atlas_peer_ping( peer_hostport, timeout=None, peer_table=None ):
"""
Ping a host
Return True if alive
Return False if not
"""
if timeout is None:
timeout = atlas_ping_timeout()
assert not atlas_peer_table_is_locked_by_me()
host, port = url_to_host_port( peer_hostport )... | [
"def",
"atlas_peer_ping",
"(",
"peer_hostport",
",",
"timeout",
"=",
"None",
",",
"peer_table",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"atlas_ping_timeout",
"(",
")",
"assert",
"not",
"atlas_peer_table_is_locked_by_me",
"(",
... | 25 | 0.015609 |
def get_archive(self, archive_name, default_version=None):
'''
Retrieve a data archive
Parameters
----------
archive_name: str
Name of the archive to retrieve
default_version: version
str or :py:class:`~distutils.StrictVersion` giving the defaul... | [
"def",
"get_archive",
"(",
"self",
",",
"archive_name",
",",
"default_version",
"=",
"None",
")",
":",
"auth",
",",
"archive_name",
"=",
"self",
".",
"_normalize_archive_name",
"(",
"archive_name",
")",
"res",
"=",
"self",
".",
"manager",
".",
"get_archive",
... | 28.477273 | 0.001543 |
def tuned(name, **kwargs):
'''
Manage options of block device
name
The name of the block device
opts:
- read-ahead
Read-ahead buffer size
- filesystem-read-ahead
Filesystem Read-ahead buffer size
- read-only
Set Read-Only
- read-write
... | [
"def",
"tuned",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
"}",
"kwarg_map",
"=",
"{",
"'read-ahead'",
":",
"... | 31.507463 | 0.000919 |
def segment_midpoints(self, segments=None):
"""
Identify the midpoints of every line segment in the triangulation.
If an array of segments of shape (no_of_segments,2) is given,
then the midpoints of only those segments is returned. Note,
segments in the array must not be duplicat... | [
"def",
"segment_midpoints",
"(",
"self",
",",
"segments",
"=",
"None",
")",
":",
"if",
"type",
"(",
"segments",
")",
"==",
"type",
"(",
"None",
")",
":",
"segments",
"=",
"self",
".",
"identify_segments",
"(",
")",
"points",
"=",
"self",
".",
"points",... | 40.052632 | 0.011553 |
def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self... | [
"def",
"key_deploy",
"(",
"self",
",",
"host",
",",
"ret",
")",
":",
"if",
"not",
"isinstance",
"(",
"ret",
"[",
"host",
"]",
",",
"dict",
")",
"or",
"self",
".",
"opts",
".",
"get",
"(",
"'ssh_key_deploy'",
")",
":",
"target",
"=",
"self",
".",
... | 45.909091 | 0.00194 |
def spk14b(handle, segid, body, center, framename, first, last, chbdeg):
"""
Begin a type 14 SPK segment in the SPK file associated with
handle. See also :func:`spk14a` and :func:`spk14e`.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spk14b_c.html
:param handle: The handle of an SPK fil... | [
"def",
"spk14b",
"(",
"handle",
",",
"segid",
",",
"body",
",",
"center",
",",
"framename",
",",
"first",
",",
"last",
",",
"chbdeg",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"segid",
"=",
"stypes",
".",
"stringToCharP",
"... | 38.558824 | 0.000744 |
def filetree(collector, *paths):
'''
Add all files in the tree. If the "path" is a file,
only that file will be added.
:param path: File or directory
:return:
'''
_paths = []
# Unglob
for path in paths:
_paths += glob.glob(path)
for path in set(_paths):
if not pa... | [
"def",
"filetree",
"(",
"collector",
",",
"*",
"paths",
")",
":",
"_paths",
"=",
"[",
"]",
"# Unglob",
"for",
"path",
"in",
"paths",
":",
"_paths",
"+=",
"glob",
".",
"glob",
"(",
"path",
")",
"for",
"path",
"in",
"set",
"(",
"_paths",
")",
":",
... | 36.621622 | 0.002157 |
def plot_zeropoint(pars):
""" Plot 2d histogram.
Pars will be a dictionary containing:
data, figure_id, vmax, title_str, xp,yp, searchrad
"""
from matplotlib import pyplot as plt
xp = pars['xp']
yp = pars['yp']
searchrad = int(pars['searchrad'] + 0.5)
plt.figure(num=pars['figu... | [
"def",
"plot_zeropoint",
"(",
"pars",
")",
":",
"from",
"matplotlib",
"import",
"pyplot",
"as",
"plt",
"xp",
"=",
"pars",
"[",
"'xp'",
"]",
"yp",
"=",
"pars",
"[",
"'yp'",
"]",
"searchrad",
"=",
"int",
"(",
"pars",
"[",
"'searchrad'",
"]",
"+",
"0.5"... | 28.711111 | 0.000749 |
def run_checks(self):
"""
Iterates over the configured ports and runs the checks on each one.
Returns a two-element tuple: the first is the set of ports that
transitioned from down to up, the second is the set of ports that
transitioned from up to down.
Also handles the... | [
"def",
"run_checks",
"(",
"self",
")",
":",
"came_up",
"=",
"set",
"(",
")",
"went_down",
"=",
"set",
"(",
")",
"for",
"port",
"in",
"self",
".",
"ports",
":",
"checks",
"=",
"self",
".",
"checks",
"[",
"port",
"]",
".",
"values",
"(",
")",
"if",... | 34.026316 | 0.001504 |
def accept( self ):
"""
Saves the current settings for the actions in the list and exits the
dialog.
"""
if ( not self.save() ):
return
for i in range(self.uiActionTREE.topLevelItemCount()):
item = self.uiActionTREE.topLevelItem(i)
... | [
"def",
"accept",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"save",
"(",
")",
")",
":",
"return",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"uiActionTREE",
".",
"topLevelItemCount",
"(",
")",
")",
":",
"item",
"=",
"self",
".",
"uiA... | 32.428571 | 0.021413 |
def setUp(self, port, soc, input):
'''
Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output
'''
name = soc.getOperationName()
bop = port.getBinding().operations.get(name)
... | [
"def",
"setUp",
"(",
"self",
",",
"port",
",",
"soc",
",",
"input",
")",
":",
"name",
"=",
"soc",
".",
"getOperationName",
"(",
")",
"bop",
"=",
"port",
".",
"getBinding",
"(",
")",
".",
"operations",
".",
"get",
"(",
"name",
")",
"op",
"=",
"por... | 34.058824 | 0.008403 |
def create_normal_logq(self,z):
"""
Create logq components for mean-field normal family (the entropy estimate)
"""
means, scale = self.get_means_and_scales()
return ss.norm.logpdf(z,loc=means,scale=scale).sum() | [
"def",
"create_normal_logq",
"(",
"self",
",",
"z",
")",
":",
"means",
",",
"scale",
"=",
"self",
".",
"get_means_and_scales",
"(",
")",
"return",
"ss",
".",
"norm",
".",
"logpdf",
"(",
"z",
",",
"loc",
"=",
"means",
",",
"scale",
"=",
"scale",
")",
... | 40.833333 | 0.024 |
def publish_pending(cursor, publication_id):
"""Given a publication id as ``publication_id``,
write the documents to the *Connexions Archive*.
"""
cursor.execute("""\
WITH state_update AS (
UPDATE publications SET state = 'Publishing' WHERE id = %s
)
SELECT publisher, publication_message
FROM publicat... | [
"def",
"publish_pending",
"(",
"cursor",
",",
"publication_id",
")",
":",
"cursor",
".",
"execute",
"(",
"\"\"\"\\\nWITH state_update AS (\n UPDATE publications SET state = 'Publishing' WHERE id = %s\n)\nSELECT publisher, publication_message\nFROM publications\nWHERE id = %s\"\"\"",
",",
... | 36.966667 | 0.000293 |
def split(self):
"""Split the phase.
When a phase is exhausted, it gets split into a pair of phases to be
further solved. The split happens like so:
1) Select the first unsolved package scope.
2) Find some common dependency in the first N variants of the scope.
3) Split ... | [
"def",
"split",
"(",
"self",
")",
":",
"assert",
"(",
"self",
".",
"status",
"==",
"SolverStatus",
".",
"exhausted",
")",
"scopes",
"=",
"[",
"]",
"next_scopes",
"=",
"[",
"]",
"split_i",
"=",
"None",
"for",
"i",
",",
"scope",
"in",
"enumerate",
"(",... | 34.072727 | 0.001556 |
def ed25519_private_key_to_string(key):
"""Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str
"""
return base64.b64encode(key.private_bytes(
encoding=serializ... | [
"def",
"ed25519_private_key_to_string",
"(",
"key",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"key",
".",
"private_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"Raw",
",",
"format",
"=",
"serialization",
".",
"PrivateFormat",
... | 30.666667 | 0.00211 |
def CopyFromDateTimeString(self, time_string):
"""Copies time elements from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be ... | [
"def",
"CopyFromDateTimeString",
"(",
"self",
",",
"time_string",
")",
":",
"date_time_values",
"=",
"self",
".",
"_CopyDateTimeFromString",
"(",
"time_string",
")",
"self",
".",
"_CopyFromDateTimeValues",
"(",
"date_time_values",
")"
] | 38.066667 | 0.001709 |
def has_no_password(gpg_secret_keyid):
"""Returns True iif gpg_secret_key has a password"""
if gnupg is None:
return False
gpg = gnupg.GPG()
s = gpg.sign("", keyid=gpg_secret_keyid, passphrase="")
try:
return s.status == "signature created"
except AttributeError:
# Thi... | [
"def",
"has_no_password",
"(",
"gpg_secret_keyid",
")",
":",
"if",
"gnupg",
"is",
"None",
":",
"return",
"False",
"gpg",
"=",
"gnupg",
".",
"GPG",
"(",
")",
"s",
"=",
"gpg",
".",
"sign",
"(",
"\"\"",
",",
"keyid",
"=",
"gpg_secret_keyid",
",",
"passphr... | 27.4 | 0.002353 |
def set_face_values(self, front_face_value, side_face_value, top_face_value):
"""stub"""
if front_face_value is None or side_face_value is None or top_face_value is None:
raise NullArgument()
self.add_integer_value(value=int(front_face_value), label='frontFaceValue')
self.add... | [
"def",
"set_face_values",
"(",
"self",
",",
"front_face_value",
",",
"side_face_value",
",",
"top_face_value",
")",
":",
"if",
"front_face_value",
"is",
"None",
"or",
"side_face_value",
"is",
"None",
"or",
"top_face_value",
"is",
"None",
":",
"raise",
"NullArgumen... | 65.571429 | 0.010753 |
def write_mnefiff(data, filename):
"""Export data to MNE using FIFF format.
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (include '.mat')
Notes
-----
It cannot store data larger than 2 GB.
The d... | [
"def",
"write_mnefiff",
"(",
"data",
",",
"filename",
")",
":",
"from",
"mne",
"import",
"create_info",
",",
"set_log_level",
"from",
"mne",
".",
"io",
"import",
"RawArray",
"set_log_level",
"(",
"WARNING",
")",
"TRIAL",
"=",
"0",
"info",
"=",
"create_info",... | 28.121212 | 0.001042 |
def _create_hosting_devices_from_config(self):
"""To be called late during plugin initialization so that any hosting
device specified in the config file is properly inserted in the DB.
"""
hd_dict = config.get_specific_config('cisco_hosting_device')
attr_info = ciscohostingdevice... | [
"def",
"_create_hosting_devices_from_config",
"(",
"self",
")",
":",
"hd_dict",
"=",
"config",
".",
"get_specific_config",
"(",
"'cisco_hosting_device'",
")",
"attr_info",
"=",
"ciscohostingdevicemanager",
".",
"RESOURCE_ATTRIBUTE_MAP",
"[",
"ciscohostingdevicemanager",
"."... | 50.444444 | 0.00108 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.