text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def format(self, record):
"""tweaked from source of base"""
try:
record.message = record.getMessage()
except TypeError:
# if error during msg = msg % self.args
if record.args:
if isinstance(record.args, collections.Mapping):
... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"record",
".",
"message",
"=",
"record",
".",
"getMessage",
"(",
")",
"except",
"TypeError",
":",
"# if error during msg = msg % self.args",
"if",
"record",
".",
"args",
":",
"if",
"isinstanc... | 38.5 | 18.466667 |
def abort(self):
"""Abort the processing_block."""
LOG.debug('Aborting PB %s', self._id)
self.set_status('aborted')
pb_type = DB.get_hash_value(self.key, 'type')
key = '{}:active'.format(self._type)
DB.remove_from_list(key, self._id)
key = '{}:active:{}'.format(se... | [
"def",
"abort",
"(",
"self",
")",
":",
"LOG",
".",
"debug",
"(",
"'Aborting PB %s'",
",",
"self",
".",
"_id",
")",
"self",
".",
"set_status",
"(",
"'aborted'",
")",
"pb_type",
"=",
"DB",
".",
"get_hash_value",
"(",
"self",
".",
"key",
",",
"'type'",
... | 41.642857 | 7.571429 |
def _rfc3339_to_datetime(dt_str):
"""Convert a microsecond-precision timestamp to a native datetime.
:type dt_str: str
:param dt_str: The string to convert.
:rtype: :class:`datetime.datetime`
:returns: The datetime object created from the string.
"""
return datetime.datetime.strptime(dt_st... | [
"def",
"_rfc3339_to_datetime",
"(",
"dt_str",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"dt_str",
",",
"_RFC3339_MICROS",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"UTC",
")"
] | 35 | 16.9 |
def execDetails(self, reqId, contract, execution):
"""execDetails(EWrapper self, int reqId, Contract contract, Execution execution)"""
return _swigibpy.EWrapper_execDetails(self, reqId, contract, execution) | [
"def",
"execDetails",
"(",
"self",
",",
"reqId",
",",
"contract",
",",
"execution",
")",
":",
"return",
"_swigibpy",
".",
"EWrapper_execDetails",
"(",
"self",
",",
"reqId",
",",
"contract",
",",
"execution",
")"
] | 73.333333 | 16.333333 |
def get_article_detail(text, del_qqmusic=True, del_voice=True):
"""根据微信文章的临时链接获取明细
1. 获取文本中所有的图片链接列表
2. 获取微信文章的html内容页面(去除标题等信息)
Parameters
----------
text : str or unicode
一篇微信文章的文本
del_qqmusic: bool
删除文章中的qq音乐
del_voice: bool
... | [
"def",
"get_article_detail",
"(",
"text",
",",
"del_qqmusic",
"=",
"True",
",",
"del_voice",
"=",
"True",
")",
":",
"# 1. 获取微信文本content",
"html_obj",
"=",
"BeautifulSoup",
"(",
"text",
",",
"\"lxml\"",
")",
"content_text",
"=",
"html_obj",
".",
"find",
"(",
... | 31.02381 | 18.845238 |
def list_fonts():
"""List system fonts
Returns
-------
fonts : list of str
List of system fonts.
"""
vals = _list_fonts()
for font in _vispy_fonts:
vals += [font] if font not in vals else []
vals = sorted(vals, key=lambda s: s.lower())
return vals | [
"def",
"list_fonts",
"(",
")",
":",
"vals",
"=",
"_list_fonts",
"(",
")",
"for",
"font",
"in",
"_vispy_fonts",
":",
"vals",
"+=",
"[",
"font",
"]",
"if",
"font",
"not",
"in",
"vals",
"else",
"[",
"]",
"vals",
"=",
"sorted",
"(",
"vals",
",",
"key",... | 22.153846 | 16.846154 |
def runProcess(cmd, *args):
"""Run `cmd` (which is searched for in the executable path) with `args` and
return the exit status.
In general (unless you know what you're doing) use::
runProcess('program', filename)
rather than::
os.system('program %s' % filename)
because the latter will... | [
"def",
"runProcess",
"(",
"cmd",
",",
"*",
"args",
")",
":",
"from",
"os",
"import",
"spawnvp",
",",
"P_WAIT",
"return",
"spawnvp",
"(",
"P_WAIT",
",",
"cmd",
",",
"(",
"cmd",
",",
")",
"+",
"args",
")"
] | 28.315789 | 20.105263 |
def render_chart_data(data):
""" Return a dictionary list formatted as a HTML table.
Args:
data: data in the form consumed by Google Charts.
"""
builder = HtmlBuilder()
builder._render_objects(data, datatype='chartdata')
return builder._to_html() | [
"def",
"render_chart_data",
"(",
"data",
")",
":",
"builder",
"=",
"HtmlBuilder",
"(",
")",
"builder",
".",
"_render_objects",
"(",
"data",
",",
"datatype",
"=",
"'chartdata'",
")",
"return",
"builder",
".",
"_to_html",
"(",
")"
] | 29.888889 | 15.222222 |
def set_size(self, pt=None, px=None):
"""
Set the size of the font, in px or pt.
The px method is a bit inacurate, there can be one or two px less, and max 4 for big numbers (like 503)
but the size is never over-estimated. It makes almost the good value.
"""
assert (pt,... | [
"def",
"set_size",
"(",
"self",
",",
"pt",
"=",
"None",
",",
"px",
"=",
"None",
")",
":",
"assert",
"(",
"pt",
",",
"px",
")",
"!=",
"(",
"None",
",",
"None",
")",
"if",
"pt",
"is",
"not",
"None",
":",
"self",
".",
"__init__",
"(",
"pt",
",",... | 34 | 21.714286 |
def __view_add_actions(self):
"""
Sets the View actions.
"""
self.__view.addAction(self.__container.engine.actions_manager.register_action(
"Actions|Umbra|Components|factory.script_editor|Search In Files|Replace All",
slot=self.__view_replace_all_action__triggere... | [
"def",
"__view_add_actions",
"(",
"self",
")",
":",
"self",
".",
"__view",
".",
"addAction",
"(",
"self",
".",
"__container",
".",
"engine",
".",
"actions_manager",
".",
"register_action",
"(",
"\"Actions|Umbra|Components|factory.script_editor|Search In Files|Replace All\... | 58.3 | 27.3 |
def locales(self):
"""
Provides access to locale management methods.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/locales
:return: :class:`EnvironmentLocalesProxy <contentful_management.environment_locales_proxy.EnvironmentLoca... | [
"def",
"locales",
"(",
"self",
")",
":",
"return",
"EnvironmentLocalesProxy",
"(",
"self",
".",
"_client",
",",
"self",
".",
"space",
".",
"id",
",",
"self",
".",
"id",
")"
] | 41.1875 | 35.8125 |
def _get_cmd(cmd):
"""Retrieve required commands for running THetA with our local bcbio python.
"""
check_cmd = "RunTHetA.py"
try:
local_cmd = subprocess.check_output(["which", check_cmd]).strip()
except subprocess.CalledProcessError:
return None
return [sys.executable, "%s/%s" %... | [
"def",
"_get_cmd",
"(",
"cmd",
")",
":",
"check_cmd",
"=",
"\"RunTHetA.py\"",
"try",
":",
"local_cmd",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"which\"",
",",
"check_cmd",
"]",
")",
".",
"strip",
"(",
")",
"except",
"subprocess",
".",
"CalledPr... | 40.555556 | 18.888889 |
def limit_order(price, persistence_type=None, size=None, time_in_force=None, min_fill_size=None, bet_target_type=None,
bet_target_size=None):
"""
Create a limit order to send to exchange.
:param float size: amount in account currency to be sent.
:param float price: price at which the ord... | [
"def",
"limit_order",
"(",
"price",
",",
"persistence_type",
"=",
"None",
",",
"size",
"=",
"None",
",",
"time_in_force",
"=",
"None",
",",
"min_fill_size",
"=",
"None",
",",
"bet_target_type",
"=",
"None",
",",
"bet_target_size",
"=",
"None",
")",
":",
"a... | 50.904762 | 29 |
def fq_merge(R1, R2):
"""
merge separate fastq files
"""
c = itertools.cycle([1, 2, 3, 4])
for r1, r2 in zip(R1, R2):
n = next(c)
if n == 1:
pair = [[], []]
pair[0].append(r1.strip())
pair[1].append(r2.strip())
if n == 4:
yield pair | [
"def",
"fq_merge",
"(",
"R1",
",",
"R2",
")",
":",
"c",
"=",
"itertools",
".",
"cycle",
"(",
"[",
"1",
",",
"2",
",",
"3",
",",
"4",
"]",
")",
"for",
"r1",
",",
"r2",
"in",
"zip",
"(",
"R1",
",",
"R2",
")",
":",
"n",
"=",
"next",
"(",
"... | 23.384615 | 11.538462 |
def update_badge_users_count(self):
"""
Denormalizes ``Badge.users.count()`` into ``Bagdes.users_count`` field.
"""
logger.debug('→ Badge %s: syncing users count...', self.slug)
badge, updated = self.badge, False
if not badge:
logger.debug(
'... | [
"def",
"update_badge_users_count",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'→ Badge %s: syncing users count...', ",
"s",
"lf.s",
"l",
"ug)",
"",
"badge",
",",
"updated",
"=",
"self",
".",
"badge",
",",
"False",
"if",
"not",
"badge",
":",
"logger... | 32.484848 | 19.212121 |
def _initialize(self):
"""Sends the initialization packet to the roaster."""
self._header.value = b'\xAA\x55'
self._current_state.value = b'\x00\x00'
s = self._generate_packet()
self._ser.write(s)
self._header.value = b'\xAA\xAA'
self._current_state.value = b'\x02... | [
"def",
"_initialize",
"(",
"self",
")",
":",
"self",
".",
"_header",
".",
"value",
"=",
"b'\\xAA\\x55'",
"self",
".",
"_current_state",
".",
"value",
"=",
"b'\\x00\\x00'",
"s",
"=",
"self",
".",
"_generate_packet",
"(",
")",
"self",
".",
"_ser",
".",
"wr... | 36.1 | 9.4 |
async def open_wallet_search(wallet_handle: int,
type_: str,
query_json: str,
options_json: str) -> int:
"""
Search for wallet records
:param wallet_handle: wallet handler (created by open_wallet).
:param type_: allo... | [
"async",
"def",
"open_wallet_search",
"(",
"wallet_handle",
":",
"int",
",",
"type_",
":",
"str",
",",
"query_json",
":",
"str",
",",
"options_json",
":",
"str",
")",
"->",
"int",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"lo... | 41.145455 | 22.054545 |
def batch_update_reimburse(self, openid, reimburse_status, invoice_list):
"""
报销方批量更新发票信息
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1496561749_f7T6D
:param openid: 用户的 Open ID
:param reimburse_status: 发票报销状态
:param invoice_list: 发票列表
:type invoice_list: li... | [
"def",
"batch_update_reimburse",
"(",
"self",
",",
"openid",
",",
"reimburse_status",
",",
"invoice_list",
")",
":",
"return",
"self",
".",
"_post",
"(",
"'reimburse/updatestatusbatch'",
",",
"data",
"=",
"{",
"'openid'",
":",
"openid",
",",
"'reimburse_status'",
... | 30 | 14.526316 |
def move(src, dest, user=None):
"""
Move or rename src to dest.
"""
src_host, src_port, src_path = path.split(src, user)
dest_host, dest_port, dest_path = path.split(dest, user)
src_fs = hdfs(src_host, src_port, user)
dest_fs = hdfs(dest_host, dest_port, user)
try:
retval = src_f... | [
"def",
"move",
"(",
"src",
",",
"dest",
",",
"user",
"=",
"None",
")",
":",
"src_host",
",",
"src_port",
",",
"src_path",
"=",
"path",
".",
"split",
"(",
"src",
",",
"user",
")",
"dest_host",
",",
"dest_port",
",",
"dest_path",
"=",
"path",
".",
"s... | 30.357143 | 13.928571 |
def find_postaggs_for(postagg_names, metrics_dict):
"""Return a list of metrics that are post aggregations"""
postagg_metrics = [
metrics_dict[name] for name in postagg_names
if metrics_dict[name].metric_type == POST_AGG_TYPE
]
# Remove post aggregations that were... | [
"def",
"find_postaggs_for",
"(",
"postagg_names",
",",
"metrics_dict",
")",
":",
"postagg_metrics",
"=",
"[",
"metrics_dict",
"[",
"name",
"]",
"for",
"name",
"in",
"postagg_names",
"if",
"metrics_dict",
"[",
"name",
"]",
".",
"metric_type",
"==",
"POST_AGG_TYPE... | 44.2 | 12.7 |
def auto_reuse_variable_scope(func):
"""
A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.co... | [
"def",
"auto_reuse_variable_scope",
"(",
"func",
")",
":",
"used_scope",
"=",
"set",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"scope",
"=",
"tf",
".",
"get_vari... | 33.975 | 18.525 |
def normalize_unicode(text):
"""
Normalize any unicode characters to ascii equivalent
https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize
"""
if isinstance(text, six.text_type):
return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf8')
else:... | [
"def",
"normalize_unicode",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
":",
"return",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"text",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
... | 36.888889 | 18.666667 |
def add(self, data_bytes):
'''Feed ASCII string or bytes to the signature function'''
try:
if isinstance(data_bytes, basestring): # Python 2.7 compatibility
data_bytes = map(ord, data_bytes)
except NameError:
if isinstance(data_bytes, str): # This branch... | [
"def",
"add",
"(",
"self",
",",
"data_bytes",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"data_bytes",
",",
"basestring",
")",
":",
"# Python 2.7 compatibility",
"data_bytes",
"=",
"map",
"(",
"ord",
",",
"data_bytes",
")",
"except",
"NameError",
":",
... | 42.6875 | 20.5625 |
def save_params(
self, f=None, f_params=None, f_optimizer=None, f_history=None):
"""Saves the module's parameters, history, and optimizer,
not the whole object.
To save the whole object, use pickle.
``f_params`` and ``f_optimizer`` uses PyTorchs'
:func:`~torch.save`... | [
"def",
"save_params",
"(",
"self",
",",
"f",
"=",
"None",
",",
"f_params",
"=",
"None",
",",
"f_optimizer",
"=",
"None",
",",
"f_history",
"=",
"None",
")",
":",
"# TODO: Remove warning in a future release",
"if",
"f",
"is",
"not",
"None",
":",
"warnings",
... | 39.203125 | 21.359375 |
def excepthook(self, etype, evalue, tb):
"""this is sys.excepthook after init_crashhandler
set self.verbose_crash=True to use our full crashhandler, instead of
a regular traceback with a short message (crash_handler_lite)
"""
if self.verbose_crash:
r... | [
"def",
"excepthook",
"(",
"self",
",",
"etype",
",",
"evalue",
",",
"tb",
")",
":",
"if",
"self",
".",
"verbose_crash",
":",
"return",
"self",
".",
"crash_handler",
"(",
"etype",
",",
"evalue",
",",
"tb",
")",
"else",
":",
"return",
"crashhandler",
"."... | 39.727273 | 19.181818 |
def _ensure_decoded(s):
""" if we have bytes, decode them to unicode """
if isinstance(s, (np.bytes_, bytes)):
s = s.decode(pd.get_option('display.encoding'))
return s | [
"def",
"_ensure_decoded",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"(",
"np",
".",
"bytes_",
",",
"bytes",
")",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"pd",
".",
"get_option",
"(",
"'display.encoding'",
")",
")",
"return",
"s"
] | 36.6 | 12.2 |
def makescacoldesc(columnname, value,
datamanagertype='',
datamanagergroup='',
options=0, maxlen=0, comment='',
valuetype='', keywords={}):
"""Create description of a scalar column.
A description for a scalar column can be created from... | [
"def",
"makescacoldesc",
"(",
"columnname",
",",
"value",
",",
"datamanagertype",
"=",
"''",
",",
"datamanagergroup",
"=",
"''",
",",
"options",
"=",
"0",
",",
"maxlen",
"=",
"0",
",",
"comment",
"=",
"''",
",",
"valuetype",
"=",
"''",
",",
"keywords",
... | 38.628571 | 20.771429 |
def run_workload(database, keys, parameters):
"""Runs workload against the database."""
total_weight = 0.0
weights = []
operations = []
latencies_ms = {}
for operation in OPERATIONS:
weight = float(parameters[operation])
if weight <= 0.0:
continue
total_weight... | [
"def",
"run_workload",
"(",
"database",
",",
"keys",
",",
"parameters",
")",
":",
"total_weight",
"=",
"0.0",
"weights",
"=",
"[",
"]",
"operations",
"=",
"[",
"]",
"latencies_ms",
"=",
"{",
"}",
"for",
"operation",
"in",
"OPERATIONS",
":",
"weight",
"="... | 31.942857 | 15.857143 |
def chalresp(ctx, slot, key, totp, touch, force, generate):
"""
Program a challenge-response credential.
If KEY is not given, an interactive prompt will ask for it.
"""
controller = ctx.obj['controller']
if key:
if generate:
ctx.fail('Invalid options: --generate conflicts w... | [
"def",
"chalresp",
"(",
"ctx",
",",
"slot",
",",
"key",
",",
"totp",
",",
"touch",
",",
"force",
",",
"generate",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"if",
"key",
":",
"if",
"generate",
":",
"ctx",
".",
"fail",... | 35.511628 | 19.093023 |
def get_semester_start_end(year, season):
"""
Returns a guess of the start and end dates for given semester.
"""
if season == Semester.SPRING:
start_month, start_day = 1, 20
end_month, end_day = 5, 17
elif season == Semester.SUMMER:
start_month, start_day = 5, 25
end_... | [
"def",
"get_semester_start_end",
"(",
"year",
",",
"season",
")",
":",
"if",
"season",
"==",
"Semester",
".",
"SPRING",
":",
"start_month",
",",
"start_day",
"=",
"1",
",",
"20",
"end_month",
",",
"end_day",
"=",
"5",
",",
"17",
"elif",
"season",
"==",
... | 32.8 | 11.333333 |
def FindClonedClients(token=None):
"""A script to find multiple machines reporting the same client_id.
This script looks at the hardware serial numbers that a client reported in
over time (they get collected with each regular interrogate). We have seen
that sometimes those serial numbers change - for example w... | [
"def",
"FindClonedClients",
"(",
"token",
"=",
"None",
")",
":",
"index",
"=",
"client_index",
".",
"CreateClientIndex",
"(",
"token",
"=",
"token",
")",
"clients",
"=",
"index",
".",
"LookupClients",
"(",
"[",
"\".\"",
"]",
")",
"hw_infos",
"=",
"_GetHWIn... | 34.236111 | 24.152778 |
def walk(self, head=None):
"""Do a breadth-first walk of the graph, yielding on each node,
starting at `head`."""
head = head or self._root_node
queue = []
queue.insert(0, head)
while queue:
node = queue.pop()
yield node.num, node.previous, node... | [
"def",
"walk",
"(",
"self",
",",
"head",
"=",
"None",
")",
":",
"head",
"=",
"head",
"or",
"self",
".",
"_root_node",
"queue",
"=",
"[",
"]",
"queue",
".",
"insert",
"(",
"0",
",",
"head",
")",
"while",
"queue",
":",
"node",
"=",
"queue",
".",
... | 28.25 | 16.9375 |
def _encode(msg, head=False, binary=False):
"""Convert a Message to a raw string.
"""
rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format(
msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version)
if not head and msg.data:
if not binary and isinstance(msg.data, s... | [
"def",
"_encode",
"(",
"msg",
",",
"head",
"=",
"False",
",",
"binary",
"=",
"False",
")",
":",
"rawstr",
"=",
"str",
"(",
"_MAGICK",
")",
"+",
"u\"{0:s} {1:s} {2:s} {3:s} {4:s}\"",
".",
"format",
"(",
"msg",
".",
"subject",
",",
"msg",
".",
"type",
",... | 39.333333 | 16.111111 |
def save(self):
"""Write changed .pth file back to disk"""
if not self.dirty:
return
data = '\n'.join(map(self.make_relative, self.paths))
if data:
log.debug("Saving %s", self.filename)
data = (
"import sys; sys.__plen = len(sys.path)\... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"dirty",
":",
"return",
"data",
"=",
"'\\n'",
".",
"join",
"(",
"map",
"(",
"self",
".",
"make_relative",
",",
"self",
".",
"paths",
")",
")",
"if",
"data",
":",
"log",
".",
"debug",... | 32.428571 | 17.428571 |
def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
--------... | [
"def",
"query",
"(",
"self",
",",
"area",
"=",
"None",
",",
"date",
"=",
"None",
",",
"raw",
"=",
"None",
",",
"area_relation",
"=",
"'Intersects'",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"*",
"*",
... | 50.027397 | 28.123288 |
def retrieve_adjacency_matrix(graph, order_nodes=None, weight=False):
"""Retrieve the adjacency matrix from the nx.DiGraph or numpy array."""
if isinstance(graph, np.ndarray):
return graph
elif isinstance(graph, nx.DiGraph):
if order_nodes is None:
order_nodes = graph.nodes()
... | [
"def",
"retrieve_adjacency_matrix",
"(",
"graph",
",",
"order_nodes",
"=",
"None",
",",
"weight",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"graph",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"graph",
"elif",
"isinstance",
"(",
"graph",
",",
"... | 47.846154 | 22.076923 |
def write_abstract_dag(self):
"""
Write all the nodes in the workflow to the DAX file.
"""
# keep track of if we are using stampede at TACC
using_stampede = False
if not self.__dax_file_path:
# this workflow is not dax-compatible, so don't write a dax
return
import Pegasus.DAX... | [
"def",
"write_abstract_dag",
"(",
"self",
")",
":",
"# keep track of if we are using stampede at TACC",
"using_stampede",
"=",
"False",
"if",
"not",
"self",
".",
"__dax_file_path",
":",
"# this workflow is not dax-compatible, so don't write a dax",
"return",
"import",
"Pegasus"... | 41.907285 | 23.748344 |
def depth_renderbuffer(self, size, *, samples=0) -> 'Renderbuffer':
'''
:py:class:`Renderbuffer` objects are OpenGL objects that contain images.
They are created and used specifically with :py:class:`Framebuffer` objects.
Args:
size (tuple): The width and hei... | [
"def",
"depth_renderbuffer",
"(",
"self",
",",
"size",
",",
"*",
",",
"samples",
"=",
"0",
")",
"->",
"'Renderbuffer'",
":",
"res",
"=",
"Renderbuffer",
".",
"__new__",
"(",
"Renderbuffer",
")",
"res",
".",
"mglo",
",",
"res",
".",
"_glo",
"=",
"self",... | 33.84 | 25.92 |
def classical(transform, loglikelihood, parameter_names, prior,
start = 0.5, ftol=0.1, disp=0, nsteps=40000,
method='neldermead', **args):
"""
**Classic optimization methods**
:param start: start position vector (before transform)
:param ftol: accuracy required to stop at optimum
:param disp: verbosity
:param... | [
"def",
"classical",
"(",
"transform",
",",
"loglikelihood",
",",
"parameter_names",
",",
"prior",
",",
"start",
"=",
"0.5",
",",
"ftol",
"=",
"0.1",
",",
"disp",
"=",
"0",
",",
"nsteps",
"=",
"40000",
",",
"method",
"=",
"'neldermead'",
",",
"*",
"*",
... | 31.07563 | 20.092437 |
def anim(self, start=0, stop=None, fps=30):
"""
Method to return a matplotlib animation. The start and stop
frames may be specified as well as the fps.
"""
figure = self.state or self.initialize_plot()
anim = animation.FuncAnimation(figure, self.update_frame,
... | [
"def",
"anim",
"(",
"self",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
",",
"fps",
"=",
"30",
")",
":",
"figure",
"=",
"self",
".",
"state",
"or",
"self",
".",
"initialize_plot",
"(",
")",
"anim",
"=",
"animation",
".",
"FuncAnimation",
"(",... | 43.25 | 12.75 |
def principal_inertia_components(self):
"""
Return the principal components of inertia
Ordering corresponds to mesh.principal_inertia_vectors
Returns
----------
components : (3,) float
Principal components of inertia
"""
# both components and v... | [
"def",
"principal_inertia_components",
"(",
"self",
")",
":",
"# both components and vectors from inertia matrix",
"components",
",",
"vectors",
"=",
"inertia",
".",
"principal_axis",
"(",
"self",
".",
"moment_inertia",
")",
"# store vectors in cache for later",
"self",
"."... | 31.352941 | 17.352941 |
def device_set(self, device):
"""Set device used by :class:`MobileClient` instance.
Parameters:
device (dict): A device dict as returned by :meth:`devices`.
"""
if device['id'].startswith('0x'):
self.device_id = device['id'][2:]
elif device['id'].startswith('ios:'):
self.device_id = device['id'].re... | [
"def",
"device_set",
"(",
"self",
",",
"device",
")",
":",
"if",
"device",
"[",
"'id'",
"]",
".",
"startswith",
"(",
"'0x'",
")",
":",
"self",
".",
"device_id",
"=",
"device",
"[",
"'id'",
"]",
"[",
"2",
":",
"]",
"elif",
"device",
"[",
"'id'",
"... | 27.923077 | 15.461538 |
def get_page_numbers(
current_page, num_pages,
extremes=DEFAULT_CALLABLE_EXTREMES,
arounds=DEFAULT_CALLABLE_AROUNDS,
arrows=DEFAULT_CALLABLE_ARROWS):
"""Default callable for page listing.
Produce a Digg-style pagination.
"""
page_range = range(1, num_pages + 1)
pages... | [
"def",
"get_page_numbers",
"(",
"current_page",
",",
"num_pages",
",",
"extremes",
"=",
"DEFAULT_CALLABLE_EXTREMES",
",",
"arounds",
"=",
"DEFAULT_CALLABLE_AROUNDS",
",",
"arrows",
"=",
"DEFAULT_CALLABLE_ARROWS",
")",
":",
"page_range",
"=",
"range",
"(",
"1",
",",
... | 26.618182 | 13.818182 |
def rlogistic(mu, tau, size=None):
"""
Logistic random variates.
"""
u = np.random.random(size)
return mu + np.log(u / (1 - u)) / tau | [
"def",
"rlogistic",
"(",
"mu",
",",
"tau",
",",
"size",
"=",
"None",
")",
":",
"u",
"=",
"np",
".",
"random",
".",
"random",
"(",
"size",
")",
"return",
"mu",
"+",
"np",
".",
"log",
"(",
"u",
"/",
"(",
"1",
"-",
"u",
")",
")",
"/",
"tau"
] | 21.142857 | 9.714286 |
def postpro_boxcox(data, report=None):
"""
Performs box cox transform on everything in data.
If report variable is passed, this is added to the report.
"""
if not report:
report = {}
# Note the min value of all time series will now be at least 1.
mindata = 1 - np.nanmin(data)
da... | [
"def",
"postpro_boxcox",
"(",
"data",
",",
"report",
"=",
"None",
")",
":",
"if",
"not",
"report",
":",
"report",
"=",
"{",
"}",
"# Note the min value of all time series will now be at least 1.",
"mindata",
"=",
"1",
"-",
"np",
".",
"nanmin",
"(",
"data",
")",... | 40.411765 | 20.843137 |
def make_gears_cache_registry(args):
"""
create a new gears registry cache on Ariane Server
:param args: the cache parameters - look to the tests to know more
:return: remote procedure call return - look to the tests to know more
"""
LOGGER.debug("InjectorCachedRegistryFa... | [
"def",
"make_gears_cache_registry",
"(",
"args",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"InjectorCachedRegistryFactoryService.make_gears_cache_registry\"",
")",
"if",
"args",
"is",
"None",
":",
"err_msg",
"=",
"'InjectorCachedRegistryFactoryService.make_gears_cache_registry -... | 51.22449 | 30.897959 |
def set_value(ctx, key, value):
"""Assigns values to config file entries. If the value is omitted,
you will be prompted, with the input hidden if it is sensitive.
\b
$ ddev config set github.user foo
New setting:
[github]
user = "foo"
"""
scrubbing = False
if value is None:
... | [
"def",
"set_value",
"(",
"ctx",
",",
"key",
",",
"value",
")",
":",
"scrubbing",
"=",
"False",
"if",
"value",
"is",
"None",
":",
"scrubbing",
"=",
"key",
"in",
"SECRET_KEYS",
"value",
"=",
"click",
".",
"prompt",
"(",
"'Value for `{}`'",
".",
"format",
... | 28.396226 | 19.283019 |
def utf8(data):
"""Convert a basestring to a valid UTF-8 str."""
if isinstance(data, bytes):
return data.decode("utf-8", "replace").encode("utf-8")
elif isinstance(data, text_type):
return data.encode("utf-8")
else:
raise TypeError("only unicode/bytes types can be converted to U... | [
"def",
"utf8",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"return",
"data",
".",
"decode",
"(",
"\"utf-8\"",
",",
"\"replace\"",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
"elif",
"isinstance",
"(",
"data",
",",
"... | 35.333333 | 19.111111 |
def append_summary_to_module_docstring(module):
"""
Change the ``module.__doc__`` docstring to include a summary table based
on its contents as declared on ``module.__all__``.
"""
pairs = [(name, getattr(module, name)) for name in module.__all__]
kws = dict(key_header="Name", summary_type="module contents")... | [
"def",
"append_summary_to_module_docstring",
"(",
"module",
")",
":",
"pairs",
"=",
"[",
"(",
"name",
",",
"getattr",
"(",
"module",
",",
"name",
")",
")",
"for",
"name",
"in",
"module",
".",
"__all__",
"]",
"kws",
"=",
"dict",
"(",
"key_header",
"=",
... | 48.125 | 16.875 |
def on_zijd_mark(self, event):
"""
Get mouse position on double right click find the interpretation in
range of mouse
position then mark that interpretation bad or good
Parameters
----------
event : the wx Mouseevent for that click
Alters
------
... | [
"def",
"on_zijd_mark",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"array",
"(",
"self",
".",
"CART_rot",
")",
".",
"any",
"(",
")",
":",
"return",
"pos",
"=",
"event",
".",
"GetPosition",
"(",
")",
"width",
",",
"height",
"=",
"self",
".",
... | 36.061224 | 18.591837 |
def _from_dict(cls, _dict):
"""Initialize a Element object from a json dictionary."""
args = {}
if 'location' in _dict:
args['location'] = Location._from_dict(_dict.get('location'))
if 'text' in _dict:
args['text'] = _dict.get('text')
if 'types' in _dict:
... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'location'",
"in",
"_dict",
":",
"args",
"[",
"'location'",
"]",
"=",
"Location",
".",
"_from_dict",
"(",
"_dict",
".",
"get",
"(",
"'location'",
")",
")",
"if",
... | 37.8 | 16.75 |
async def make_response(self, request, response, **response_kwargs):
"""Convert a handler result to web response."""
while iscoroutine(response):
response = await response
if isinstance(response, StreamResponse):
return response
response_kwargs.setdefault('conte... | [
"async",
"def",
"make_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"*",
"*",
"response_kwargs",
")",
":",
"while",
"iscoroutine",
"(",
"response",
")",
":",
"response",
"=",
"await",
"response",
"if",
"isinstance",
"(",
"response",
",",
"S... | 36.818182 | 20.909091 |
def createUser(self, localpart, domain, password=None):
"""
Create a new, blank user account with the given name and domain and, if
specified, with the given password.
@type localpart: C{unicode}
@param localpart: The local portion of the username. ie, the
C{'alice'} in... | [
"def",
"createUser",
"(",
"self",
",",
"localpart",
",",
"domain",
",",
"password",
"=",
"None",
")",
":",
"loginSystem",
"=",
"self",
".",
"browser",
".",
"store",
".",
"parent",
".",
"findUnique",
"(",
"userbase",
".",
"LoginSystem",
")",
"if",
"passwo... | 45.047619 | 21.619048 |
def parse_doc(doc):
"""
Parse docstrings to dict, it should look like:
key: value
"""
if not doc:
return {}
out = {}
for s in doc.split('\n'):
s = s.strip().split(':', maxsplit=1)
if len(s) == 2:
out[s[0]] = s[1]
return out | [
"def",
"parse_doc",
"(",
"doc",
")",
":",
"if",
"not",
"doc",
":",
"return",
"{",
"}",
"out",
"=",
"{",
"}",
"for",
"s",
"in",
"doc",
".",
"split",
"(",
"'\\n'",
")",
":",
"s",
"=",
"s",
".",
"strip",
"(",
")",
".",
"split",
"(",
"':'",
","... | 21.615385 | 15.461538 |
def serverProperties(self):
"""gets the server properties for the site as an object"""
return ServerProperties(url=self._url + "/properties",
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
p... | [
"def",
"serverProperties",
"(",
"self",
")",
":",
"return",
"ServerProperties",
"(",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/properties\"",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
... | 55.571429 | 15.571429 |
def open(self):
"""Open an existing database"""
if self._table_exists():
self.mode = "open"
# get table info
self._get_table_info()
return self
else:
# table not found
raise IOError,"Table %s doesn't exist" %self.na... | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"_table_exists",
"(",
")",
":",
"self",
".",
"mode",
"=",
"\"open\"",
"# get table info\r",
"self",
".",
"_get_table_info",
"(",
")",
"return",
"self",
"else",
":",
"# table not found\r",
"raise",
"I... | 31.3 | 12.9 |
def delete_patch(self, patch_name=None, remove=False, backup=False):
""" Delete specified patch from the series
If remove is True the patch file will also be removed. If remove and
backup are True a copy of the deleted patch file will be made.
"""
if patch_name:
patch... | [
"def",
"delete_patch",
"(",
"self",
",",
"patch_name",
"=",
"None",
",",
"remove",
"=",
"False",
",",
"backup",
"=",
"False",
")",
":",
"if",
"patch_name",
":",
"patch",
"=",
"Patch",
"(",
"patch_name",
")",
"else",
":",
"patch",
"=",
"self",
".",
"d... | 39.923077 | 17.384615 |
def _rmv_deps(self, dependencies, package):
"""Remove dependencies
"""
removes = []
dependencies.append(package)
self._check_if_used(dependencies)
for dep in dependencies:
if dep not in self.skip and GetFromInstalled(dep).name():
ver = GetFromI... | [
"def",
"_rmv_deps",
"(",
"self",
",",
"dependencies",
",",
"package",
")",
":",
"removes",
"=",
"[",
"]",
"dependencies",
".",
"append",
"(",
"package",
")",
"self",
".",
"_check_if_used",
"(",
"dependencies",
")",
"for",
"dep",
"in",
"dependencies",
":",
... | 36.166667 | 8.416667 |
def tag_handler(self, cmd):
"""Process a TagCommand."""
# Keep tags if they indirectly reference something we kept
cmd.from_ = self._find_interesting_from(cmd.from_)
self.keep = cmd.from_ is not None | [
"def",
"tag_handler",
"(",
"self",
",",
"cmd",
")",
":",
"# Keep tags if they indirectly reference something we kept",
"cmd",
".",
"from_",
"=",
"self",
".",
"_find_interesting_from",
"(",
"cmd",
".",
"from_",
")",
"self",
".",
"keep",
"=",
"cmd",
".",
"from_",
... | 45.4 | 11.6 |
def chdir(self, dir, change_os_dir=0):
"""Change the current working directory for lookups.
If change_os_dir is true, we will also change the "real" cwd
to match.
"""
curr=self._cwd
try:
if dir is not None:
self._cwd = dir
if ch... | [
"def",
"chdir",
"(",
"self",
",",
"dir",
",",
"change_os_dir",
"=",
"0",
")",
":",
"curr",
"=",
"self",
".",
"_cwd",
"try",
":",
"if",
"dir",
"is",
"not",
"None",
":",
"self",
".",
"_cwd",
"=",
"dir",
"if",
"change_os_dir",
":",
"os",
".",
"chdir... | 31.285714 | 13.071429 |
def relative_noise_size(self, data, noise):
'''
:data: original data as numpy matrix
:noise: noise matrix as numpy matrix
'''
return np.mean([
sci_dist.cosine(u / la.norm(u), v / la.norm(v))
for u, v in zip(noise, data)
]) | [
"def",
"relative_noise_size",
"(",
"self",
",",
"data",
",",
"noise",
")",
":",
"return",
"np",
".",
"mean",
"(",
"[",
"sci_dist",
".",
"cosine",
"(",
"u",
"/",
"la",
".",
"norm",
"(",
"u",
")",
",",
"v",
"/",
"la",
".",
"norm",
"(",
"v",
")",
... | 31.777778 | 14.888889 |
def __calculate_radius(self, number_neighbors, radius):
"""!
@brief Calculate new connectivity radius.
@param[in] number_neighbors (uint): Average amount of neighbors that should be connected by new radius.
@param[in] radius (double): Current connectivity radius.
... | [
"def",
"__calculate_radius",
"(",
"self",
",",
"number_neighbors",
",",
"radius",
")",
":",
"if",
"(",
"number_neighbors",
">=",
"len",
"(",
"self",
".",
"_osc_loc",
")",
")",
":",
"return",
"radius",
"*",
"self",
".",
"__increase_persent",
"+",
"radius",
... | 38.866667 | 23.2 |
def _serialize(self, uri, node):
"""
Serialize node result as dict
"""
meta = self._decode_meta(node['meta'], is_published=bool(node['is_published']))
return {
'uri': uri.clone(ext=node['plugin'], version=node['version']),
'content': node['content'],
... | [
"def",
"_serialize",
"(",
"self",
",",
"uri",
",",
"node",
")",
":",
"meta",
"=",
"self",
".",
"_decode_meta",
"(",
"node",
"[",
"'meta'",
"]",
",",
"is_published",
"=",
"bool",
"(",
"node",
"[",
"'is_published'",
"]",
")",
")",
"return",
"{",
"'uri'... | 34 | 16.4 |
def sha512_digest(instr):
'''
Generate a sha512 hash of a given string
'''
return salt.utils.stringutils.to_unicode(
hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest()
) | [
"def",
"sha512_digest",
"(",
"instr",
")",
":",
"return",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"hashlib",
".",
"sha512",
"(",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_bytes",
"(",
"instr",
")",
")",
".",
"hexdigest"... | 29.571429 | 22.714286 |
def _get_ref_info_helper(cls, repo, ref_path):
"""Return: (str(sha), str(target_ref_path)) if available, the sha the file at
rela_path points to, or None. target_ref_path is the reference we
point to, or None"""
tokens = None
repodir = _git_dir(repo, ref_path)
try:
... | [
"def",
"_get_ref_info_helper",
"(",
"cls",
",",
"repo",
",",
"ref_path",
")",
":",
"tokens",
"=",
"None",
"repodir",
"=",
"_git_dir",
"(",
"repo",
",",
"ref_path",
")",
"try",
":",
"with",
"open",
"(",
"osp",
".",
"join",
"(",
"repodir",
",",
"ref_path... | 42.864865 | 18.405405 |
def _update_model(self, gammas, count_matrices, maxiter=10000000):
"""
Maximization step: Updates the HMM model given the hidden state assignment and count matrices
Parameters
----------
gamma : [ ndarray(T,N, dtype=float) ]
list of state probabilities for each traje... | [
"def",
"_update_model",
"(",
"self",
",",
"gammas",
",",
"count_matrices",
",",
"maxiter",
"=",
"10000000",
")",
":",
"gamma0_sum",
"=",
"self",
".",
"_init_counts",
"(",
"gammas",
")",
"C",
"=",
"self",
".",
"_transition_counts",
"(",
"count_matrices",
")",... | 41.659574 | 22.382979 |
def random_digit_or_empty(self):
"""
Returns a random digit/number
between 0 and 9 or an empty string.
"""
if self.generator.random.randint(0, 1):
return self.generator.random.randint(0, 9)
else:
return '' | [
"def",
"random_digit_or_empty",
"(",
"self",
")",
":",
"if",
"self",
".",
"generator",
".",
"random",
".",
"randint",
"(",
"0",
",",
"1",
")",
":",
"return",
"self",
".",
"generator",
".",
"random",
".",
"randint",
"(",
"0",
",",
"9",
")",
"else",
... | 29.888889 | 9 |
def dataframe(start_row=0, max_rows=None, use_cache=True):
""" Construct a query output object where the result is a dataframe
Args:
start_row: the row of the table at which to start the export (default 0).
max_rows: an upper limit on the number of rows to export (default None).
use_cache: wh... | [
"def",
"dataframe",
"(",
"start_row",
"=",
"0",
",",
"max_rows",
"=",
"None",
",",
"use_cache",
"=",
"True",
")",
":",
"output",
"=",
"QueryOutput",
"(",
")",
"output",
".",
"_output_type",
"=",
"'dataframe'",
"output",
".",
"_dataframe_start_row",
"=",
"s... | 40.571429 | 17.571429 |
def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None):
"""Search game to determine best action; use alpha-beta pruning.
This version cuts off search and uses an evaluation function."""
player = game.to_move(state)
def max_value(state, alpha, beta, depth):
if cutoff_test(state,... | [
"def",
"alphabeta_search",
"(",
"state",
",",
"game",
",",
"d",
"=",
"4",
",",
"cutoff_test",
"=",
"None",
",",
"eval_fn",
"=",
"None",
")",
":",
"player",
"=",
"game",
".",
"to_move",
"(",
"state",
")",
"def",
"max_value",
"(",
"state",
",",
"alpha"... | 38.052632 | 15.894737 |
def dragEnterEvent(self, event):
"""Reimplement Qt method
Inform Qt about the types of data that the widget accepts"""
source = event.mimeData()
# The second check is necessary on Windows, where source.hasUrls()
# can return True but source.urls() is []
# The third ... | [
"def",
"dragEnterEvent",
"(",
"self",
",",
"event",
")",
":",
"source",
"=",
"event",
".",
"mimeData",
"(",
")",
"# The second check is necessary on Windows, where source.hasUrls()\r",
"# can return True but source.urls() is []\r",
"# The third check is needed since a file could be... | 45 | 14.846154 |
def delete(self, rid, raise_on_error=True):
"""Write cache data to the data store.
Args:
rid (str): The record identifier.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request response.
"... | [
"def",
"delete",
"(",
"self",
",",
"rid",
",",
"raise_on_error",
"=",
"True",
")",
":",
"return",
"self",
".",
"ds",
".",
"delete",
"(",
"rid",
",",
"raise_on_error",
")"
] | 33 | 18.909091 |
def _combine(self, applied, shortcut=False):
"""Recombine the applied objects like the original."""
applied_example, applied = peek_at(applied)
coord, dim, positions = self._infer_concat_args(applied_example)
if shortcut:
combined = self._concat_shortcut(applied, dim, positio... | [
"def",
"_combine",
"(",
"self",
",",
"applied",
",",
"shortcut",
"=",
"False",
")",
":",
"applied_example",
",",
"applied",
"=",
"peek_at",
"(",
"applied",
")",
"coord",
",",
"dim",
",",
"positions",
"=",
"self",
".",
"_infer_concat_args",
"(",
"applied_ex... | 43.47619 | 17.095238 |
def dynamic_exclusion_worker(display, n_threads):
"""This worker allows mutualy exclusive jobs to start safely. The
user provides the information on which jobs exclude the simultaneous
execution of other jobs::
a = task()
b = task()
update_hints(a, {'task': '1', 'exclude': ['2']})
... | [
"def",
"dynamic_exclusion_worker",
"(",
"display",
",",
"n_threads",
")",
":",
"LogQ",
"=",
"Queue",
"(",
")",
"threading",
".",
"Thread",
"(",
"target",
"=",
"patch",
",",
"args",
"=",
"(",
"LogQ",
".",
"source",
",",
"sink_map",
"(",
"display",
")",
... | 31.329545 | 18.329545 |
def resolved_packages(self):
"""Return a list of PackageVariant objects, or None if the resolve did
not complete or was unsuccessful.
"""
if (self.status != SolverStatus.solved):
return None
final_phase = self.phase_stack[-1]
return final_phase._get_solved_va... | [
"def",
"resolved_packages",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"status",
"!=",
"SolverStatus",
".",
"solved",
")",
":",
"return",
"None",
"final_phase",
"=",
"self",
".",
"phase_stack",
"[",
"-",
"1",
"]",
"return",
"final_phase",
".",
"_get_... | 35.555556 | 9.888889 |
def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None):
"""
The main rendering sequence for placeholders.
This will do all the magic for caching, and call :func:`render_items` in the end.
"""
... | [
"def",
"render_placeholder",
"(",
"self",
",",
"placeholder",
",",
"parent_object",
"=",
"None",
",",
"template_name",
"=",
"None",
",",
"cachable",
"=",
"None",
",",
"limit_parent_language",
"=",
"True",
",",
"fallback_language",
"=",
"None",
")",
":",
"place... | 50.9375 | 29.8125 |
def max(self, expr, extra_constraints=(), solver=None, model_callback=None):
"""
Return the maximum value of expr.
:param expr: expression (an AST) to evaluate
:param solver: a solver object, native to the backend, to assist in
the evaluation (for example, a z3.So... | [
"def",
"max",
"(",
"self",
",",
"expr",
",",
"extra_constraints",
"=",
"(",
")",
",",
"solver",
"=",
"None",
",",
"model_callback",
"=",
"None",
")",
":",
"if",
"self",
".",
"_solver_required",
"and",
"solver",
"is",
"None",
":",
"raise",
"BackendError",... | 59.133333 | 33.666667 |
def get_vm_info(self, client):
"""Return vm info."""
out = ''
self._set_init_system(client)
if self.init_system == 'systemd':
try:
out += 'systemd-analyze:\n\n'
out += ipa_utils.execute_ssh_command(
client,
... | [
"def",
"get_vm_info",
"(",
"self",
",",
"client",
")",
":",
"out",
"=",
"''",
"self",
".",
"_set_init_system",
"(",
"client",
")",
"if",
"self",
".",
"init_system",
"==",
"'systemd'",
":",
"try",
":",
"out",
"+=",
"'systemd-analyze:\\n\\n'",
"out",
"+=",
... | 30.142857 | 15.964286 |
async def verify_parent_task_definition(chain, parent_link):
"""Rebuild the decision/action/cron task definition via json-e.
This is Chain of Trust verification version 2, aka cotv2.
Instead of looking at various parts of the parent task's task definition
and making sure they look well-formed, let's re... | [
"async",
"def",
"verify_parent_task_definition",
"(",
"chain",
",",
"parent_link",
")",
":",
"log",
".",
"info",
"(",
"\"Verifying {} {} definition...\"",
".",
"format",
"(",
"parent_link",
".",
"name",
",",
"parent_link",
".",
"task_id",
")",
")",
"decision_link"... | 45.369565 | 26.5 |
def __update(self):
"""Load the IRQ file and update the internal dict."""
self.reset()
if not os.path.exists(self.IRQ_FILE):
# Correct issue #947: IRQ file do not exist on OpenVZ container
return self.stats
try:
with open(self.IRQ_FILE) as irq_proc:
... | [
"def",
"__update",
"(",
"self",
")",
":",
"self",
".",
"reset",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"IRQ_FILE",
")",
":",
"# Correct issue #947: IRQ file do not exist on OpenVZ container",
"return",
"self",
".",
"stats",
... | 39.666667 | 16.060606 |
def _is_null(instance, name):
'''
Determine if an attribute of an *instance* with a specific *name*
is null.
'''
if name in instance.__dict__:
value = instance.__dict__[name]
else:
value = getattr(instance, name)
if value:
return False
elif value is None:
... | [
"def",
"_is_null",
"(",
"instance",
",",
"name",
")",
":",
"if",
"name",
"in",
"instance",
".",
"__dict__",
":",
"value",
"=",
"instance",
".",
"__dict__",
"[",
"name",
"]",
"else",
":",
"value",
"=",
"getattr",
"(",
"instance",
",",
"name",
")",
"if... | 25.264706 | 19.794118 |
def get_all_sources(self):
"""
Returns:
OrderedDict: all source file names in the hierarchy, paired with
the names of their subpages.
"""
if self.__all_sources is None:
self.__all_sources = OrderedDict()
self.walk(self.__add_one)
... | [
"def",
"get_all_sources",
"(",
"self",
")",
":",
"if",
"self",
".",
"__all_sources",
"is",
"None",
":",
"self",
".",
"__all_sources",
"=",
"OrderedDict",
"(",
")",
"self",
".",
"walk",
"(",
"self",
".",
"__add_one",
")",
"return",
"self",
".",
"__all_sou... | 33.8 | 9.6 |
def update_colors(self):
"""Apply any corrections to the current color list
and send the results to the driver output. This function primarily
provided as a wrapper for each driver's implementation of
:py:func:`_compute_packet` and :py:func:`_send_packet`.
"""
start = sel... | [
"def",
"update_colors",
"(",
"self",
")",
":",
"start",
"=",
"self",
".",
"clock",
".",
"time",
"(",
")",
"with",
"self",
".",
"brightness_lock",
":",
"# Swap in a new brightness.",
"brightness",
",",
"self",
".",
"_waiting_brightness",
"=",
"(",
"self",
"."... | 35.409091 | 15.818182 |
def list_upgrades(refresh=False, root=None, **kwargs): # pylint: disable=W0613
'''
List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
upgrades = {}
cmd = ['pacman', '-S', '-p', '-u', '--print-format', '%n %v']
... | [
"def",
"list_upgrades",
"(",
"refresh",
"=",
"False",
",",
"root",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=W0613",
"upgrades",
"=",
"{",
"}",
"cmd",
"=",
"[",
"'pacman'",
",",
"'-S'",
",",
"'-p'",
",",
"'-u'",
",",
"'--print-... | 31.270833 | 22.9375 |
def push_content(self, title, url,
images=None, date=None, expire_date=None,
description=None, location=None, price=None,
tags=None,
author=None, site_name=None,
spider=None, vars=None):
"""
Push a ... | [
"def",
"push_content",
"(",
"self",
",",
"title",
",",
"url",
",",
"images",
"=",
"None",
",",
"date",
"=",
"None",
",",
"expire_date",
"=",
"None",
",",
"description",
"=",
"None",
",",
"location",
"=",
"None",
",",
"price",
"=",
"None",
",",
"tags"... | 37.722222 | 13.018519 |
def http(self, *args, **kwargs):
"""Starts the process of building a new HTTP route linked to this API instance"""
kwargs['api'] = self.api
return http(*args, **kwargs) | [
"def",
"http",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'api'",
"]",
"=",
"self",
".",
"api",
"return",
"http",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 47.25 | 5 |
def loader_cls(self):
"""Loader class used in `JsonRef.replace_refs`."""
cls = self.app.config['JSONSCHEMAS_LOADER_CLS']
if isinstance(cls, six.string_types):
return import_string(cls)
return cls | [
"def",
"loader_cls",
"(",
"self",
")",
":",
"cls",
"=",
"self",
".",
"app",
".",
"config",
"[",
"'JSONSCHEMAS_LOADER_CLS'",
"]",
"if",
"isinstance",
"(",
"cls",
",",
"six",
".",
"string_types",
")",
":",
"return",
"import_string",
"(",
"cls",
")",
"retur... | 39 | 10.666667 |
def _find_egg_info(ireq):
"""Find this package's .egg-info directory.
Due to how sdists are designed, the .egg-info directory cannot be reliably
found without running setup.py to aggregate all configurations. This
function instead uses some heuristics to locate the egg-info directory
that most like... | [
"def",
"_find_egg_info",
"(",
"ireq",
")",
":",
"root",
"=",
"ireq",
".",
"setup_py_dir",
"directory_iterator",
"=",
"_iter_egg_info_directories",
"(",
"root",
",",
"ireq",
".",
"name",
")",
"try",
":",
"top_egg_info",
"=",
"next",
"(",
"directory_iterator",
"... | 36.742857 | 21.885714 |
def is_pid(value):
"""
This function checks whether file path
that is specified at "pid_file" option eixsts,
whether write permission to the file path.
Return the following value:
case1: exists path and write permission
is_pid('/tmp')
'/tmp/hogehoge.pid'
case2: non-exis... | [
"def",
"is_pid",
"(",
"value",
")",
":",
"value",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"value",
")",
"value",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"value",
")",
"value",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"value",
... | 31.341463 | 19.658537 |
def create(
self,
name,
command_to_run,
description="",
environment_variables=None,
required_arguments=None,
required_arguments_default_values=None,
extra_data_to_post=None,
):
"""Create a task type.
Args:
name (str): The n... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"command_to_run",
",",
"description",
"=",
"\"\"",
",",
"environment_variables",
"=",
"None",
",",
"required_arguments",
"=",
"None",
",",
"required_arguments_default_values",
"=",
"None",
",",
"extra_data_to_post",
... | 37.714286 | 19.757143 |
def can_use_cache(self, target: Target) -> bool:
"""Return True if should attempt to load `target` from cache.
Return False if `target` has to be built, regardless of its cache
status (because cache is disabled, or dependencies are dirty).
"""
# if caching is disabled for t... | [
"def",
"can_use_cache",
"(",
"self",
",",
"target",
":",
"Target",
")",
"->",
"bool",
":",
"# if caching is disabled for this execution, then all targets are dirty",
"if",
"self",
".",
"conf",
".",
"no_build_cache",
":",
"return",
"False",
"# if the target's `cachable` pr... | 49.388889 | 19.611111 |
def _transcribe_files(self, file_list, file_mimetype):
''' a helper method for multi-processing file transcription '''
# import dependencies
import queue
from threading import Thread
# define multithreading function
def _recognize_file(file_path, file_mimetype, queue)... | [
"def",
"_transcribe_files",
"(",
"self",
",",
"file_list",
",",
"file_mimetype",
")",
":",
"# import dependencies\r",
"import",
"queue",
"from",
"threading",
"import",
"Thread",
"# define multithreading function\r",
"def",
"_recognize_file",
"(",
"file_path",
",",
"file... | 31.283019 | 20.716981 |
def get_assessment_part_query_session_for_bank(self, bank_id, proxy):
"""Gets the ``OsidSession`` associated with the assessment part query service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assess... | [
"def",
"get_assessment_part_query_session_for_bank",
"(",
"self",
",",
"bank_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_assessment_part_query",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also include check to see... | 51.208333 | 21.791667 |
def _getpwnam(name, root=None):
'''
Alternative implementation for getpwnam, that use only /etc/passwd
'''
root = '/' if not root else root
passwd = os.path.join(root, 'etc/passwd')
with salt.utils.files.fopen(passwd) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_... | [
"def",
"_getpwnam",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"root",
"=",
"'/'",
"if",
"not",
"root",
"else",
"root",
"passwd",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'etc/passwd'",
")",
"with",
"salt",
".",
"utils",
".",
... | 39 | 15.666667 |
def search_in_workspace(self, workspace, params={}, **options):
"""The search endpoint allows you to build complex queries to find and fetch exactly the data you need from Asana. For a more comprehensive description of all the query parameters and limitations of this endpoint, see our [long-form documentation]... | [
"def",
"search_in_workspace",
"(",
"self",
",",
"workspace",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/workspaces/%s/tasks/search\"",
"%",
"(",
"workspace",
")",
"return",
"self",
".",
"client",
".",
"get_collection",... | 70 | 21 |
def build_author_inclusion_filter(authors: Strings) -> EdgePredicate:
"""Build an edge predicate that passes for edges with citations written by the given author(s)."""
if isinstance(authors, str):
@edge_predicate
def author_filter(edge_data: EdgeData) -> bool:
"""Pass for edges with... | [
"def",
"build_author_inclusion_filter",
"(",
"authors",
":",
"Strings",
")",
"->",
"EdgePredicate",
":",
"if",
"isinstance",
"(",
"authors",
",",
"str",
")",
":",
"@",
"edge_predicate",
"def",
"author_filter",
"(",
"edge_data",
":",
"EdgeData",
")",
"->",
"boo... | 41.347826 | 19.695652 |
def get_data(
dataset,
query=None,
crs="epsg:4326",
bounds=None,
sortby=None,
pagesize=10000,
max_workers=5,
):
"""Get GeoJSON featurecollection from DataBC WFS
"""
param_dicts = define_request(dataset, query, crs, bounds, sortby, pagesize)
with ThreadPoolExecutor(max_worker... | [
"def",
"get_data",
"(",
"dataset",
",",
"query",
"=",
"None",
",",
"crs",
"=",
"\"epsg:4326\"",
",",
"bounds",
"=",
"None",
",",
"sortby",
"=",
"None",
",",
"pagesize",
"=",
"10000",
",",
"max_workers",
"=",
"5",
",",
")",
":",
"param_dicts",
"=",
"d... | 26.45 | 22.3 |
def set_occupancy_modes(self, index, auto_away=None, follow_me=None):
'''Enable/disable Smart Home/Away and Follow Me modes
Values: True, False
'''
body = {
'selection': {
'selectionType': 'thermostats',
'selectionMatch': self.thermost... | [
"def",
"set_occupancy_modes",
"(",
"self",
",",
"index",
",",
"auto_away",
"=",
"None",
",",
"follow_me",
"=",
"None",
")",
":",
"body",
"=",
"{",
"'selection'",
":",
"{",
"'selectionType'",
":",
"'thermostats'",
",",
"'selectionMatch'",
":",
"self",
".",
... | 36.6875 | 18.6875 |
def parse_manifest(cls, session, url_or_manifest, **args):
"""
Attempt to parse a DASH manifest file and return its streams
:param session: Streamlink session instance
:param url_or_manifest: URL of the manifest file or an XML manifest string
:return: a dict of name -> DASHStrea... | [
"def",
"parse_manifest",
"(",
"cls",
",",
"session",
",",
"url_or_manifest",
",",
"*",
"*",
"args",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"url_or_manifest",
".",
"startswith",
"(",
"'<?xml'",
")",
":",
"mpd",
"=",
"MPD",
"(",
"parse_xml",
"(",
"url_or_... | 37.5 | 23.175676 |
def parse(self,xml):
"""
Parses an XML document into a form read for insertion into the database
xml = the xml document to be parsed
"""
if not self.xmlparser:
raise LIGOLwParseError, "pyRXP parser not initialized"
if not self.lwtparser:
raise LIGOLwParseError, "LIGO_LW tuple parser... | [
"def",
"parse",
"(",
"self",
",",
"xml",
")",
":",
"if",
"not",
"self",
".",
"xmlparser",
":",
"raise",
"LIGOLwParseError",
",",
"\"pyRXP parser not initialized\"",
"if",
"not",
"self",
".",
"lwtparser",
":",
"raise",
"LIGOLwParseError",
",",
"\"LIGO_LW tuple pa... | 35.866667 | 15.866667 |
def execute_action_sequence(self, action_sequence: List[str], side_arguments: List[Dict] = None):
"""
Executes the program defined by an action sequence directly, without needing the overhead
of translating to a logical form first. For any given program, :func:`execute` and this
functio... | [
"def",
"execute_action_sequence",
"(",
"self",
",",
"action_sequence",
":",
"List",
"[",
"str",
"]",
",",
"side_arguments",
":",
"List",
"[",
"Dict",
"]",
"=",
"None",
")",
":",
"# We'll strip off the first action, because it doesn't matter for execution.",
"first_actio... | 64.684211 | 32.578947 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.