text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def staticfiles_url_fetcher(url):
"""
Returns the file matching url.
This method will handle any URL resources that rendering HTML requires
(eg: images pointed my ``img`` tags, stylesheets, etc).
The default behaviour will fetch any http(s) files normally, and will
also attempt to resolve stat... | [
"def",
"staticfiles_url_fetcher",
"(",
"url",
")",
":",
"if",
"url",
".",
"startswith",
"(",
"'/'",
")",
":",
"base_url",
"=",
"staticfiles_storage",
".",
"base_url",
"filename",
"=",
"url",
".",
"replace",
"(",
"base_url",
",",
"''",
",",
"1",
")",
"pat... | 37.666667 | 0.000616 |
def get_summary_page_link(ifo, utc_time):
"""Return a string that links to the summary page and aLOG for this ifo
Parameters
----------
ifo : string
The detector name
utc_time : sequence
First three elements must be strings giving year, month, day resp.
Returns
-------
... | [
"def",
"get_summary_page_link",
"(",
"ifo",
",",
"utc_time",
")",
":",
"search_form",
"=",
"search_form_string",
"data",
"=",
"{",
"'H1'",
":",
"data_h1_string",
",",
"'L1'",
":",
"data_l1_string",
"}",
"if",
"ifo",
"not",
"in",
"data",
":",
"return",
"ifo",... | 34.961538 | 0.002141 |
def nodes_walker(node, ascendants=False):
"""
Defines a generator used to walk into Nodes hierarchy.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_d ... | [
"def",
"nodes_walker",
"(",
"node",
",",
"ascendants",
"=",
"False",
")",
":",
"attribute",
"=",
"\"children\"",
"if",
"not",
"ascendants",
"else",
"\"parent\"",
"if",
"not",
"hasattr",
"(",
"node",
",",
"attribute",
")",
":",
"return",
"elements",
"=",
"g... | 30.12 | 0.000643 |
def show_list(timeout_in_sec, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
'''get the name list of the topics, and print it
'''
class TopicNameStore(object):
def __init__(self):
self._topic_names = set()
def callback(self, msg, topic):
... | [
"def",
"show_list",
"(",
"timeout_in_sec",
",",
"out",
"=",
"sys",
".",
"stdout",
",",
"host",
"=",
"jps",
".",
"env",
".",
"get_master_host",
"(",
")",
",",
"sub_port",
"=",
"jps",
".",
"DEFAULT_SUB_PORT",
")",
":",
"class",
"TopicNameStore",
"(",
"obje... | 33.375 | 0.002427 |
def synthesize_member(member_name,
default = None,
contract = None,
read_only = False,
getter_name = None,
setter_name = None,
private_member_name = None):
"""
When applied to a cl... | [
"def",
"synthesize_member",
"(",
"member_name",
",",
"default",
"=",
"None",
",",
"contract",
"=",
"None",
",",
"read_only",
"=",
"False",
",",
"getter_name",
"=",
"None",
",",
"setter_name",
"=",
"None",
",",
"private_member_name",
"=",
"None",
")",
":",
... | 56.822222 | 0.020377 |
def committee(request, abbr, committee_id):
'''
Context:
- committee
- abbr
- metadata
- sources
- nav_active
Tempaltes:
- billy/web/public/committee.html
'''
committee = db.committees.find_one({'_id': committee_id})
if committee is None:
... | [
"def",
"committee",
"(",
"request",
",",
"abbr",
",",
"committee_id",
")",
":",
"committee",
"=",
"db",
".",
"committees",
".",
"find_one",
"(",
"{",
"'_id'",
":",
"committee_id",
"}",
")",
"if",
"committee",
"is",
"None",
":",
"raise",
"Http404",
"retur... | 27.809524 | 0.001656 |
def accel_prev(self, *args):
"""Callback to go to the previous tab. Called by the accel key.
"""
if self.get_notebook().get_current_page() == 0:
self.get_notebook().set_current_page(self.get_notebook().get_n_pages() - 1)
else:
self.get_notebook().prev_page()
... | [
"def",
"accel_prev",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"==",
"0",
":",
"self",
".",
"get_notebook",
"(",
")",
".",
"set_current_page",
"(",
"self",
".",
"get_noteboo... | 40.875 | 0.008982 |
def find_pore_hulls(self, pores=None):
r"""
Finds the indices of the Voronoi nodes that define the convex hull
around the given Delaunay nodes.
Parameters
----------
pores : array_like
The pores whose convex hull are sought. The given pores should be
... | [
"def",
"find_pore_hulls",
"(",
"self",
",",
"pores",
"=",
"None",
")",
":",
"if",
"pores",
"is",
"None",
":",
"pores",
"=",
"self",
".",
"pores",
"(",
"'delaunay'",
")",
"temp",
"=",
"[",
"]",
"tvals",
"=",
"self",
"[",
"'throat.interconnect'",
"]",
... | 36.259259 | 0.00199 |
def request_elements(
self, credentials=None, url=None, method='GET', params=None,
headers=None, body='', json_input=None, return_json=False
):
"""
Creates request elements for accessing **protected resource of a
user**. Required arguments are :data:`credentials` and ... | [
"def",
"request_elements",
"(",
"self",
",",
"credentials",
"=",
"None",
",",
"url",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"''",
",",
"json_input",
"=",
"None",
",",
"retu... | 32.138889 | 0.000838 |
def get_command_info(self, peer_jid, command_name):
"""
Obtain information about a command.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command
:type command_name: :class:`str`
:rtype: :cla... | [
"def",
"get_command_info",
"(",
"self",
",",
"peer_jid",
",",
"command_name",
")",
":",
"disco",
"=",
"self",
".",
"dependencies",
"[",
"aioxmpp",
".",
"disco",
".",
"DiscoClient",
"]",
"response",
"=",
"yield",
"from",
"disco",
".",
"query_info",
"(",
"pe... | 39.285714 | 0.001775 |
def _recv_timeout_loop(self):
"""
A loop to check timeout of receiving remote BFD packet.
"""
while self._detect_time:
last_wait = time.time()
self._lock = hub.Event()
self._lock.wait(timeout=self._detect_time)
if self._lock.is_set():
... | [
"def",
"_recv_timeout_loop",
"(",
"self",
")",
":",
"while",
"self",
".",
"_detect_time",
":",
"last_wait",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_lock",
"=",
"hub",
".",
"Event",
"(",
")",
"self",
".",
"_lock",
".",
"wait",
"(",
"timeout... | 42.714286 | 0.001635 |
def add(
self,
uri,
methods,
handler,
host=None,
strict_slashes=False,
version=None,
name=None,
):
"""Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
... | [
"def",
"add",
"(",
"self",
",",
"uri",
",",
"methods",
",",
"handler",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"False",
",",
"version",
"=",
"None",
",",
"name",
"=",
"None",
",",
")",
":",
"if",
"version",
"is",
"not",
"None",
":",
... | 38.048387 | 0.00124 |
def search(self, query, page=None, per_page=1000, mentions=3, data=False):
"""
Retrieve all objects that make a search query.
Will loop through all pages that match unless you provide
the number of pages you'd like to restrict the search to.
Example usage:
>> docum... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"page",
"=",
"None",
",",
"per_page",
"=",
"1000",
",",
"mentions",
"=",
"3",
",",
"data",
"=",
"False",
")",
":",
"# If the user provides a page, search it and stop there",
"if",
"page",
":",
"document_list",
... | 32.829787 | 0.001259 |
def get_gicon(self, icon_id: str) -> "Gio.Icon":
"""Lookup Gio.Icon from udiskie-internal id."""
return Gio.ThemedIcon.new_from_names(self._icon_names[icon_id]) | [
"def",
"get_gicon",
"(",
"self",
",",
"icon_id",
":",
"str",
")",
"->",
"\"Gio.Icon\"",
":",
"return",
"Gio",
".",
"ThemedIcon",
".",
"new_from_names",
"(",
"self",
".",
"_icon_names",
"[",
"icon_id",
"]",
")"
] | 58 | 0.011364 |
def publishTemplate(self, templateMessage):
"""
发送单聊模板消息方法(一个用户向多个用户发送不同消息内容,单条消息最大 128k。每分钟最多发送 6000 条信息,每次发送用户上限为 1000 人。) 方法
@param templateMessage:单聊模版消息。
@return code:返回码,200 为正常。
@return errorMessage:错误信息。
"""
desc = {
"name": "CodeSuccessReslu... | [
"def",
"publishTemplate",
"(",
"self",
",",
"templateMessage",
")",
":",
"desc",
"=",
"{",
"\"name\"",
":",
"\"CodeSuccessReslut\"",
",",
"\"desc\"",
":",
"\" http 成功返回结果\",",
"",
"\"fields\"",
":",
"[",
"{",
"\"name\"",
":",
"\"code\"",
",",
"\"type\"",
":",
... | 30.555556 | 0.010576 |
def create_protobuf_span(span):
"""Converts a py_zipkin Span in a protobuf Span.
:param span: py_zipkin Span to convert.
:type span: py_zipkin.encoding.Span
:return: protobuf's Span
:rtype: zipkin_pb2.Span
"""
# Protobuf's composite types (i.e. Span's local_endpoint) are immutable.
# S... | [
"def",
"create_protobuf_span",
"(",
"span",
")",
":",
"# Protobuf's composite types (i.e. Span's local_endpoint) are immutable.",
"# So we can't create a zipkin_pb2.Span here and then set the appropriate",
"# fields since `pb_span.local_endpoint = zipkin_pb2.Endpoint` fails.",
"# Instead we just c... | 30.634615 | 0.001217 |
def do_version(self, args):
"""
Usage:
version
Prints out the version number
"""
Console.ok("cmd3: {:}".format(str(cmd3.__version__)))
Console.ok("cloudmesh_base: {:}".format(str(cloudmesh_base.__version__)))
python_version, pip_version = get_python()... | [
"def",
"do_version",
"(",
"self",
",",
"args",
")",
":",
"Console",
".",
"ok",
"(",
"\"cmd3: {:}\"",
".",
"format",
"(",
"str",
"(",
"cmd3",
".",
"__version__",
")",
")",
")",
"Console",
".",
"ok",
"(",
"\"cloudmesh_base: {:}\"",
".",
"format",
"(",
"s... | 26.352941 | 0.008621 |
def enqueue(self, stanza, **kwargs):
"""
Put a `stanza` in the internal transmission queue and return a token to
track it.
:param stanza: Stanza to send
:type stanza: :class:`IQ`, :class:`Message` or :class:`Presence`
:param kwargs: see :class:`StanzaToken`
:rais... | [
"def",
"enqueue",
"(",
"self",
",",
"stanza",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"established_event",
".",
"is_set",
"(",
")",
":",
"raise",
"ConnectionError",
"(",
"\"stream is not ready\"",
")",
"return",
"self",
".",
"stream",
... | 35.552632 | 0.001441 |
def postal_code(random=random, *args, **kwargs):
"""
Produce something that vaguely resembles a postal code
>>> mock_random.seed(0)
>>> postal_code(random=mock_random)
'b0b 0c0'
>>> postal_code(random=mock_random, capitalize=True)
'E0E 0F0'
>>> postal_code(random=mock_random, slugify=Tr... | [
"def",
"postal_code",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"random",
".",
"choice",
"(",
"[",
"\"{letter}{number}{letter} {other_number}{other_letter}{other_number}\"",
",",
"\"{number}{other_number}{number}{number... | 32.217391 | 0.001311 |
def set(self, project, date, data, data_ts):
"""
Set the cache data for a specified project for the specified date.
:param project: project name to set data for
:type project: str
:param date: date to set data for
:type date: datetime.datetime
:param data: data t... | [
"def",
"set",
"(",
"self",
",",
"project",
",",
"date",
",",
"data",
",",
"data_ts",
")",
":",
"data",
"[",
"'cache_metadata'",
"]",
"=",
"{",
"'project'",
":",
"project",
",",
"'date'",
":",
"date",
".",
"strftime",
"(",
"'%Y%m%d'",
")",
",",
"'upda... | 36.44 | 0.002139 |
def contains_project_name(name, link):
"""
Checks if the given link `somewhat` contains the project name.
:param name: str, project name
:param link: str, link
:return: bool, True if the link contains the project name
"""
def unclutter(string):
# strip out all python references and r... | [
"def",
"contains_project_name",
"(",
"name",
",",
"link",
")",
":",
"def",
"unclutter",
"(",
"string",
")",
":",
"# strip out all python references and remove all excessive characters",
"string",
"=",
"string",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"\"_\"",
... | 44.785714 | 0.001563 |
def multilabel_accuracy_matchk(predictions,
labels,
k,
weights_fn=common_layers.weights_nonzero):
"""Used to evaluate the VQA accuracy.
Let n be the times that predictions appear in labels, then final score
is min(n/k, 1... | [
"def",
"multilabel_accuracy_matchk",
"(",
"predictions",
",",
"labels",
",",
"k",
",",
"weights_fn",
"=",
"common_layers",
".",
"weights_nonzero",
")",
":",
"predictions",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"argmax",
"(",
"predictions",
",",
"axis",
... | 32.870968 | 0.011439 |
def data_items(self) -> typing.List[DataItem]:
"""Return the list of data items.
:return: The list of :py:class:`nion.swift.Facade.DataItem` objects.
.. versionadded:: 1.0
Scriptable: Yes
"""
return [DataItem(data_item) for data_item in self.__document_model.data_items... | [
"def",
"data_items",
"(",
"self",
")",
"->",
"typing",
".",
"List",
"[",
"DataItem",
"]",
":",
"return",
"[",
"DataItem",
"(",
"data_item",
")",
"for",
"data_item",
"in",
"self",
".",
"__document_model",
".",
"data_items",
"]"
] | 31.2 | 0.009346 |
def parker_weighting(ray_trafo, q=0.25):
"""Create parker weighting for a `RayTransform`.
Parker weighting is a weighting function that ensures that oversampled
fan/cone beam data are weighted such that each line has unit weight. It is
useful in analytic reconstruction methods such as FBP to give a mor... | [
"def",
"parker_weighting",
"(",
"ray_trafo",
",",
"q",
"=",
"0.25",
")",
":",
"# Note: Parameter names taken from WES2002",
"# Extract parameters",
"src_radius",
"=",
"ray_trafo",
".",
"geometry",
".",
"src_radius",
"det_radius",
"=",
"ray_trafo",
".",
"geometry",
"."... | 37.97 | 0.000257 |
def _tls_PRF(secret, label, seed, req_len):
"""
Provides the implementation of TLS PRF function as defined in
section 5 of RFC 4346:
PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
P_SHA-1(S2, label + seed)
Parameters are:
- secret: the secret used by the... | [
"def",
"_tls_PRF",
"(",
"secret",
",",
"label",
",",
"seed",
",",
"req_len",
")",
":",
"tmp_len",
"=",
"(",
"len",
"(",
"secret",
")",
"+",
"1",
")",
"//",
"2",
"S1",
"=",
"secret",
"[",
":",
"tmp_len",
"]",
"S2",
"=",
"secret",
"[",
"-",
"tmp_... | 33.92 | 0.001147 |
def get_callback_name(cb):
"""Get a callback fully-qualified name.
If no name can be produced ``repr(cb)`` is called and returned.
"""
segments = []
try:
segments.append(cb.__qualname__)
except AttributeError:
try:
segments.append(cb.__name__)
if inspect.... | [
"def",
"get_callback_name",
"(",
"cb",
")",
":",
"segments",
"=",
"[",
"]",
"try",
":",
"segments",
".",
"append",
"(",
"cb",
".",
"__qualname__",
")",
"except",
"AttributeError",
":",
"try",
":",
"segments",
".",
"append",
"(",
"cb",
".",
"__name__",
... | 32.774194 | 0.000956 |
def squawk(self) -> Set[str]:
"""Returns all the unique squawk values in the trajectory."""
return set(self.data.squawk.ffill().bfill()) | [
"def",
"squawk",
"(",
"self",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"return",
"set",
"(",
"self",
".",
"data",
".",
"squawk",
".",
"ffill",
"(",
")",
".",
"bfill",
"(",
")",
")"
] | 50 | 0.013158 |
def _parse_master(path=MASTER_CF):
'''
Parse the master.cf file. This file is essentially a whitespace-delimited
columnar file. The columns are: service, type, private (yes), unpriv (yes),
chroot (yes), wakeup (never), maxproc (100), command + args.
This function parses out the columns, leaving emp... | [
"def",
"_parse_master",
"(",
"path",
"=",
"MASTER_CF",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"'r'",
")",
"as",
"fh_",
":",
"full_conf",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
... | 36.075 | 0.000675 |
def build(self):
"""
The decoder computational graph consists of three components:
(1) the input node `decoder_input`
(2) the embedding node `decoder_embed`
(3) the recurrent (RNN) part `decoder_rnn`
(4) the output of th... | [
"def",
"build",
"(",
"self",
")",
":",
"# Grab hyperparameters from self.config:",
"hidden_dim",
"=",
"self",
".",
"config",
"[",
"'encoding-layer-width'",
"]",
"recurrent_unit",
"=",
"self",
".",
"config",
"[",
"'recurrent-unit-type'",
"]",
"bidirectional",
"=",
"F... | 49.333333 | 0.009524 |
def get_port_bindings(binding_key=None):
"""Returns filtered list of port bindings that may be relevant on CVX
This query is a little complex as we need all binding levels for any
binding that has a single managed physnet, but we need to filter bindings
that have no managed physnets. In order to achiev... | [
"def",
"get_port_bindings",
"(",
"binding_key",
"=",
"None",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"binding_level_model",
"=",
"ml2_models",
".",
"PortBindingLevel",
"aliased_blm",
... | 52.272727 | 0.000244 |
def cancellation_fee(self, percentage):
''' Generates an invoice with a cancellation fee, and applies
credit to the invoice.
percentage (Decimal): The percentage of the credit note to turn into
a cancellation fee. Must be 0 <= percentage <= 100.
'''
# Local import to fi... | [
"def",
"cancellation_fee",
"(",
"self",
",",
"percentage",
")",
":",
"# Local import to fix import cycles. Can we do better?",
"from",
".",
"invoice",
"import",
"InvoiceController",
"assert",
"(",
"percentage",
">=",
"0",
"and",
"percentage",
"<=",
"100",
")",
"cancel... | 34.75 | 0.002334 |
def search_bm25f(cls, term, weights=None, with_score=False,
score_alias='score', explicit_ordering=False):
"""Full-text search for selected `term` using BM25 algorithm."""
return cls._search(
term,
weights,
with_score,
score_alias,
... | [
"def",
"search_bm25f",
"(",
"cls",
",",
"term",
",",
"weights",
"=",
"None",
",",
"with_score",
"=",
"False",
",",
"score_alias",
"=",
"'score'",
",",
"explicit_ordering",
"=",
"False",
")",
":",
"return",
"cls",
".",
"_search",
"(",
"term",
",",
"weight... | 36.1 | 0.008108 |
def _update_partition_dci_id(self, tenant_name, dci_id,
vrf_prof=None, part_name=None):
"""Function to update DCI ID of partition. """
self.dcnm_obj.update_project(tenant_name, part_name, dci_id=dci_id,
vrf_prof=vrf_prof) | [
"def",
"_update_partition_dci_id",
"(",
"self",
",",
"tenant_name",
",",
"dci_id",
",",
"vrf_prof",
"=",
"None",
",",
"part_name",
"=",
"None",
")",
":",
"self",
".",
"dcnm_obj",
".",
"update_project",
"(",
"tenant_name",
",",
"part_name",
",",
"dci_id",
"="... | 60.6 | 0.009772 |
def _setup_component(self, storm_conf, context):
"""Add helpful instance variables to component after initial handshake
with Storm. Also configure logging.
"""
self.topology_name = storm_conf.get("topology.name", "")
self.task_id = context.get("taskid", "")
self.componen... | [
"def",
"_setup_component",
"(",
"self",
",",
"storm_conf",
",",
"context",
")",
":",
"self",
".",
"topology_name",
"=",
"storm_conf",
".",
"get",
"(",
"\"topology.name\"",
",",
"\"\"",
")",
"self",
".",
"task_id",
"=",
"context",
".",
"get",
"(",
"\"taskid... | 44.183099 | 0.001559 |
def append_text_column(self, text: str, index: int):
""" Add value to the output row, width based on index """
width = self.columns[index]["width"]
return f"{text:<{width}}" | [
"def",
"append_text_column",
"(",
"self",
",",
"text",
":",
"str",
",",
"index",
":",
"int",
")",
":",
"width",
"=",
"self",
".",
"columns",
"[",
"index",
"]",
"[",
"\"width\"",
"]",
"return",
"f\"{text:<{width}}\""
] | 48.5 | 0.010152 |
def djeffify_string(string_to_djeff):
"""
Djeffifies string_to_djeff
"""
string_to_djeff = re.sub(r'^(?=[jg])', 'd', string_to_djeff, flags=re.IGNORECASE) # first
string_to_djeff = re.sub(r'[ ](?=[jg])', ' d', string_to_djeff, flags=re.IGNORECASE) # spaces
string_to_djeff = re.sub(r'[\n](?=[jg... | [
"def",
"djeffify_string",
"(",
"string_to_djeff",
")",
":",
"string_to_djeff",
"=",
"re",
".",
"sub",
"(",
"r'^(?=[jg])'",
",",
"'d'",
",",
"string_to_djeff",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"# first",
"string_to_djeff",
"=",
"re",
".",
"sub... | 49.375 | 0.00995 |
def get_column_flat(self, field, components=None, computed_type='for_observations'):
"""
TODO: add documentation
return a single merged value (hstacked) from all meshes
:parameter str field: name of the mesh columnname
:parameter components:
"""
return self.pack... | [
"def",
"get_column_flat",
"(",
"self",
",",
"field",
",",
"components",
"=",
"None",
",",
"computed_type",
"=",
"'for_observations'",
")",
":",
"return",
"self",
".",
"pack_column_flat",
"(",
"self",
".",
"get_column",
"(",
"field",
",",
"components",
",",
"... | 40.416667 | 0.010081 |
def read_vcf_into_dataframe(
path,
include_info=False,
sample_names=None,
chunk_size=None):
"""
Load the data of a VCF into a pandas dataframe. All headers are ignored.
Parameters
----------
path : str
Path to local file. HTTP and other protocols are not impl... | [
"def",
"read_vcf_into_dataframe",
"(",
"path",
",",
"include_info",
"=",
"False",
",",
"sample_names",
"=",
"None",
",",
"chunk_size",
"=",
"None",
")",
":",
"vcf_field_types",
"=",
"OrderedDict",
"(",
")",
"vcf_field_types",
"[",
"'CHROM'",
"]",
"=",
"str",
... | 31.626866 | 0.000458 |
def create_detailed_results(result):
"""
Use the result from the API call to create an organized single string output for printing to the console.
:param dict result: Results from API call for one file
:return str string: Organized results for printing
"""
string = ""
# Validation Response ... | [
"def",
"create_detailed_results",
"(",
"result",
")",
":",
"string",
"=",
"\"\"",
"# Validation Response output",
"# string += \"VALIDATION RESPONSE\\n\"",
"string",
"+=",
"\"STATUS: {}\\n\"",
".",
"format",
"(",
"result",
"[",
"\"status\"",
"]",
")",
"if",
"result",
... | 41.761905 | 0.00223 |
def DOM_setAttributesAsText(self, nodeId, text, **kwargs):
"""
Function path: DOM.setAttributesAsText
Domain: DOM
Method name: setAttributesAsText
Parameters:
Required arguments:
'nodeId' (type: NodeId) -> Id of the element to set attributes for.
'text' (type: string) -> Text with a number... | [
"def",
"DOM_setAttributesAsText",
"(",
"self",
",",
"nodeId",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"text",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'text' must be of type '['str']'. Received type: '%s'\"",
"%",
"ty... | 44.366667 | 0.036029 |
def _parseCommandLineOptions(args):
"""Parse command line options
Args:
args: command line arguments (not including sys.argv[0])
Returns:
namedtuple ParseCommandLineOptionsResult
"""
usageStr = (
"%prog [options] descriptionPyDirectory\n"
"This script runs a single OPF Model described by desc... | [
"def",
"_parseCommandLineOptions",
"(",
"args",
")",
":",
"usageStr",
"=",
"(",
"\"%prog [options] descriptionPyDirectory\\n\"",
"\"This script runs a single OPF Model described by description.py \"",
"\"located in the given directory.\"",
")",
"parser",
"=",
"optparse",
".",
"Opti... | 41.113821 | 0.008689 |
def _LogRecord_msg():
"""
Overrides logging.LogRecord.msg attribute to ensure variable content is stored as unicode.
"""
def _LogRecord_msgProperty(self):
return self.__msg
def _LogRecord_msgSetter(self, value):
self.__msg = to_unicode(value)
logging.LogRecord.msg = property(_... | [
"def",
"_LogRecord_msg",
"(",
")",
":",
"def",
"_LogRecord_msgProperty",
"(",
"self",
")",
":",
"return",
"self",
".",
"__msg",
"def",
"_LogRecord_msgSetter",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"__msg",
"=",
"to_unicode",
"(",
"value",
")",
... | 29.416667 | 0.008242 |
def parents(self, vertex):
"""
Return the list of immediate parents of this vertex.
"""
return [self.tail(edge) for edge in self.in_edges(vertex)] | [
"def",
"parents",
"(",
"self",
",",
"vertex",
")",
":",
"return",
"[",
"self",
".",
"tail",
"(",
"edge",
")",
"for",
"edge",
"in",
"self",
".",
"in_edges",
"(",
"vertex",
")",
"]"
] | 29 | 0.011173 |
def get_or_create(cls, key, defaults={}):
'''
A port of functionality from the Django ORM. Defaults can be passed in
if creating a new document is necessary. Keyword args are used to
lookup the document. Returns a tuple of (object, created), where object
is the retrieved or creat... | [
"def",
"get_or_create",
"(",
"cls",
",",
"key",
",",
"defaults",
"=",
"{",
"}",
")",
":",
"instance",
"=",
"cls",
".",
"get",
"(",
"key",
")",
"if",
"not",
"instance",
":",
"created",
"=",
"True",
"data",
"=",
"dict",
"(",
"key",
"=",
"key",
")",... | 43.6 | 0.002245 |
def load_config(app_name, *args, **kwargs):
"""
Given a path to a file, parse its lines in ini-like format, and then
set them in the current namespace.
Quiet by default. Set verbose to True to see the absolute path to the config
files printed on stderr.
"""
configure_logging()
# compat... | [
"def",
"load_config",
"(",
"app_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"configure_logging",
"(",
")",
"# compatible with Python 2 and 3.",
"prefix",
"=",
"kwargs",
".",
"get",
"(",
"'prefix'",
",",
"'etc'",
")",
"verbose",
"=",
"kwargs",... | 41.447059 | 0.001941 |
def checkCompatibleParams(initialParams, laterParams):
"""
Check a later set of BLAST parameters against those originally found.
@param initialParams: A C{dict} with the originally encountered BLAST
parameter settings.
@param laterParams: A C{dict} with BLAST parameter settings encountered
... | [
"def",
"checkCompatibleParams",
"(",
"initialParams",
",",
"laterParams",
")",
":",
"# Note that although the params contains a 'date', its value is empty",
"# (as far as I've seen). This could become an issue one day if it",
"# becomes non-empty and differs between JSON files that we cat",
"#... | 44.257143 | 0.000632 |
def info(path):
''' Display synchronization information. '''
output, err = cli_syncthing_adapter.info(folder=path)
if err:
click.echo(output, err=err)
else:
stat = output['status']
click.echo("State: %s" % stat['state'])
click.echo("\nTotal Files: %s" % stat['localFiles'])
click.echo("File... | [
"def",
"info",
"(",
"path",
")",
":",
"output",
",",
"err",
"=",
"cli_syncthing_adapter",
".",
"info",
"(",
"folder",
"=",
"path",
")",
"if",
"err",
":",
"click",
".",
"echo",
"(",
"output",
",",
"err",
"=",
"err",
")",
"else",
":",
"stat",
"=",
... | 28.03125 | 0.009698 |
def update_bounds(self, bounds):
'''Update the bounds inplace'''
self.bounds = np.array(bounds, dtype='float32')
vertices, directions = self._gen_bounds(self.bounds)
self._verts_vbo.set_data(vertices)
self._directions_vbo.set_data(directions)
self.widget.update(... | [
"def",
"update_bounds",
"(",
"self",
",",
"bounds",
")",
":",
"self",
".",
"bounds",
"=",
"np",
".",
"array",
"(",
"bounds",
",",
"dtype",
"=",
"'float32'",
")",
"vertices",
",",
"directions",
"=",
"self",
".",
"_gen_bounds",
"(",
"self",
".",
"bounds"... | 39.25 | 0.012461 |
def load_buffer(self, imname, chname, img_buf, dims, dtype,
header, metadata, compressed):
"""Display a FITS image buffer.
Parameters
----------
imname : string
a name to use for the image in Ginga
chname : string
channel in which to l... | [
"def",
"load_buffer",
"(",
"self",
",",
"imname",
",",
"chname",
",",
"img_buf",
",",
"dims",
",",
"dtype",
",",
"header",
",",
"metadata",
",",
"compressed",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"received image data len=%d\"",
"%",
"(",
... | 32.826667 | 0.001183 |
def compress_gz(fname):
"""Compress the file with the given name and delete the uncompressed file.
The compressed filename is simply the input filename with '.gz' appended.
Arguments
---------
fname : str
Name of the file to compress and delete.
Returns
-------
comp_fname : st... | [
"def",
"compress_gz",
"(",
"fname",
")",
":",
"import",
"shutil",
"import",
"gzip",
"comp_fname",
"=",
"fname",
"+",
"'.gz'",
"with",
"codecs",
".",
"open",
"(",
"fname",
",",
"'rb'",
")",
"as",
"f_in",
",",
"gzip",
".",
"open",
"(",
"comp_fname",
",",... | 25.916667 | 0.00155 |
def verify(self, **kwargs):
"""
Make sure all the required values are there and that the values are
of the correct type
"""
_spec = self.c_param
try:
_allowed = self.c_allowed_values
except KeyError:
_allowed = {}
for (attribute, (... | [
"def",
"verify",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"_spec",
"=",
"self",
".",
"c_param",
"try",
":",
"_allowed",
"=",
"self",
".",
"c_allowed_values",
"except",
"KeyError",
":",
"_allowed",
"=",
"{",
"}",
"for",
"(",
"attribute",
",",
"... | 29.263158 | 0.001741 |
def trans(self, key) -> str:
"""
Root Example:
Translator()
Translator.trans('messages.hello')
resources/lang/en/messages.lang will be opened
and parsed for { 'hello': 'Some english text' }
If language is fr,
resources/lang/fr/messages.lang will be... | [
"def",
"trans",
"(",
"self",
",",
"key",
")",
"->",
"str",
":",
"key_list",
"=",
"self",
".",
"__list_key",
"(",
"key",
")",
"try",
":",
"current_selection",
"=",
"current_app",
".",
"config",
"[",
"'LANGUAGE_PACKS'",
"]",
"[",
"self",
".",
"module_name"... | 35.6875 | 0.001705 |
def send_confirm_password_email(person):
"""Sends an email to user allowing them to confirm their password."""
url = '%s/profile/login/%s/' % (
settings.REGISTRATION_BASE_URL, person.username)
context = CONTEXT.copy()
context.update({
'url': url,
'receiver': person,
})
... | [
"def",
"send_confirm_password_email",
"(",
"person",
")",
":",
"url",
"=",
"'%s/profile/login/%s/'",
"%",
"(",
"settings",
".",
"REGISTRATION_BASE_URL",
",",
"person",
".",
"username",
")",
"context",
"=",
"CONTEXT",
".",
"copy",
"(",
")",
"context",
".",
"upd... | 30.533333 | 0.002119 |
def Initialize(config=None,
external_hostname = None,
admin_password = None,
redownload_templates = False,
repack_templates = True,
token = None):
"""Initialize or update a GRR configuration."""
print("Checking write access on config %s" % ... | [
"def",
"Initialize",
"(",
"config",
"=",
"None",
",",
"external_hostname",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"redownload_templates",
"=",
"False",
",",
"repack_templates",
"=",
"True",
",",
"token",
"=",
"None",
")",
":",
"print",
"(",
... | 40.862745 | 0.014527 |
def _extrap1d(interpolator):
"""
http://stackoverflow.com/questions/2745329/
How to make scipy.interpolate return an extrapolated result beyond the
input range.
"""
xs, ys = interpolator.x, interpolator.y
def pointwise(x):
if x < xs[0]:
return ys[0] + (x - xs[0]) * (ys[... | [
"def",
"_extrap1d",
"(",
"interpolator",
")",
":",
"xs",
",",
"ys",
"=",
"interpolator",
".",
"x",
",",
"interpolator",
".",
"y",
"def",
"pointwise",
"(",
"x",
")",
":",
"if",
"x",
"<",
"xs",
"[",
"0",
"]",
":",
"return",
"ys",
"[",
"0",
"]",
"... | 26.869565 | 0.001563 |
def from_indra_pickle(path: str,
name: Optional[str] = None,
version: Optional[str] = None,
description: Optional[str] = None,
authors: Optional[str] = None,
contact: Optional[str] = None,
... | [
"def",
"from_indra_pickle",
"(",
"path",
":",
"str",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"version",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"description",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
... | 36.243243 | 0.000726 |
def get_section(file_name, section, separator='='):
'''
Retrieve a section from an ini file. Returns the section as dictionary. If
the section is not found, an empty dictionary is returned.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
... | [
"def",
"get_section",
"(",
"file_name",
",",
"section",
",",
"separator",
"=",
"'='",
")",
":",
"inifile",
"=",
"_Ini",
".",
"get_ini_file",
"(",
"file_name",
",",
"separator",
"=",
"separator",
")",
"ret",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"i... | 27.307692 | 0.001361 |
def display_value(self, value):
"""Sets `sysparm_display_value`
:param value: Bool or 'all'
"""
if not (isinstance(value, bool) or value == 'all'):
raise InvalidUsage("Display value can be of type bool or value 'all'")
self._sysparms['sysparm_display_value'] = val... | [
"def",
"display_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"value",
",",
"bool",
")",
"or",
"value",
"==",
"'all'",
")",
":",
"raise",
"InvalidUsage",
"(",
"\"Display value can be of type bool or value 'all'\"",
")",
"sel... | 31.3 | 0.009317 |
def _make_signed_headers(headers, headers_to_sign):
"""
Return a semicolon-delimited list of headers to sign.
@param headers: The request headers.
@type headers: L{dict}
@param headers_to_sign: A sequence of header names that should be
signed.
@type headers_to_sign: L{bytes}
@retu... | [
"def",
"_make_signed_headers",
"(",
"headers",
",",
"headers_to_sign",
")",
":",
"return",
"b\";\"",
".",
"join",
"(",
"header",
".",
"lower",
"(",
")",
"for",
"header",
"in",
"sorted",
"(",
"headers_to_sign",
")",
"if",
"header",
"in",
"headers",
")"
] | 30.9375 | 0.001961 |
def get_profile_info(self, obj):
"""Returns the info for a Profile
"""
info = self.get_base_info(obj)
info.update({})
return info | [
"def",
"get_profile_info",
"(",
"self",
",",
"obj",
")",
":",
"info",
"=",
"self",
".",
"get_base_info",
"(",
"obj",
")",
"info",
".",
"update",
"(",
"{",
"}",
")",
"return",
"info"
] | 27.333333 | 0.011834 |
def removexattr(self, req, ino, name):
"""Remove an extended attribute
Valid replies:
reply_err
"""
self.reply_err(req, errno.ENOSYS) | [
"def",
"removexattr",
"(",
"self",
",",
"req",
",",
"ino",
",",
"name",
")",
":",
"self",
".",
"reply_err",
"(",
"req",
",",
"errno",
".",
"ENOSYS",
")"
] | 24.142857 | 0.028571 |
def do_macro_block(parser, token):
""" Function taking parsed template tag
to a MacroBlockNode.
"""
tag_name, macro_name, args, kwargs = parse_macro_params(token)
# could add extra validation on the macro_name tag
# here, but probably don't need to since we're checking
# if there's a macro b... | [
"def",
"do_macro_block",
"(",
"parser",
",",
"token",
")",
":",
"tag_name",
",",
"macro_name",
",",
"args",
",",
"kwargs",
"=",
"parse_macro_params",
"(",
"token",
")",
"# could add extra validation on the macro_name tag",
"# here, but probably don't need to since we're che... | 47.558824 | 0.001818 |
def resolve(self):
""" Resolve one or more tempids.
Automatically takes place after transaction is executed.
"""
assert isinstance(self.resp, dict), "Transaction in uncommitted or failed state"
rids = [(v) for k,v in self.resp['tempids'].items()]
self.txid = self.resp['tx-data'][0]['tx']
ri... | [
"def",
"resolve",
"(",
"self",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"resp",
",",
"dict",
")",
",",
"\"Transaction in uncommitted or failed state\"",
"rids",
"=",
"[",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"resp",
"[",
"... | 36.923077 | 0.014228 |
def get_local_part(value):
""" local-part = dot-atom / quoted-string / obs-local-part
"""
local_part = LocalPart()
leader = None
if value[0] in CFWS_LEADER:
leader, value = get_cfws(value)
if not value:
raise errors.HeaderParseError(
"expected local-part but found '{... | [
"def",
"get_local_part",
"(",
"value",
")",
":",
"local_part",
"=",
"LocalPart",
"(",
")",
"leader",
"=",
"None",
"if",
"value",
"[",
"0",
"]",
"in",
"CFWS_LEADER",
":",
"leader",
",",
"value",
"=",
"get_cfws",
"(",
"value",
")",
"if",
"not",
"value",
... | 38.5 | 0.002 |
def get_next_invalid_time_from_t(self, timestamp):
# pylint: disable=too-many-branches
"""
Get the next invalid time
:param timestamp: timestamp in seconds (of course)
:type timestamp: int or float
:return: timestamp of next invalid time
:rtype: int or float
... | [
"def",
"get_next_invalid_time_from_t",
"(",
"self",
",",
"timestamp",
")",
":",
"# pylint: disable=too-many-branches",
"timestamp",
"=",
"int",
"(",
"timestamp",
")",
"original_t",
"=",
"timestamp",
"dr_mins",
"=",
"[",
"]",
"for",
"daterange",
"in",
"self",
".",
... | 37.04918 | 0.001724 |
def parallelize_func(iterable, func, chunksz=1, n_jobs=16, *args, **kwargs):
""" Parallelize a function over each element of an iterable. """
chunker = func
chunks = more_itertools.chunked(iterable, chunksz)
chunks_results = Parallel(n_jobs=n_jobs, verbose=50)(
delayed(chunker)(chunk, *args, **k... | [
"def",
"parallelize_func",
"(",
"iterable",
",",
"func",
",",
"chunksz",
"=",
"1",
",",
"n_jobs",
"=",
"16",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"chunker",
"=",
"func",
"chunks",
"=",
"more_itertools",
".",
"chunked",
"(",
"iterable",
... | 52.25 | 0.002353 |
def replicated(*decArgs, **decKwargs):
"""Replicated decorator. Use it to mark your class members that modifies
a class state. Function will be called asynchronously. Function accepts
flowing additional parameters (optional):
'callback': callback(result, failReason), failReason - `FAIL_REASON <#pysy... | [
"def",
"replicated",
"(",
"*",
"decArgs",
",",
"*",
"*",
"decKwargs",
")",
":",
"def",
"replicatedImpl",
"(",
"func",
")",
":",
"def",
"newFunc",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"pop",
"(",
"... | 43.394737 | 0.002075 |
def removd(item, inset):
"""
Remove an item from a double precision set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/removd_c.html
:param item: Item to be removed.
:type item: float
:param inset: Set to be updated.
:type inset: spiceypy.utils.support_types.SpiceCell
"""
... | [
"def",
"removd",
"(",
"item",
",",
"inset",
")",
":",
"assert",
"isinstance",
"(",
"inset",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"inset",
".",
"dtype",
"==",
"1",
"item",
"=",
"ctypes",
".",
"c_double",
"(",
"item",
")",
"libspice",
".",
"... | 30.6 | 0.002114 |
def parse_args():
"""Create an argument parser for the ``build-stack-docs`` program.
Returns
-------
args : `argparse.Namespace`
Parsed argument object.
"""
parser = argparse.ArgumentParser(
description="Build a Sphinx documentation site for an EUPS stack, "
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Build a Sphinx documentation site for an EUPS stack, \"",
"\"such as pipelines.lsst.io.\"",
",",
"epilog",
"=",
"\"Version {0}\"",
".",
"format",
"(",
"__vers... | 30.166667 | 0.001339 |
def load_template(filename):
# type: (str) -> str
""" Load template from file.
The templates are part of the package and must be included as
``package_data`` in project ``setup.py``.
Args:
filename (str):
The template path. Relative to `peltak` package directory.
Returns:
... | [
"def",
"load_template",
"(",
"filename",
")",
":",
"# type: (str) -> str",
"template_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"PKG_DIR",
",",
"'templates'",
",",
"filename",
")",
"with",
"open",
"(",
"template_file",
")",
"as",
"fp",
":",
"return",
... | 28.588235 | 0.001992 |
def scratch_file(unlink=True, **kwargs):
"""Create a temporary file and return its name.
Additional arguments are passed to :class:`tempfile.NamedTemporaryFile`
At the start of the with block a secure, temporary file is created
and its name returned. At the end of the with block it is
deleted.
... | [
"def",
"scratch_file",
"(",
"unlink",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'delete'",
"]",
"=",
"False",
"tf",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"*",
"*",
"kwargs",
")",
"tf",
".",
"close",
"(",
")",
"try",
... | 29.058824 | 0.001961 |
def fraction_illuminated(ephemeris, body, t):
"""Compute the illuminated fraction of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be a
... | [
"def",
"fraction_illuminated",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
":",
"a",
"=",
"phase_angle",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
".",
"radians",
"return",
"0.5",
"*",
"(",
"1.0",
"+",
"cos",
"(",
"a",
")",
")"
] | 43.5 | 0.001876 |
def build_dict(img_iterator):
"""
Build a dict from files from iterator.
{'absolute_filename': {'EXIF field': 'exif tag value'}}
Parse DateTime from filename in the same loop, added as 'TIME'.
"""
files_with_tags = dict()
for f in img_iterator:
with open(str(f.abspath()), 'rb... | [
"def",
"build_dict",
"(",
"img_iterator",
")",
":",
"files_with_tags",
"=",
"dict",
"(",
")",
"for",
"f",
"in",
"img_iterator",
":",
"with",
"open",
"(",
"str",
"(",
"f",
".",
"abspath",
"(",
")",
")",
",",
"'rb'",
")",
"as",
"jpg",
":",
"tags",
"=... | 36.777778 | 0.001473 |
def register_internal_data(cls):
"""Register a new class, *cls*, with various internal data structures.
:params `sandman.model.Model` cls: class to register
"""
with app.app_context():
if getattr(cls, 'endpoint', None) is None:
orig_class = cls
cls = type('Sandman' + cl... | [
"def",
"register_internal_data",
"(",
"cls",
")",
":",
"with",
"app",
".",
"app_context",
"(",
")",
":",
"if",
"getattr",
"(",
"cls",
",",
"'endpoint'",
",",
"None",
")",
"is",
"None",
":",
"orig_class",
"=",
"cls",
"cls",
"=",
"type",
"(",
"'Sandman'"... | 41 | 0.00149 |
def send_modified_key(self, keyName, modifiers):
"""
Send a modified key (e.g. when emulating a hotkey)
"""
self.__enqueue(self.__sendModifiedKey, keyName, modifiers) | [
"def",
"send_modified_key",
"(",
"self",
",",
"keyName",
",",
"modifiers",
")",
":",
"self",
".",
"__enqueue",
"(",
"self",
".",
"__sendModifiedKey",
",",
"keyName",
",",
"modifiers",
")"
] | 38.8 | 0.010101 |
def insert_all_synapses(self, cellindex, cell):
"""
Insert all synaptic events from all presynaptic layers on
cell object with index `cellindex`.
Parameters
----------
cellindex : int
cell index in the population.
cell : `LFPy.Cell` instance
... | [
"def",
"insert_all_synapses",
"(",
"self",
",",
"cellindex",
",",
"cell",
")",
":",
"for",
"i",
",",
"X",
"in",
"enumerate",
"(",
"self",
".",
"X",
")",
":",
"#range(self.k_yXL.shape[1]):",
"synParams",
"=",
"self",
".",
"synParams",
"synParams",
".",
"upd... | 30.186047 | 0.01791 |
def search_upstream(self, device: devicetools.Device,
name: str = 'upstream') -> 'Selection':
"""Return the network upstream of the given starting point, including
the starting point itself.
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, ... | [
"def",
"search_upstream",
"(",
"self",
",",
"device",
":",
"devicetools",
".",
"Device",
",",
"name",
":",
"str",
"=",
"'upstream'",
")",
"->",
"'Selection'",
":",
"try",
":",
"selection",
"=",
"Selection",
"(",
"name",
")",
"if",
"isinstance",
"(",
"dev... | 43.321429 | 0.000806 |
def update_graph(self, dep_id=None, success=True):
"""dep_id just finished. Update our dependency
graph and submit any jobs that just became runable.
Called with dep_id=None to update entire graph for hwm, but without finishing
a task.
"""
# print ("\n\n***********")
... | [
"def",
"update_graph",
"(",
"self",
",",
"dep_id",
"=",
"None",
",",
"success",
"=",
"True",
")",
":",
"# print (\"\\n\\n***********\")",
"# pprint (dep_id)",
"# pprint (self.graph)",
"# pprint (self.depending)",
"# pprint (self.all_completed)",
"# pprint (self.all_failed)",
... | 40.763158 | 0.008827 |
def release(self):
"""Release the currently held lock.
In case the current thread holds no lock, a ValueError is thrown."""
me = currentThread()
self.__condition.acquire()
try:
if self.__writer is me:
# We are the writer, take one nesting depth away.... | [
"def",
"release",
"(",
"self",
")",
":",
"me",
"=",
"currentThread",
"(",
")",
"self",
".",
"__condition",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"__writer",
"is",
"me",
":",
"# We are the writer, take one nesting depth away.",
"self",
".",... | 42.066667 | 0.001549 |
def kallisto_alignment_plot (self):
""" Make the HighCharts HTML to plot the alignment rates """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['pseudoaligned_reads'] = { 'color': '#437bb1', 'name': 'Pseudoaligned' }
keys['not_pseudoaligned_re... | [
"def",
"kallisto_alignment_plot",
"(",
"self",
")",
":",
"# Specify the order of the different possible categories",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'pseudoaligned_reads'",
"]",
"=",
"{",
"'color'",
":",
"'#437bb1'",
",",
"'name'",
":",
"'Pseudoali... | 38.823529 | 0.014793 |
def _intersection_slice_tuples(lhs_arr, rhs_arr, offset):
"""Return tuples to yield the intersecting part of both given arrays.
The returned slices ``lhs_slc`` and ``rhs_slc`` are such that
``lhs_arr[lhs_slc]`` and ``rhs_arr[rhs_slc]`` have the same shape.
The ``offset`` parameter determines how much i... | [
"def",
"_intersection_slice_tuples",
"(",
"lhs_arr",
",",
"rhs_arr",
",",
"offset",
")",
":",
"lhs_slc",
",",
"rhs_slc",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"istart",
",",
"n_lhs",
",",
"n_rhs",
"in",
"zip",
"(",
"offset",
",",
"lhs_arr",
".",
"shape"... | 37.166667 | 0.000874 |
def delete(cls, label='default', path=None):
"""Delete a server configuration.
This method is thread safe.
:param label: A string. The configuration identified by ``label`` is
deleted.
:param path: A string. The configuration file to be manipulated.
Defaults to ... | [
"def",
"delete",
"(",
"cls",
",",
"label",
"=",
"'default'",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"_get_config_file_path",
"(",
"cls",
".",
"_xdg_config_dir",
",",
"cls",
".",
"_xdg_config_file",
")",
"cls",
... | 32.740741 | 0.002198 |
def match(self, subsetLines, offsetOfSubset, fileName):
"""
Search through lines for match.
Raise an Exception if a match
"""
for (offset,l) in enumerate(subsetLines):
for t in self.regex:
m = t.Regex.search(l)
if m != None:
... | [
"def",
"match",
"(",
"self",
",",
"subsetLines",
",",
"offsetOfSubset",
",",
"fileName",
")",
":",
"for",
"(",
"offset",
",",
"l",
")",
"in",
"enumerate",
"(",
"subsetLines",
")",
":",
"for",
"t",
"in",
"self",
".",
"regex",
":",
"m",
"=",
"t",
"."... | 46.333333 | 0.011283 |
def patched_fax_v1_init(self, domain):
"""
Initialize the V1 version of Fax
:returns: V1 version of Fax
:rtype: twilio.rest.fax.v1.V1.V1
"""
print(domain.__class__.__name__)
super(TwilioV1, self).__init__(domain)
self.version = "2010-04-01/Accounts/" + domain.account_sid
self._faxes = None | [
"def",
"patched_fax_v1_init",
"(",
"self",
",",
"domain",
")",
":",
"print",
"(",
"domain",
".",
"__class__",
".",
"__name__",
")",
"super",
"(",
"TwilioV1",
",",
"self",
")",
".",
"__init__",
"(",
"domain",
")",
"self",
".",
"version",
"=",
"\"2010-04-0... | 29.9 | 0.019481 |
def refresh(self, credentials=False):
"""
::
GET /:login/machines/:id
:param credentials: whether to return machine passwords
:type credentials: :py:class:`bool`
Fetch the existing state and values for the
:py:class:`smartdc.machine... | [
"def",
"refresh",
"(",
"self",
",",
"credentials",
"=",
"False",
")",
":",
"data",
"=",
"self",
".",
"datacenter",
".",
"raw_machine_data",
"(",
"self",
".",
"id",
",",
"credentials",
"=",
"credentials",
")",
"self",
".",
"_save",
"(",
"data",
")"
] | 31.875 | 0.017143 |
def root2hdf5(rfile, hfile, rpath='',
entries=-1, userfunc=None,
show_progress=False,
ignore_exception=False,
**kwargs):
"""
Convert all trees in a ROOT file into tables in an HDF5 file.
Parameters
----------
rfile : string or asrootpy'd ROOT... | [
"def",
"root2hdf5",
"(",
"rfile",
",",
"hfile",
",",
"rpath",
"=",
"''",
",",
"entries",
"=",
"-",
"1",
",",
"userfunc",
"=",
"None",
",",
"show_progress",
"=",
"False",
",",
"ignore_exception",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"own_r... | 32.413223 | 0.000247 |
def get_normed_points(point_array, norm): # good to go
"""
input: point_array, norm
output: normed array
"""
norm = float(norm)
#floated_array = []
#for p in point_array: # need to make sure each point is a float
#floated_array.append(float(p))
points = old_div(numpy.array(point_... | [
"def",
"get_normed_points",
"(",
"point_array",
",",
"norm",
")",
":",
"# good to go",
"norm",
"=",
"float",
"(",
"norm",
")",
"#floated_array = []",
"#for p in point_array: # need to make sure each point is a float",
"#floated_array.append(float(p))",
"points",
"=",
"old_div... | 31 | 0.017094 |
def validate(self, command, args):
"""
Validates Parameters args for command specified by its name using defined schema.
If validation schema is not defined than the methods returns no errors.
It returns validation error if the command is not found.
:param command: the n... | [
"def",
"validate",
"(",
"self",
",",
"command",
",",
"args",
")",
":",
"cref",
"=",
"self",
".",
"find_command",
"(",
"command",
")",
"if",
"cref",
"==",
"None",
":",
"results",
"=",
"[",
"]",
"results",
".",
"append",
"(",
"ValidationResult",
"(",
"... | 39.925926 | 0.009964 |
def findOverlappingSNPsWithGoldStandard(prefix, gold_prefixe, out_prefix,
use_marker_names=False):
"""Find the overlapping SNPs in 4 different data sets."""
# Reading the main file
sourceSnpToExtract = {}
if use_marker_names:
sourceSnpToExtract = set()
... | [
"def",
"findOverlappingSNPsWithGoldStandard",
"(",
"prefix",
",",
"gold_prefixe",
",",
"out_prefix",
",",
"use_marker_names",
"=",
"False",
")",
":",
"# Reading the main file",
"sourceSnpToExtract",
"=",
"{",
"}",
"if",
"use_marker_names",
":",
"sourceSnpToExtract",
"="... | 35.873684 | 0.000286 |
def parse_ids(self, skiprecover):
'''IDS file has a list of contigs that need to be ordered. 'recover',
keyword, if available in the third column, is less confident.
tig00015093 46912
tig00035238 46779 recover
tig00030900 119291
'''
idsfile = self.i... | [
"def",
"parse_ids",
"(",
"self",
",",
"skiprecover",
")",
":",
"idsfile",
"=",
"self",
".",
"idsfile",
"logging",
".",
"debug",
"(",
"\"Parse idsfile `{}`\"",
".",
"format",
"(",
"idsfile",
")",
")",
"fp",
"=",
"open",
"(",
"idsfile",
")",
"tigs",
"=",
... | 33.2 | 0.001951 |
def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently b... | [
"def",
"pair",
"(",
"address",
",",
"key",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"validate",
".",
"net",
".",
"mac",
"(",
"address",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid BD address passed to bluetooth.pair'",
")",
"try",
":"... | 28.176471 | 0.001009 |
def match_files(self, files, separators=None):
"""
Matches the files to this path-spec.
*files* (:class:`~collections.abc.Iterable` of :class:`str`) contains
the file paths to be matched against :attr:`self.patterns
<PathSpec.patterns>`.
*separators* (:class:`~collections.abc.Collection` of :class:`str`;
... | [
"def",
"match_files",
"(",
"self",
",",
"files",
",",
"separators",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"files",
",",
"(",
"bytes",
",",
"unicode",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"files:{!r} is not an iterable.\"",
".",
"format",
"... | 35.913043 | 0.023585 |
def conn_target(self):
"""Connect to the target.
"""
shutit_global.shutit_global_object.yield_to_draw()
conn_module = None
for mod in self.conn_modules:
if mod.module_id == self.build['conn_module']:
conn_module = mod
break
if conn_module is None:
self.fail('Couldn\'t find conn_module ' + self... | [
"def",
"conn_target",
"(",
"self",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"conn_module",
"=",
"None",
"for",
"mod",
"in",
"self",
".",
"conn_modules",
":",
"if",
"mod",
".",
"module_id",
"==",
"self",
".",
"... | 29.266667 | 0.037528 |
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
... | [
"def",
"get_roles",
"(",
"username",
")",
":",
"info",
"=",
"sendline",
"(",
"'show user-account {0}'",
".",
"format",
"(",
"username",
")",
")",
"roles",
"=",
"re",
".",
"search",
"(",
"r'^\\s*roles:(.*)$'",
",",
"info",
",",
"re",
".",
"MULTILINE",
")",
... | 26.2 | 0.002457 |
def write_file(fname_parts, content):
""" write a file and create all needed directories """
fname_parts = [str(part) for part in fname_parts]
# try to create the directory
if len(fname_parts) > 1:
try:
os.makedirs(os.path.join(*fname_parts[:-1]))
except OSError:
... | [
"def",
"write_file",
"(",
"fname_parts",
",",
"content",
")",
":",
"fname_parts",
"=",
"[",
"str",
"(",
"part",
")",
"for",
"part",
"in",
"fname_parts",
"]",
"# try to create the directory",
"if",
"len",
"(",
"fname_parts",
")",
">",
"1",
":",
"try",
":",
... | 30.571429 | 0.002268 |
def customer(self):
"""Return the customer for this subscription."""
url = self._get_link('customer')
if url:
resp = self.client.customers.perform_api_call(self.client.customers.REST_READ, url)
return Customer(resp) | [
"def",
"customer",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_get_link",
"(",
"'customer'",
")",
"if",
"url",
":",
"resp",
"=",
"self",
".",
"client",
".",
"customers",
".",
"perform_api_call",
"(",
"self",
".",
"client",
".",
"customers",
".",
... | 43 | 0.011407 |
def guess_task_type(name, task_defn):
"""Guess the task type of the task.
Args:
name (str): the name of the task.
Returns:
str: the task_type.
Raises:
CoTError: on invalid task_type.
"""
parts = name.split(':')
task_type = parts[-1]
if task_type == 'parent':
... | [
"def",
"guess_task_type",
"(",
"name",
",",
"task_defn",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"':'",
")",
"task_type",
"=",
"parts",
"[",
"-",
"1",
"]",
"if",
"task_type",
"==",
"'parent'",
":",
"if",
"is_action",
"(",
"task_defn",
")",
... | 22.6 | 0.001698 |
def create_feature_array(text, n_pad=21):
"""
Create feature array of character and surrounding characters
"""
n = len(text)
n_pad_2 = int((n_pad - 1)/2)
text_pad = [' '] * n_pad_2 + [t for t in text] + [' '] * n_pad_2
x_char, x_type = [], []
for i in range(n_pad_2, n_pad_2 + n):
... | [
"def",
"create_feature_array",
"(",
"text",
",",
"n_pad",
"=",
"21",
")",
":",
"n",
"=",
"len",
"(",
"text",
")",
"n_pad_2",
"=",
"int",
"(",
"(",
"n_pad",
"-",
"1",
")",
"/",
"2",
")",
"text_pad",
"=",
"[",
"' '",
"]",
"*",
"n_pad_2",
"+",
"["... | 40.25 | 0.002427 |
def configurar_interface_de_rede(self, configuracao):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
"""
resp = self._http_post('configurarinterfacederede',
co... | [
"def",
"configurar_interface_de_rede",
"(",
"self",
",",
"configuracao",
")",
":",
"resp",
"=",
"self",
".",
"_http_post",
"(",
"'configurarinterfacederede'",
",",
"configuracao",
"=",
"configuracao",
".",
"documento",
"(",
")",
")",
"conteudo",
"=",
"resp",
"."... | 45.9 | 0.010684 |
def _unwrap(self, ret_fun, err_fun):
"""Iterate over the options in the choice type, and try to perform some
action on them. If the action fails (returns None or raises either CoercionError
or ValueError), then it goes on to the next type.
Args:
ret_fun: a function that takes a wrapped option val... | [
"def",
"_unwrap",
"(",
"self",
",",
"ret_fun",
",",
"err_fun",
")",
":",
"for",
"opt",
"in",
"self",
".",
"CHOICES",
":",
"if",
"isinstance",
"(",
"self",
".",
"_value",
",",
"opt",
")",
":",
"return",
"ret_fun",
"(",
"self",
".",
"_value",
")",
"e... | 41.333333 | 0.011823 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.