text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def lint(self, dataset=None, col=None, no_header=False,
ignore_nfd=False, ignore_ws=False, linewise=False, no_lines=False):
"""
Returns a string containing all the issues found in the dataset
defined by the given file path.
"""
reader = Reader(dataset, has_header=not no_header, ipa_col=col)
recog = Rec... | [
"def",
"lint",
"(",
"self",
",",
"dataset",
"=",
"None",
",",
"col",
"=",
"None",
",",
"no_header",
"=",
"False",
",",
"ignore_nfd",
"=",
"False",
",",
"ignore_ws",
"=",
"False",
",",
"linewise",
"=",
"False",
",",
"no_lines",
"=",
"False",
")",
":",... | 31.9 | 0.027397 |
def pem(self):
"""
Serialize in PEM format
"""
bio = Membio()
if not libcrypto.PEM_write_bio_CMS(bio.bio, self.ptr):
raise CMSError("writing CMS to PEM")
return str(bio) | [
"def",
"pem",
"(",
"self",
")",
":",
"bio",
"=",
"Membio",
"(",
")",
"if",
"not",
"libcrypto",
".",
"PEM_write_bio_CMS",
"(",
"bio",
".",
"bio",
",",
"self",
".",
"ptr",
")",
":",
"raise",
"CMSError",
"(",
"\"writing CMS to PEM\"",
")",
"return",
"str"... | 27.75 | 0.008734 |
def _Backward2a_T_Ps(P, s):
"""Backward equation for region 2a, T=f(P,s)
Parameters
----------
P : float
Pressure, [MPa]
s : float
Specific entropy, [kJ/kgK]
Returns
-------
T : float
Temperature, [K]
References
----------
IAPWS, Revised Release on ... | [
"def",
"_Backward2a_T_Ps",
"(",
"P",
",",
"s",
")",
":",
"I",
"=",
"[",
"-",
"1.5",
",",
"-",
"1.5",
",",
"-",
"1.5",
",",
"-",
"1.5",
",",
"-",
"1.5",
",",
"-",
"1.5",
",",
"-",
"1.25",
",",
"-",
"1.25",
",",
"-",
"1.25",
",",
"-",
"1.0"... | 39.689655 | 0.000848 |
def _totalsize_handler(self, args):
'''Handler of total_size command'''
total_size = 0
for src, size in self.s3handler().size(args[1:]):
total_size += size
message(str(total_size)) | [
"def",
"_totalsize_handler",
"(",
"self",
",",
"args",
")",
":",
"total_size",
"=",
"0",
"for",
"src",
",",
"size",
"in",
"self",
".",
"s3handler",
"(",
")",
".",
"size",
"(",
"args",
"[",
"1",
":",
"]",
")",
":",
"total_size",
"+=",
"size",
"messa... | 32.833333 | 0.009901 |
def deploy(self, site=None):
"""
Writes entire crontab to the host.
"""
r = self.local_renderer
self.deploy_logrotate()
cron_crontabs = []
# if self.verbose:
# print('hostname: "%s"' % (hostname,), file=sys.stderr)
for _site, site_data in sel... | [
"def",
"deploy",
"(",
"self",
",",
"site",
"=",
"None",
")",
":",
"r",
"=",
"self",
".",
"local_renderer",
"self",
".",
"deploy_logrotate",
"(",
")",
"cron_crontabs",
"=",
"[",
"]",
"# if self.verbose:",
"# print('hostname: \"%s\"' % (hostname,),... | 40.666667 | 0.001715 |
def search_payload(self, fields=None, query=None):
"""Create a search query.
Do the following:
1. Generate a search query. By default, all values returned by
:meth:`nailgun.entity_mixins.Entity.get_values` are used. If
``fields`` is specified, only the named values are us... | [
"def",
"search_payload",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"query",
"=",
"None",
")",
":",
"if",
"fields",
"is",
"None",
":",
"fields",
"=",
"set",
"(",
"self",
".",
"get_values",
"(",
")",
".",
"keys",
"(",
")",
")",
"if",
"query",
"... | 39.558442 | 0.000641 |
def class_of ( object ):
""" Returns a string containing the class name of an object with the
correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
'a PlotValue').
"""
if isinstance( object, basestring ):
return add_article( object )
return add_article( object.__class... | [
"def",
"class_of",
"(",
"object",
")",
":",
"if",
"isinstance",
"(",
"object",
",",
"basestring",
")",
":",
"return",
"add_article",
"(",
"object",
")",
"return",
"add_article",
"(",
"object",
".",
"__class__",
".",
"__name__",
")"
] | 36.111111 | 0.03003 |
def predicate_type(self, pred: URIRef) -> URIRef:
"""
Return the type of pred
:param pred: predicate to map
:return:
"""
return self._o.value(pred, RDFS.range) | [
"def",
"predicate_type",
"(",
"self",
",",
"pred",
":",
"URIRef",
")",
"->",
"URIRef",
":",
"return",
"self",
".",
"_o",
".",
"value",
"(",
"pred",
",",
"RDFS",
".",
"range",
")"
] | 28.714286 | 0.009662 |
def connect(
self: _IOStreamType, address: tuple, server_hostname: str = None
) -> "Future[_IOStreamType]":
"""Connects the socket to a remote address without blocking.
May only be called if the socket passed to the constructor was
not previously connected. The address parameter is... | [
"def",
"connect",
"(",
"self",
":",
"_IOStreamType",
",",
"address",
":",
"tuple",
",",
"server_hostname",
":",
"str",
"=",
"None",
")",
"->",
"\"Future[_IOStreamType]\"",
":",
"self",
".",
"_connecting",
"=",
"True",
"future",
"=",
"Future",
"(",
")",
"# ... | 43.652778 | 0.000933 |
def get_app_from_path(path):
'''
:param path: A string to attempt to resolve to an app object
:type path: string
:returns: The describe hash of the app object if found, or None otherwise
:rtype: dict or None
This method parses a string that is expected to perhaps refer to
an app object. If... | [
"def",
"get_app_from_path",
"(",
"path",
")",
":",
"alias",
"=",
"None",
"if",
"not",
"path",
".",
"startswith",
"(",
"'app-'",
")",
":",
"path",
"=",
"'app-'",
"+",
"path",
"if",
"'/'",
"in",
"path",
":",
"alias",
"=",
"path",
"[",
"path",
".",
"f... | 32.956522 | 0.001282 |
def get_object(model, cid, engine_name=None, connection=None):
"""
Get cached object from redis
if id is None then return None:
"""
from uliweb import settings
if not id:
return
if not check_enable():
return
redis = get_redis()
if not redis: retur... | [
"def",
"get_object",
"(",
"model",
",",
"cid",
",",
"engine_name",
"=",
"None",
",",
"connection",
"=",
"None",
")",
":",
"from",
"uliweb",
"import",
"settings",
"if",
"not",
"id",
":",
"return",
"if",
"not",
"check_enable",
"(",
")",
":",
"return",
"r... | 25.028571 | 0.010989 |
def start_publishing(mysql_settings, **kwargs):
"""Start publishing MySQL row-based binlog events to blinker signals
Args:
mysql_settings (dict): information to connect to mysql via pymysql
**kwargs: The additional kwargs will be passed to
:py:class:`pymysqlreplication.BinLogStreamReade... | [
"def",
"start_publishing",
"(",
"mysql_settings",
",",
"*",
"*",
"kwargs",
")",
":",
"_logger",
".",
"info",
"(",
"'Start publishing from %s with:\\n%s'",
"%",
"(",
"mysql_settings",
",",
"kwargs",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"'server_id'",
",",
... | 34.75 | 0.000778 |
def gcs_files(prefix_filter=None):
"""List all files in GCS bucket."""
top_level_xml_str = download_gcs_file("", prefix_filter=prefix_filter)
xml_root = ElementTree.fromstring(top_level_xml_str)
filenames = [el[0].text for el in xml_root if el.tag.endswith("Contents")]
return filenames | [
"def",
"gcs_files",
"(",
"prefix_filter",
"=",
"None",
")",
":",
"top_level_xml_str",
"=",
"download_gcs_file",
"(",
"\"\"",
",",
"prefix_filter",
"=",
"prefix_filter",
")",
"xml_root",
"=",
"ElementTree",
".",
"fromstring",
"(",
"top_level_xml_str",
")",
"filenam... | 48.5 | 0.02027 |
def WhatMustIUnderstand(self):
'''Return a list of (uri,localname) tuples for all elements in the
header that have mustUnderstand set.
'''
return [ ( E.namespaceURI, E.localName )
for E in self.header_elements if _find_mu(E) == "1" ] | [
"def",
"WhatMustIUnderstand",
"(",
"self",
")",
":",
"return",
"[",
"(",
"E",
".",
"namespaceURI",
",",
"E",
".",
"localName",
")",
"for",
"E",
"in",
"self",
".",
"header_elements",
"if",
"_find_mu",
"(",
"E",
")",
"==",
"\"1\"",
"]"
] | 46 | 0.024911 |
def make_movie(q: np.ndarray, step: int, bodies: List[str], plot_colors: Dict[str, str], fname: str):
"""
Make a series of frames of the planetary orbits that can be assembled into a movie.
q is a Nx3B array. t indexes time points. 3B columns are (x, y, z) for the bodies in order.
"""
# Get N and ... | [
"def",
"make_movie",
"(",
"q",
":",
"np",
".",
"ndarray",
",",
"step",
":",
"int",
",",
"bodies",
":",
"List",
"[",
"str",
"]",
",",
"plot_colors",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"fname",
":",
"str",
")",
":",
"# Get N and number of... | 41.116279 | 0.009392 |
def is_temple_project():
"""Raises `InvalidTempleProjectError` if repository is not a temple project"""
if not os.path.exists(temple.constants.TEMPLE_CONFIG_FILE):
msg = 'No {} file found in repository.'.format(temple.constants.TEMPLE_CONFIG_FILE)
raise temple.exceptions.InvalidTempleProjectErro... | [
"def",
"is_temple_project",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"temple",
".",
"constants",
".",
"TEMPLE_CONFIG_FILE",
")",
":",
"msg",
"=",
"'No {} file found in repository.'",
".",
"format",
"(",
"temple",
".",
"constants",
"... | 64.4 | 0.009202 |
def path(self, value):
"""
Setter for **self.__path** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("path", value)
self._... | [
"def",
"path",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"unicode",
",",
"\"'{0}' attribute: '{1}' type is not 'unicode'!\"",
".",
"format",
"(",
"\"path\"",
",",
"value",
")",
... | 29.363636 | 0.009009 |
def parse_posting_id(text, city):
"""
Parse the posting ID from the Backpage ad.
text -> The ad's HTML (or the a substring containing the "Post ID:" section)
city -> The Backpage city of the ad
"""
parts = text.split('Post ID: ')
if len(parts) == 2:
post_id = parts[1].split(' ')[0]
if p... | [
"def",
"parse_posting_id",
"(",
"text",
",",
"city",
")",
":",
"parts",
"=",
"text",
".",
"split",
"(",
"'Post ID: '",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
":",
"post_id",
"=",
"parts",
"[",
"1",
"]",
".",
"split",
"(",
"' '",
")",
"["... | 33.090909 | 0.018717 |
def _command_line(): # pragma: no cover pylint: disable=too-many-branches,too-many-statements
"""
Provide the command line interface.
"""
if __name__ == "PyFunceble":
# We initiate the end of the coloration at the end of each line.
initiate(autoreset=True)
# We load the config... | [
"def",
"_command_line",
"(",
")",
":",
"# pragma: no cover pylint: disable=too-many-branches,too-many-statements",
"if",
"__name__",
"==",
"\"PyFunceble\"",
":",
"# We initiate the end of the coloration at the end of each line.",
"initiate",
"(",
"autoreset",
"=",
"True",
")",
"#... | 35.705357 | 0.001251 |
def _compute_rtfilter_map(self):
"""Returns neighbor's RT filter (permit/allow filter based on RT).
Walks RT filter tree and computes current RT filters for each peer that
have advertised RT NLRIs.
Returns:
dict of peer, and `set` of rts that a particular neighbor is
... | [
"def",
"_compute_rtfilter_map",
"(",
"self",
")",
":",
"rtfilter_map",
"=",
"{",
"}",
"def",
"get_neigh_filter",
"(",
"neigh",
")",
":",
"neigh_filter",
"=",
"rtfilter_map",
".",
"get",
"(",
"neigh",
")",
"# Lazy creation of neighbor RT filter",
"if",
"neigh_filte... | 43.25 | 0.000754 |
def commit(self):
"""
Delete the rest of the line.
"""
# Get the text cursor for the current document and unselect
# everything.
tc = self.qteWidget.textCursor()
tc.clearSelection()
# If this is the first ever call to this undo/redo element then
... | [
"def",
"commit",
"(",
"self",
")",
":",
"# Get the text cursor for the current document and unselect",
"# everything.",
"tc",
"=",
"self",
".",
"qteWidget",
".",
"textCursor",
"(",
")",
"tc",
".",
"clearSelection",
"(",
")",
"# If this is the first ever call to this undo/... | 37.34375 | 0.001631 |
def run_in_memory(args, edges):
"""Run OSLOM with an in-memory list of edges, return in-memory results."""
# Create an OSLOM runner with a temporary working directory
oslom_runner = OslomRunner(tempfile.mkdtemp())
# Write temporary edges file with re-mapped Ids
logging.info("writing temporary edges... | [
"def",
"run_in_memory",
"(",
"args",
",",
"edges",
")",
":",
"# Create an OSLOM runner with a temporary working directory",
"oslom_runner",
"=",
"OslomRunner",
"(",
"tempfile",
".",
"mkdtemp",
"(",
")",
")",
"# Write temporary edges file with re-mapped Ids",
"logging",
".",... | 38.818182 | 0.001523 |
def on_recv_rsp(self, rsp_pb):
"""receive response callback function"""
ret_code, msg, conn_info_map = InitConnect.unpack_rsp(rsp_pb)
if self._notify_obj is not None:
self._notify_obj.on_async_init_connect(ret_code, msg, conn_info_map)
return ret_code, msg | [
"def",
"on_recv_rsp",
"(",
"self",
",",
"rsp_pb",
")",
":",
"ret_code",
",",
"msg",
",",
"conn_info_map",
"=",
"InitConnect",
".",
"unpack_rsp",
"(",
"rsp_pb",
")",
"if",
"self",
".",
"_notify_obj",
"is",
"not",
"None",
":",
"self",
".",
"_notify_obj",
"... | 36.875 | 0.009934 |
def collect_columns(self):
"""
Collect columns information from a given model.
a column info contains
the py3 informations
exclude
Should the column be excluded from the current context ?
name
the name of t... | [
"def",
"collect_columns",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"for",
"prop",
"in",
"self",
".",
"get_sorted_columns",
"(",
")",
":",
"info_dict",
"=",
"self",
".",
"get_info_field",
"(",
"prop",
")",
"export_infos",
"=",
"info_dict",
".",
"get",... | 27.237288 | 0.001201 |
def save(markov, fname, args):
"""Save a generator.
Parameters
----------
markov : `markovchain.Markov`
Generator to save.
fname : `str`
Output file path.
args : `argparse.Namespace`
Command arguments.
"""
if isinstance(markov.storage, JsonStorage):
if fn... | [
"def",
"save",
"(",
"markov",
",",
"fname",
",",
"args",
")",
":",
"if",
"isinstance",
"(",
"markov",
".",
"storage",
",",
"JsonStorage",
")",
":",
"if",
"fname",
"is",
"None",
":",
"markov",
".",
"save",
"(",
"sys",
".",
"stdout",
")",
"else",
":"... | 25.307692 | 0.001464 |
def median(numbers):
"""
Return the median of the list of numbers.
see: http://mail.python.org/pipermail/python-list/2004-December/294990.html
"""
# Sort the list and take the middle element.
n = len(numbers)
copy = sorted(numbers)
if n & 1: # There is an odd number of elements
... | [
"def",
"median",
"(",
"numbers",
")",
":",
"# Sort the list and take the middle element.",
"n",
"=",
"len",
"(",
"numbers",
")",
"copy",
"=",
"sorted",
"(",
"numbers",
")",
"if",
"n",
"&",
"1",
":",
"# There is an odd number of elements",
"return",
"copy",
"[",
... | 30.230769 | 0.002469 |
async def findTask(self, *args, **kwargs):
"""
Find Indexed Task
Find a task by index path, returning the highest-rank task with that path. If no
task exists for the given path, this API end-point will respond with a 404 status.
This method gives output: ``v1/indexed-task-respo... | [
"async",
"def",
"findTask",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"findTask\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 34.615385 | 0.010823 |
def tplot_names():
"""
This function will print out and return a list of all current Tplot Variables stored in the memory.
Parameters:
None
Returns:
list : list of str
A list of all Tplot Variables stored in the memory
Examples:
>>> i... | [
"def",
"tplot_names",
"(",
")",
":",
"index",
"=",
"0",
"return_names",
"=",
"[",
"]",
"for",
"key",
",",
"_",
"in",
"data_quants",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"data_quants",
"[",
"key",
"]",
".",
"data",
",",
"list",
")",... | 30.948718 | 0.008835 |
def safe_rmtree(directory):
"""Delete a directory if it's present. If it's not present, no-op."""
if os.path.exists(directory):
shutil.rmtree(directory, True) | [
"def",
"safe_rmtree",
"(",
"directory",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"shutil",
".",
"rmtree",
"(",
"directory",
",",
"True",
")"
] | 40.75 | 0.018072 |
def getServiceEndpoints(input_url, flt=None):
"""Perform the Yadis protocol on the input URL and return an
iterable of resulting endpoint objects.
@param flt: A filter object or something that is convertable to
a filter object (using mkFilter) that will be used to generate
endpoint objects.... | [
"def",
"getServiceEndpoints",
"(",
"input_url",
",",
"flt",
"=",
"None",
")",
":",
"result",
"=",
"discover",
"(",
"input_url",
")",
"try",
":",
"endpoints",
"=",
"applyFilter",
"(",
"result",
".",
"normalized_uri",
",",
"result",
".",
"response_text",
",",
... | 37.44 | 0.001042 |
def flatten(cls, stats):
"""Makes a flat statistics from the given statistics."""
flat_children = {}
for _stats in spread_stats(stats):
key = (_stats.name, _stats.filename, _stats.lineno, _stats.module)
try:
flat_stats = flat_children[key]
exce... | [
"def",
"flatten",
"(",
"cls",
",",
"stats",
")",
":",
"flat_children",
"=",
"{",
"}",
"for",
"_stats",
"in",
"spread_stats",
"(",
"stats",
")",
":",
"key",
"=",
"(",
"_stats",
".",
"name",
",",
"_stats",
".",
"filename",
",",
"_stats",
".",
"lineno",... | 48.470588 | 0.002381 |
def create_project(session, title, description,
currency, budget, jobs):
"""
Create a project
"""
project_data = {'title': title,
'description': description,
'currency': currency,
'budget': budget,
'jobs':... | [
"def",
"create_project",
"(",
"session",
",",
"title",
",",
"description",
",",
"currency",
",",
"budget",
",",
"jobs",
")",
":",
"project_data",
"=",
"{",
"'title'",
":",
"title",
",",
"'description'",
":",
"description",
",",
"'currency'",
":",
"currency",... | 37.8 | 0.001032 |
def hincrbyfloat(self, key, field, increment=1.0):
"""Increment the float value of a hash field by the given number."""
fut = self.execute(b'HINCRBYFLOAT', key, field, increment)
return wait_convert(fut, float) | [
"def",
"hincrbyfloat",
"(",
"self",
",",
"key",
",",
"field",
",",
"increment",
"=",
"1.0",
")",
":",
"fut",
"=",
"self",
".",
"execute",
"(",
"b'HINCRBYFLOAT'",
",",
"key",
",",
"field",
",",
"increment",
")",
"return",
"wait_convert",
"(",
"fut",
","... | 57.75 | 0.008547 |
def dicom_to_nifti(dicom_input, output_file=None):
"""
This is the main dicom to nifti conversion fuction for philips images.
As input philips images are required. It will then determine the type of images and do the correct conversion
Examples: See unit test
:param output_file: file path to the o... | [
"def",
"dicom_to_nifti",
"(",
"dicom_input",
",",
"output_file",
"=",
"None",
")",
":",
"assert",
"common",
".",
"is_philips",
"(",
"dicom_input",
")",
"if",
"common",
".",
"is_multiframe_dicom",
"(",
"dicom_input",
")",
":",
"_assert_explicit_vr",
"(",
"dicom_i... | 41.03125 | 0.001488 |
async def execute(self, raise_on_error=True):
"Execute all the commands in the current pipeline"
stack = self.command_stack
if not stack:
return []
if self.scripts:
await self.load_scripts()
if self.transaction or self.explicit_transaction:
exe... | [
"async",
"def",
"execute",
"(",
"self",
",",
"raise_on_error",
"=",
"True",
")",
":",
"stack",
"=",
"self",
".",
"command_stack",
"if",
"not",
"stack",
":",
"return",
"[",
"]",
"if",
"self",
".",
"scripts",
":",
"await",
"self",
".",
"load_scripts",
"(... | 42.947368 | 0.001198 |
def get_query_indexes(self, raw_result=False):
"""
Retrieves query indexes from the remote database.
:param bool raw_result: If set to True then the raw JSON content for
the request is returned. Default is to return a list containing
:class:`~cloudant.index.Index`,
... | [
"def",
"get_query_indexes",
"(",
"self",
",",
"raw_result",
"=",
"False",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_index'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"url",
")",
... | 37.122449 | 0.001071 |
def get_snapshot_by_version(obj, version=0):
"""Get a snapshot by version
Snapshot versions begin with `0`, because this is the first index of the
storage, which is a list.
:param obj: Content object
:param version: The index position of the snapshot in the storage
:returns: Snapshot at the gi... | [
"def",
"get_snapshot_by_version",
"(",
"obj",
",",
"version",
"=",
"0",
")",
":",
"if",
"version",
"<",
"0",
":",
"return",
"None",
"snapshots",
"=",
"get_snapshots",
"(",
"obj",
")",
"if",
"version",
">",
"len",
"(",
"snapshots",
")",
"-",
"1",
":",
... | 30.8125 | 0.001969 |
def printFrequencyStatistics(counts, frequencies, numWords, size):
"""
Print interesting statistics regarding the counts and frequency matrices
"""
avgBits = float(counts.sum())/numWords
print "Retina width=128, height=128"
print "Total number of words processed=",numWords
print "Average number of bits pe... | [
"def",
"printFrequencyStatistics",
"(",
"counts",
",",
"frequencies",
",",
"numWords",
",",
"size",
")",
":",
"avgBits",
"=",
"float",
"(",
"counts",
".",
"sum",
"(",
")",
")",
"/",
"numWords",
"print",
"\"Retina width=128, height=128\"",
"print",
"\"Total numbe... | 44.8125 | 0.035519 |
def update(self, adgroup_id, default_price, nonsearch_max_price, is_nonsearch_default_price, online_status, campaign_id, nick=None):
'''xxxxx.xxxxx.adgroup.update
===================================
更新一个推广组的信息,可以设置默认出价、是否上线、非搜索出价、非搜索是否使用默认出价'''
request = TOPRequest('xxxxx.xxxxx.adgroup.u... | [
"def",
"update",
"(",
"self",
",",
"adgroup_id",
",",
"default_price",
",",
"nonsearch_max_price",
",",
"is_nonsearch_default_price",
",",
"online_status",
",",
"campaign_id",
",",
"nick",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'xxxxx.xxxxx.adg... | 60.642857 | 0.013921 |
def result_type(*arrays_and_dtypes):
"""Like np.result_type, but with type promotion rules matching pandas.
Examples of changed behavior:
number + string -> object (not string)
bytes + unicode -> object (not unicode)
Parameters
----------
*arrays_and_dtypes : list of arrays and dtypes
... | [
"def",
"result_type",
"(",
"*",
"arrays_and_dtypes",
")",
":",
"types",
"=",
"{",
"np",
".",
"result_type",
"(",
"t",
")",
".",
"type",
"for",
"t",
"in",
"arrays_and_dtypes",
"}",
"for",
"left",
",",
"right",
"in",
"PROMOTE_TO_OBJECT",
":",
"if",
"(",
... | 30.25 | 0.001335 |
def _station(self) -> str:
"""Extract station name."""
return str(self.obj.SBRes.SBReq.Start.Station.HafasName.Text.pyval) | [
"def",
"_station",
"(",
"self",
")",
"->",
"str",
":",
"return",
"str",
"(",
"self",
".",
"obj",
".",
"SBRes",
".",
"SBReq",
".",
"Start",
".",
"Station",
".",
"HafasName",
".",
"Text",
".",
"pyval",
")"
] | 45.333333 | 0.014493 |
def find_file( self, folder_id, basename, limit = 500 ):
'''
Finds a file based on a box path
Returns a list of file IDs
Returns multiple file IDs if the file was split into parts with the extension '.partN' (where N is an integer)
'''
search_folder = self.client.folder( ... | [
"def",
"find_file",
"(",
"self",
",",
"folder_id",
",",
"basename",
",",
"limit",
"=",
"500",
")",
":",
"search_folder",
"=",
"self",
".",
"client",
".",
"folder",
"(",
"folder_id",
"=",
"folder_id",
")",
"offset",
"=",
"0",
"search_items",
"=",
"search_... | 47 | 0.033545 |
def setLevel(self, level):
r"""Overrides the parent method to adapt the formatting string to the level.
Parameters
----------
level : int
The new log level to set. See the logging levels in the logging module for details.
Examples
-------... | [
"def",
"setLevel",
"(",
"self",
",",
"level",
")",
":",
"if",
"logging",
".",
"DEBUG",
">=",
"level",
":",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"\"%(asctime)s [%(levelname)-8s] %(message)s (in %(module)s.%(funcName)s:%(lineno)s)\"",
",",
"\"%d.%m.%Y %H:%M... | 40.434783 | 0.013655 |
def _GetFileAndLine():
"""Returns (filename, linenumber) for the stack frame."""
# Use sys._getframe(). This avoids creating a traceback object.
# pylint: disable=protected-access
f = _sys._getframe()
# pylint: enable=protected-access
our_file = f.f_code.co_filename
f = f.f_back
while f... | [
"def",
"_GetFileAndLine",
"(",
")",
":",
"# Use sys._getframe(). This avoids creating a traceback object.",
"# pylint: disable=protected-access",
"f",
"=",
"_sys",
".",
"_getframe",
"(",
")",
"# pylint: enable=protected-access",
"our_file",
"=",
"f",
".",
"f_code",
".",
"c... | 33.714286 | 0.002062 |
def default_endpoint_from_config(config, option=None):
"""Return a default endpoint."""
default_endpoint = config.get('core', {}).get('default')
project_endpoint = config.get('project',
{}).get('core',
{}).get('default', default_end... | [
"def",
"default_endpoint_from_config",
"(",
"config",
",",
"option",
"=",
"None",
")",
":",
"default_endpoint",
"=",
"config",
".",
"get",
"(",
"'core'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'default'",
")",
"project_endpoint",
"=",
"config",
".",
"get",
... | 40.666667 | 0.002004 |
def dump(obj, f, preserve=False):
"""Write dict object into file
:param obj: the object to be dumped into toml
:param f: the file object
:param preserve: optional flag to preserve the inline table in result
"""
if not f.write:
raise TypeError('You can only dump an object into a file obj... | [
"def",
"dump",
"(",
"obj",
",",
"f",
",",
"preserve",
"=",
"False",
")",
":",
"if",
"not",
"f",
".",
"write",
":",
"raise",
"TypeError",
"(",
"'You can only dump an object into a file object'",
")",
"encoder",
"=",
"Encoder",
"(",
"f",
",",
"preserve",
"="... | 35.818182 | 0.002475 |
def node_received_infos(node_id):
"""Get all the infos a node has been sent and has received.
You must specify the node id in the url.
You can also pass the info type.
"""
exp = Experiment(session)
# get the parameters
info_type = request_parameter(
parameter="info_type", parameter... | [
"def",
"node_received_infos",
"(",
"node_id",
")",
":",
"exp",
"=",
"Experiment",
"(",
"session",
")",
"# get the parameters",
"info_type",
"=",
"request_parameter",
"(",
"parameter",
"=",
"\"info_type\"",
",",
"parameter_type",
"=",
"\"known_class\"",
",",
"default... | 27.342105 | 0.001859 |
def date_to_string(date):
"""Transform a date or datetime object into a string and return it.
Examples:
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34, tzinfo=UTC))
'2012-01-03T12:23:34+00:00'
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34))
'2012-01-03T12:23:34'
>... | [
"def",
"date_to_string",
"(",
"date",
")",
":",
"if",
"isinstance",
"(",
"date",
",",
"datetime",
".",
"datetime",
")",
":",
"# Create an ISO 8601 datetime string",
"date_str",
"=",
"date",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%S'",
")",
"tzstr",
"=",
"date",
... | 36.925926 | 0.000978 |
def p_expression_times(self, p):
'expression : expression TIMES expression'
p[0] = Times(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_expression_times",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Times",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
... | 42.5 | 0.011561 |
def _CopyTimeFromString(self, time_string):
"""Copies a time from a string.
Args:
time_string (str): time value formatted as:
hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The seconds fraction a... | [
"def",
"_CopyTimeFromString",
"(",
"self",
",",
"time_string",
")",
":",
"time_string_length",
"=",
"len",
"(",
"time_string",
")",
"# The time string should at least contain 'hh:mm:ss'.",
"if",
"time_string_length",
"<",
"8",
":",
"raise",
"ValueError",
"(",
"'Time str... | 33.295652 | 0.008623 |
def pldist(point, start, end):
"""
Calculates the distance from ``point`` to the line given
by the points ``start`` and ``end``.
:param point: a point
:type point: numpy array
:param start: a point of the line
:type start: numpy array
:param end: another point of the line
:type end:... | [
"def",
"pldist",
"(",
"point",
",",
"start",
",",
"end",
")",
":",
"if",
"np",
".",
"all",
"(",
"np",
".",
"equal",
"(",
"start",
",",
"end",
")",
")",
":",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"point",
"-",
"start",
")",
"return",
... | 30.166667 | 0.001786 |
def _properties_from_dict(d, key_name='key'):
'''
Transforms dictionary into pipeline object properties.
The output format conforms to boto's specification.
Example input:
{
'a': '1',
'b': {
'ref': '2'
},
}
Example output:
... | [
"def",
"_properties_from_dict",
"(",
"d",
",",
"key_name",
"=",
"'key'",
")",
":",
"fields",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"d",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"fie... | 21.487179 | 0.001142 |
def FinalizeConfigInit(config,
token,
admin_password = None,
redownload_templates = False,
repack_templates = True,
prompt = True):
"""Performs the final steps of config initialization."""
config.Set("... | [
"def",
"FinalizeConfigInit",
"(",
"config",
",",
"token",
",",
"admin_password",
"=",
"None",
",",
"redownload_templates",
"=",
"False",
",",
"repack_templates",
"=",
"True",
",",
"prompt",
"=",
"True",
")",
":",
"config",
".",
"Set",
"(",
"\"Server.initialize... | 42.97561 | 0.017203 |
def xSectionLink(lines):
"""
Parse Cross Section Links Method
"""
# Constants
KEYWORDS = ('LINK',
'DX',
'TRAPEZOID',
'TRAPEZOID_ERODE',
'TRAPEZOID_SUBSURFACE',
'ERODE_TRAPEZOID',
'ERODE_SUBSURFACE',
... | [
"def",
"xSectionLink",
"(",
"lines",
")",
":",
"# Constants",
"KEYWORDS",
"=",
"(",
"'LINK'",
",",
"'DX'",
",",
"'TRAPEZOID'",
",",
"'TRAPEZOID_ERODE'",
",",
"'TRAPEZOID_SUBSURFACE'",
",",
"'ERODE_TRAPEZOID'",
",",
"'ERODE_SUBSURFACE'",
",",
"'SUBSURFACE_TRAPEZOID'",
... | 33.578947 | 0.001269 |
def make_dict(cls, table):
"""Build and return a dict of `FileHandle` from an `astropy.table.Table`
The dictionary is keyed by FileHandle.key, which is a unique integer for each file
"""
ret_dict = {}
for row in table:
file_handle = cls.create_from_row(row)
r... | [
"def",
"make_dict",
"(",
"cls",
",",
"table",
")",
":",
"ret_dict",
"=",
"{",
"}",
"for",
"row",
"in",
"table",
":",
"file_handle",
"=",
"cls",
".",
"create_from_row",
"(",
"row",
")",
"ret_dict",
"[",
"file_handle",
".",
"key",
"]",
"=",
"file_handle"... | 37.3 | 0.010471 |
def list_ctx(self):
"""Returns a list of contexts this parameter is initialized on."""
if self._data is None:
if self._deferred_init:
return self._deferred_init[1]
raise RuntimeError("Parameter '%s' has not been initialized"%self.name)
return self._ctx_lis... | [
"def",
"list_ctx",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data",
"is",
"None",
":",
"if",
"self",
".",
"_deferred_init",
":",
"return",
"self",
".",
"_deferred_init",
"[",
"1",
"]",
"raise",
"RuntimeError",
"(",
"\"Parameter '%s' has not been initialized\... | 45 | 0.012461 |
def get_power_factor(self, output='eigs', doping_levels=True,
relaxation_time=1e-14):
"""
Gives the power factor (Seebeck^2 * conductivity) in units
microW/(m*K^2) in either a full 3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
... | [
"def",
"get_power_factor",
"(",
"self",
",",
"output",
"=",
"'eigs'",
",",
"doping_levels",
"=",
"True",
",",
"relaxation_time",
"=",
"1e-14",
")",
":",
"result",
"=",
"None",
"result_doping",
"=",
"None",
"if",
"doping_levels",
":",
"result_doping",
"=",
"{... | 47.734375 | 0.000962 |
def model_to_dict(model, sort=False):
"""Convert model to a dict.
Parameters
----------
model : cobra.Model
The model to reformulate as a dict.
sort : bool, optional
Whether to sort the metabolites, reactions, and genes or maintain the
order defined in the model.
Return... | [
"def",
"model_to_dict",
"(",
"model",
",",
"sort",
"=",
"False",
")",
":",
"obj",
"=",
"OrderedDict",
"(",
")",
"obj",
"[",
"\"metabolites\"",
"]",
"=",
"list",
"(",
"map",
"(",
"metabolite_to_dict",
",",
"model",
".",
"metabolites",
")",
")",
"obj",
"... | 33.166667 | 0.000814 |
def parse_plotProfile(self):
"""Find plotProfile output"""
self.deeptools_plotProfile = dict()
for f in self.find_log_files('deeptools/plotProfile', filehandles=False):
parsed_data, bin_labels, converted_bin_labels = self.parsePlotProfileData(f)
for k, v in parsed_data.it... | [
"def",
"parse_plotProfile",
"(",
"self",
")",
":",
"self",
".",
"deeptools_plotProfile",
"=",
"dict",
"(",
")",
"for",
"f",
"in",
"self",
".",
"find_log_files",
"(",
"'deeptools/plotProfile'",
",",
"filehandles",
"=",
"False",
")",
":",
"parsed_data",
",",
"... | 64.631579 | 0.008825 |
def remove_loghandler (handler):
"""Remove log handler from root logger and LOG_ROOT."""
logging.getLogger(LOG_ROOT).removeHandler(handler)
logging.getLogger().removeHandler(handler) | [
"def",
"remove_loghandler",
"(",
"handler",
")",
":",
"logging",
".",
"getLogger",
"(",
"LOG_ROOT",
")",
".",
"removeHandler",
"(",
"handler",
")",
"logging",
".",
"getLogger",
"(",
")",
".",
"removeHandler",
"(",
"handler",
")"
] | 47.75 | 0.010309 |
def transact_with_contract_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""
Helper function for interacting with a contract function by sending a
transaction.
"""
trans... | [
"def",
"transact_with_contract_function",
"(",
"address",
",",
"web3",
",",
"function_name",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | 24.192308 | 0.001529 |
def correlation(x,
y=None,
sample_axis=0,
event_axis=-1,
keepdims=False,
name=None):
"""Sample correlation (Pearson) between observations indexed by `event_axis`.
Given `N` samples of scalar random variables `X` and `Y`, correlation ma... | [
"def",
"correlation",
"(",
"x",
",",
"y",
"=",
"None",
",",
"sample_axis",
"=",
"0",
",",
"event_axis",
"=",
"-",
"1",
",",
"keepdims",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"... | 39.694118 | 0.001446 |
def add_news(self, news):
"""
在素材库中创建图文消息
:param news: list 对象, 其中的每个元素为一个 dict 对象, 代表一条图文, key 值分别为 ``title``, ``author``, ``summary``,
``content``, ``picture_id``, ``from_url``, 对应内容为标题, 作者, 摘要, 内容, 素材库里的
图片ID(可通过 ``upload_file`` 函数上传获取), 来源链接。
... | [
"def",
"add_news",
"(",
"self",
",",
"news",
")",
":",
"if",
"not",
"news",
":",
"raise",
"ValueError",
"(",
"'The news cannot be empty'",
")",
"for",
"item",
"in",
"news",
":",
"if",
"'title'",
"not",
"in",
"item",
"or",
"'content'",
"not",
"in",
"item"... | 37.716216 | 0.002444 |
def deepcopy(original_obj):
"""
Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
object: deep copy of the ... | [
"def",
"deepcopy",
"(",
"original_obj",
")",
":",
"if",
"isinstance",
"(",
"original_obj",
",",
"list",
")",
":",
"return",
"list",
"(",
"deepcopy",
"(",
"item",
")",
"for",
"item",
"in",
"original_obj",
")",
"elif",
"isinstance",
"(",
"original_obj",
",",... | 31.944444 | 0.001689 |
def ConvCnstrMODMaskOptionsDefaults(method='fista'):
"""Get defaults dict for the ConvCnstrMODMask class specified by the
``method`` parameter.
"""
dflt = copy.deepcopy(ccmodmsk_class_label_lookup(method).Options.defaults)
if method == 'fista':
dflt.update({'MaxMainIter': 1, 'BackTrack':
... | [
"def",
"ConvCnstrMODMaskOptionsDefaults",
"(",
"method",
"=",
"'fista'",
")",
":",
"dflt",
"=",
"copy",
".",
"deepcopy",
"(",
"ccmodmsk_class_label_lookup",
"(",
"method",
")",
".",
"Options",
".",
"defaults",
")",
"if",
"method",
"==",
"'fista'",
":",
"dflt",... | 39.466667 | 0.00165 |
def newton_refine_curve(curve, point, s, new_s):
"""Image for :func:`._curve_helpers.newton_refine` docstring."""
if NO_IMAGES:
return
ax = curve.plot(256)
ax.plot(point[0, :], point[1, :], marker="H")
wrong_points = curve.evaluate_multi(np.asfortranarray([s, new_s]))
ax.plot(
w... | [
"def",
"newton_refine_curve",
"(",
"curve",
",",
"point",
",",
"s",
",",
"new_s",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"ax",
"=",
"curve",
".",
"plot",
"(",
"256",
")",
"ax",
".",
"plot",
"(",
"point",
"[",
"0",
",",
":",
"]",
",",
"point"... | 27.517241 | 0.001211 |
def get(self, device_id: int) -> Optional[Device]:
"""Get device using the specified ID, or None if not found."""
return self._devices.get(device_id) | [
"def",
"get",
"(",
"self",
",",
"device_id",
":",
"int",
")",
"->",
"Optional",
"[",
"Device",
"]",
":",
"return",
"self",
".",
"_devices",
".",
"get",
"(",
"device_id",
")"
] | 54.333333 | 0.012121 |
def get_activity_form_for_update(self, activity_id=None):
"""Gets the activity form for updating an existing activity.
A new activity form should be requested for each update
transaction.
arg: activityId (osid.id.Id): the Id of the Activity
return: (osid.learning.ActivityForm)... | [
"def",
"get_activity_form_for_update",
"(",
"self",
",",
"activity_id",
"=",
"None",
")",
":",
"if",
"activity_id",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"try",
":",
"url_path",
"=",
"construct_url",
"(",
"'activities'",
",",
"bank_id",
"=",
... | 45.8 | 0.001711 |
def token(self):
"""
Returns the next LexToken. Returns None when all tokens have been
exhausted.
"""
if self.tokens_queue:
self.last_token = self.tokens_queue.pop(0)
else:
r = self.lex.token()
if isinstance(r, MultiToken):
... | [
"def",
"token",
"(",
"self",
")",
":",
"if",
"self",
".",
"tokens_queue",
":",
"self",
".",
"last_token",
"=",
"self",
".",
"tokens_queue",
".",
"pop",
"(",
"0",
")",
"else",
":",
"r",
"=",
"self",
".",
"lex",
".",
"token",
"(",
")",
"if",
"isins... | 40.966667 | 0.00159 |
def create_attributes(klass, attributes, previous_object=None):
"""
Attributes for content type creation.
"""
result = super(ContentType, klass).create_attributes(attributes, previous_object)
if 'fields' not in result:
result['fields'] = []
return result | [
"def",
"create_attributes",
"(",
"klass",
",",
"attributes",
",",
"previous_object",
"=",
"None",
")",
":",
"result",
"=",
"super",
"(",
"ContentType",
",",
"klass",
")",
".",
"create_attributes",
"(",
"attributes",
",",
"previous_object",
")",
"if",
"'fields'... | 30.7 | 0.009494 |
def sheets(self, index=None):
"""Return either a list of all sheets if index is None, or the sheet at the given index."""
if self._sheets is None:
self._sheets = [self.get_worksheet(s, i) for i, s in enumerate(self.iterate_sheets())]
if index is None:
return self._sheets
else:
return s... | [
"def",
"sheets",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"if",
"self",
".",
"_sheets",
"is",
"None",
":",
"self",
".",
"_sheets",
"=",
"[",
"self",
".",
"get_worksheet",
"(",
"s",
",",
"i",
")",
"for",
"i",
",",
"s",
"in",
"enumerate",
... | 41.375 | 0.017751 |
def cert_base_path(cacert_path=None):
'''
Return the base path for certs from CLI or from options
cacert_path
absolute path to ca certificates root directory
CLI Example:
.. code-block:: bash
salt '*' tls.cert_base_path
'''
if not cacert_path:
cacert_path = __cont... | [
"def",
"cert_base_path",
"(",
"cacert_path",
"=",
"None",
")",
":",
"if",
"not",
"cacert_path",
":",
"cacert_path",
"=",
"__context__",
".",
"get",
"(",
"'ca.contextual_cert_base_path'",
",",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'ca.contextual_cert_base_pa... | 27.409091 | 0.001603 |
def u8(self, name, value=None, align=None):
"""Add an unsigned 1 byte integer field to template.
This is an convenience method that simply calls `Uint` keyword with predefined length."""
self.uint(1, name, value, align) | [
"def",
"u8",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"align",
"=",
"None",
")",
":",
"self",
".",
"uint",
"(",
"1",
",",
"name",
",",
"value",
",",
"align",
")"
] | 48 | 0.012295 |
async def create_with_details(source_id: str, invite_details: str):
"""
Create a connection object with a provided invite, represents a single endpoint and can be used for sending and receiving
credentials and proofs
Invite details are provided by the entity offering a connection and ge... | [
"async",
"def",
"create_with_details",
"(",
"source_id",
":",
"str",
",",
"invite_details",
":",
"str",
")",
":",
"constructor_params",
"=",
"(",
"source_id",
",",
")",
"c_source_id",
"=",
"c_char_p",
"(",
"source_id",
".",
"encode",
"(",
"'utf-8'",
")",
")"... | 49.954545 | 0.008036 |
def get_module_data_path(modname, relpath=None, attr_name='DATAPATH'):
"""Return module *modname* data path
Note: relpath is ignored if module has an attribute named *attr_name*
Handles py2exe/cx_Freeze distributions"""
datapath = getattr(sys.modules[modname], attr_name, '')
if datapath:
... | [
"def",
"get_module_data_path",
"(",
"modname",
",",
"relpath",
"=",
"None",
",",
"attr_name",
"=",
"'DATAPATH'",
")",
":",
"datapath",
"=",
"getattr",
"(",
"sys",
".",
"modules",
"[",
"modname",
"]",
",",
"attr_name",
",",
"''",
")",
"if",
"datapath",
":... | 45.842105 | 0.00225 |
def writeAMF3(self, data):
"""
Writes an element in L{AMF3<pyamf.amf3>} format.
"""
self.writeType(TYPE_AMF3)
self.context.getAMF3Encoder(self).writeElement(data) | [
"def",
"writeAMF3",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"writeType",
"(",
"TYPE_AMF3",
")",
"self",
".",
"context",
".",
"getAMF3Encoder",
"(",
"self",
")",
".",
"writeElement",
"(",
"data",
")"
] | 28.142857 | 0.009852 |
def get_fields(node, fields_tag="field_list"):
"""Get the field names and their values from a node.
:sig: (Document, str) -> Dict[str, str]
:param node: Node to get the fields from.
:param fields_tag: Tag of child node that contains the fields.
:return: Names and values of fields.
"""
field... | [
"def",
"get_fields",
"(",
"node",
",",
"fields_tag",
"=",
"\"field_list\"",
")",
":",
"fields_nodes",
"=",
"[",
"c",
"for",
"c",
"in",
"node",
".",
"children",
"if",
"c",
".",
"tagname",
"==",
"fields_tag",
"]",
"if",
"len",
"(",
"fields_nodes",
")",
"... | 38.789474 | 0.001325 |
def mean_target(df, feature_name, target_name, C=None):
"""Mean target.
Original idea: Stanislav Semenov
Parameters
----------
C : float, default None
Regularization coefficient. The higher, the more conservative result.
The optimal value lies between 10 and 50 depending on the data... | [
"def",
"mean_target",
"(",
"df",
",",
"feature_name",
",",
"target_name",
",",
"C",
"=",
"None",
")",
":",
"def",
"group_mean",
"(",
"group",
")",
":",
"group_size",
"=",
"float",
"(",
"group",
".",
"shape",
"[",
"0",
"]",
")",
"if",
"C",
"is",
"No... | 28.888889 | 0.002481 |
def cpu_times(per_cpu=False):
'''
Return the percent of time the CPU spends in each state,
e.g. user, system, idle, nice, iowait, irq, softirq.
per_cpu
if True return an array of percents for each CPU, otherwise aggregate
all percents into one number
CLI Example:
.. code-block... | [
"def",
"cpu_times",
"(",
"per_cpu",
"=",
"False",
")",
":",
"if",
"per_cpu",
":",
"result",
"=",
"[",
"dict",
"(",
"times",
".",
"_asdict",
"(",
")",
")",
"for",
"times",
"in",
"psutil",
".",
"cpu_times",
"(",
"True",
")",
"]",
"else",
":",
"result... | 26.35 | 0.001832 |
def games(years, months=None, days=None, home=None, away=None):
"""Return a list of lists of games for multiple days.
If home and away are the same team, it will return all games for that team.
"""
# put in data if months and days are not specified
if months is None:
months = list(range(1, ... | [
"def",
"games",
"(",
"years",
",",
"months",
"=",
"None",
",",
"days",
"=",
"None",
",",
"home",
"=",
"None",
",",
"away",
"=",
"None",
")",
":",
"# put in data if months and days are not specified",
"if",
"months",
"is",
"None",
":",
"months",
"=",
"list"... | 35.766667 | 0.000907 |
def truncate(hmac_result, length=6):
""" Perform the truncating. """
assert(len(hmac_result) == 20)
offset = ord(hmac_result[19]) & 0xf
bin_code = (ord(hmac_result[offset]) & 0x7f) << 24 \
| (ord(hmac_result[offset+1]) & 0xff) << 16 \
| (ord(hmac_result[offset+2]) & 0xff) << 8 \
... | [
"def",
"truncate",
"(",
"hmac_result",
",",
"length",
"=",
"6",
")",
":",
"assert",
"(",
"len",
"(",
"hmac_result",
")",
"==",
"20",
")",
"offset",
"=",
"ord",
"(",
"hmac_result",
"[",
"19",
"]",
")",
"&",
"0xf",
"bin_code",
"=",
"(",
"ord",
"(",
... | 43.333333 | 0.01005 |
def cookie_attr_value_check(attr_name, attr_value):
""" Check cookie attribute value for validity. Return True if value is valid
:param attr_name: attribute name to check
:param attr_value: attribute value to check
:return: bool
"""
attr_value.encode('us-ascii')
return WHTTPCookie.cookie_attr_value_compl... | [
"def",
"cookie_attr_value_check",
"(",
"attr_name",
",",
"attr_value",
")",
":",
"attr_value",
".",
"encode",
"(",
"'us-ascii'",
")",
"return",
"WHTTPCookie",
".",
"cookie_attr_value_compliance",
"[",
"attr_name",
"]",
".",
"match",
"(",
"attr_value",
")",
"is",
... | 39.777778 | 0.027322 |
def iter_orgs(username, number=-1, etag=None):
"""List the organizations associated with ``username``.
:param str username: (required), login of the user
:param int number: (optional), number of orgs to return. Default: -1,
return all of the issues
:param str etag: (optional), ETag from a previ... | [
"def",
"iter_orgs",
"(",
"username",
",",
"number",
"=",
"-",
"1",
",",
"etag",
"=",
"None",
")",
":",
"return",
"gh",
".",
"iter_orgs",
"(",
"username",
",",
"number",
",",
"etag",
")",
"if",
"username",
"else",
"[",
"]"
] | 39.230769 | 0.001916 |
def max_pv_count(self):
"""
Returns the maximum allowed physical volume count.
"""
self.open()
count = lvm_vg_get_max_pv(self.handle)
self.close()
return count | [
"def",
"max_pv_count",
"(",
"self",
")",
":",
"self",
".",
"open",
"(",
")",
"count",
"=",
"lvm_vg_get_max_pv",
"(",
"self",
".",
"handle",
")",
"self",
".",
"close",
"(",
")",
"return",
"count"
] | 26 | 0.009302 |
def get_extended_metadata_text(self, item_id, metadata_type):
"""Get extended metadata text for a media item.
Args:
item_id (str): The item for which metadata is required
metadata_type (str): The type of text to return, eg
``'ARTIST_BIO'``, or ``'ALBUM_NOTES'``. Call... | [
"def",
"get_extended_metadata_text",
"(",
"self",
",",
"item_id",
",",
"metadata_type",
")",
":",
"response",
"=",
"self",
".",
"soap_client",
".",
"call",
"(",
"'getExtendedMetadataText'",
",",
"[",
"(",
"'id'",
",",
"item_id",
")",
",",
"(",
"'type'",
",",... | 41.714286 | 0.002232 |
def fit_trace_polynomial(trace, deg, axis=0):
'''
Fit a trace information table to a polynomial.
Parameters
----------
trace
A 2D array, 2 columns and n rows
deg : int
Degree of polynomial
axis : {0, 1}
Spatial axis of the array (0 is Y, 1 is X).
'''
... | [
"def",
"fit_trace_polynomial",
"(",
"trace",
",",
"deg",
",",
"axis",
"=",
"0",
")",
":",
"dispaxis",
"=",
"axis_to_dispaxis",
"(",
"axis",
")",
"# FIT to a polynomial",
"pfit",
"=",
"numpy",
".",
"polyfit",
"(",
"trace",
"[",
":",
",",
"0",
"]",
",",
... | 24.285714 | 0.011321 |
def load_model(model_cls_path, model_cls_name, model_load_args):
"""Get an instance of the described model.
Args:
model_cls_path: Path to the module in which the model class
is defined.
model_cls_name: Name of the model class.
model_load_args: Dictionary of args to pass to t... | [
"def",
"load_model",
"(",
"model_cls_path",
",",
"model_cls_name",
",",
"model_load_args",
")",
":",
"spec",
"=",
"importlib",
".",
"util",
".",
"spec_from_file_location",
"(",
"'active_model'",
",",
"model_cls_path",
")",
"model_module",
"=",
"importlib",
".",
"u... | 39.32 | 0.000993 |
async def _notify_update(self, name, change_type, change_info=None, directed_client=None):
"""Notify updates on a service to anyone who cares."""
for monitor in self._monitors:
try:
result = monitor(name, change_type, change_info, directed_client=directed_client)
... | [
"async",
"def",
"_notify_update",
"(",
"self",
",",
"name",
",",
"change_type",
",",
"change_info",
"=",
"None",
",",
"directed_client",
"=",
"None",
")",
":",
"for",
"monitor",
"in",
"self",
".",
"_monitors",
":",
"try",
":",
"result",
"=",
"monitor",
"... | 54.272727 | 0.009885 |
def to_dict(self):
"""
Encode the name, the status of all checks, and the current overall status.
"""
if not isinstance(self.graph.loader, PartitioningLoader):
return dict(msg="Config sharing disabled for non-partioned loader")
if not hasattr(self.graph.loader, "sec... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"graph",
".",
"loader",
",",
"PartitioningLoader",
")",
":",
"return",
"dict",
"(",
"msg",
"=",
"\"Config sharing disabled for non-partioned loader\"",
")",
"if",
"not",
"has... | 36.888889 | 0.008811 |
def get_link(self, rel):
"""
Return link for specified resource
"""
if rel in self.links:
return self.links[rel]
raise ResourceNotFound('Resource requested: %r is not available '
'on this element.' % rel) | [
"def",
"get_link",
"(",
"self",
",",
"rel",
")",
":",
"if",
"rel",
"in",
"self",
".",
"links",
":",
"return",
"self",
".",
"links",
"[",
"rel",
"]",
"raise",
"ResourceNotFound",
"(",
"'Resource requested: %r is not available '",
"'on this element.'",
"%",
"rel... | 32.625 | 0.011194 |
def parse_sargasso_logs(self, f):
""" Parse the sargasso log file. """
species_name = list()
items = list()
header = list()
is_first_line = True
for l in f['f'].splitlines():
s = l.split(",")
# Check that this actually is a Sargasso file
... | [
"def",
"parse_sargasso_logs",
"(",
"self",
",",
"f",
")",
":",
"species_name",
"=",
"list",
"(",
")",
"items",
"=",
"list",
"(",
")",
"header",
"=",
"list",
"(",
")",
"is_first_line",
"=",
"True",
"for",
"l",
"in",
"f",
"[",
"'f'",
"]",
".",
"split... | 39.253731 | 0.008531 |
def find_coord(targ_length,xyz,rcum,theta,phi):
"""
Find (x,y,z) ending coordinate of segment path along section
path.
Args:
targ_length = scalar specifying length of segment path, starting
from the begining of the section path
xyz = coordinates specifying the sect... | [
"def",
"find_coord",
"(",
"targ_length",
",",
"xyz",
",",
"rcum",
",",
"theta",
",",
"phi",
")",
":",
"# [1] Find spherical coordinates for the line segment containing",
"# the endpoint.",
"# [2] Find endpoint in spherical coords and convert to cartesian",
"i",
"=",... | 41.045455 | 0.015152 |
def _mglobals(self):
"""Return current globals -- handles Pdb frames"""
if self._pdb_frame is not None:
return self._pdb_frame.f_globals
else:
return self.shell.user_ns | [
"def",
"_mglobals",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pdb_frame",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_pdb_frame",
".",
"f_globals",
"else",
":",
"return",
"self",
".",
"shell",
".",
"user_ns"
] | 35.166667 | 0.009259 |
def run_cmd(cmd, remote, rootdir='', workdir='', ignore_exit_code=False,
ssh='ssh'):
r'''Run the given cmd in the given workdir, either locally or remotely, and
return the combined stdout/stderr
Parameters:
cmd (list of str or str): Command to execute, as list consisting of the
... | [
"def",
"run_cmd",
"(",
"cmd",
",",
"remote",
",",
"rootdir",
"=",
"''",
",",
"workdir",
"=",
"''",
",",
"ignore_exit_code",
"=",
"False",
",",
"ssh",
"=",
"'ssh'",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"workdir",
... | 43.28866 | 0.001164 |
def _set_sla_data(self, test_id, metrics):
"""
Get sla data from each metric and set it in the _Analysis object specified by test_id to make it available
for retrieval
:return: currently always returns CONSTANTS.OK. Maybe enhanced in future to return additional status
"""
for metric in metrics:
... | [
"def",
"_set_sla_data",
"(",
"self",
",",
"test_id",
",",
"metrics",
")",
":",
"for",
"metric",
"in",
"metrics",
":",
"self",
".",
"_analyses",
"[",
"test_id",
"]",
".",
"sla_data",
"[",
"metric",
".",
"label",
"]",
"=",
"metric",
".",
"sla_map",
"retu... | 45 | 0.009685 |
def cleanupPunct( tweet ):
""" NonEnglishOrTamilOr """
tweet = ''.join( map( lambda c: (unicodedata.name(c).split()[0] in [u'TAMIL',u'LATIN']) and c or u' ', tweet) )
return tweet | [
"def",
"cleanupPunct",
"(",
"tweet",
")",
":",
"tweet",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"lambda",
"c",
":",
"(",
"unicodedata",
".",
"name",
"(",
"c",
")",
".",
"split",
"(",
")",
"[",
"0",
"]",
"in",
"[",
"u'TAMIL'",
",",
"u'LATIN'",
... | 50 | 0.044335 |
def locked_execute(self, sql, parameters = None, cursorClass = DictCursor, quiet = False):
'''We are lock-happy here but SQL performance is not currently an issue daemon-side.'''
return self.execute(sql, parameters, cursorClass, quiet = quiet, locked = True) | [
"def",
"locked_execute",
"(",
"self",
",",
"sql",
",",
"parameters",
"=",
"None",
",",
"cursorClass",
"=",
"DictCursor",
",",
"quiet",
"=",
"False",
")",
":",
"return",
"self",
".",
"execute",
"(",
"sql",
",",
"parameters",
",",
"cursorClass",
",",
"quie... | 87 | 0.068441 |
def reboot(name, call=None):
'''
Reboot a linode.
.. versionadded:: 2015.8.0
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The show_instance ac... | [
"def",
"reboot",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudException",
"(",
"'The show_instance action must be called with -a or --action.'",
")",
"node_id",
"=",
"get_linode_id_from_name",
"(",
"name",
... | 21.866667 | 0.00146 |
def update_gradients_full(self, dL_dK, X, X2=None):
"""derivative of the covariance matrix with respect to the parameters."""
X,slices = X[:,:-1],index_to_slices(X[:,-1])
if X2 is None:
X2,slices2 = X,slices
else:
X2,slices2 = X2[:,:-1],index_to_slices(X2[:,-1])
... | [
"def",
"update_gradients_full",
"(",
"self",
",",
"dL_dK",
",",
"X",
",",
"X2",
"=",
"None",
")",
":",
"X",
",",
"slices",
"=",
"X",
"[",
":",
",",
":",
"-",
"1",
"]",
",",
"index_to_slices",
"(",
"X",
"[",
":",
",",
"-",
"1",
"]",
")",
"if",... | 62.108434 | 0.034558 |
def vradErrorSkyAvg(vmag, spt):
"""
Calculate radial velocity error from V and the spectral type. The value of the error is an average over
the sky.
Parameters
----------
vmag - Value of V-band magnitude.
spt - String representing the spectral type of the star.
Returns
-------
The radial veloci... | [
"def",
"vradErrorSkyAvg",
"(",
"vmag",
",",
"spt",
")",
":",
"return",
"_vradCalibrationFloor",
"+",
"_vradErrorBCoeff",
"[",
"spt",
"]",
"*",
"exp",
"(",
"_vradErrorACoeff",
"[",
"spt",
"]",
"*",
"(",
"vmag",
"-",
"_vradMagnitudeZeroPoint",
")",
")"
] | 25.882353 | 0.010965 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.