text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def __WaitForInstance(instance, desired_state):
""" Blocks until instance is in desired_state. """
print 'Waiting for instance %s to change to %s' % (instance.id, desired_state)
while True:
try:
instance.update()
state = instance.state
sys.stdout.write('.')
sys.stdout... | [
"def",
"__WaitForInstance",
"(",
"instance",
",",
"desired_state",
")",
":",
"print",
"'Waiting for instance %s to change to %s'",
"%",
"(",
"instance",
".",
"id",
",",
"desired_state",
")",
"while",
"True",
":",
"try",
":",
"instance",
".",
"update",
"(",
")",
... | 33.705882 | 17 |
def _example_order_book(quote_ctx):
"""
获取摆盘数据,输出 买价,买量,买盘经纪个数,卖价,卖量,卖盘经纪个数
"""
stock_code_list = ["US.AAPL", "HK.00700"]
# subscribe "ORDER_BOOK"
ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.ORDER_BOOK)
if ret_status != ft.RET_OK:
print(ret_data)
e... | [
"def",
"_example_order_book",
"(",
"quote_ctx",
")",
":",
"stock_code_list",
"=",
"[",
"\"US.AAPL\"",
",",
"\"HK.00700\"",
"]",
"# subscribe \"ORDER_BOOK\"",
"ret_status",
",",
"ret_data",
"=",
"quote_ctx",
".",
"subscribe",
"(",
"stock_code_list",
",",
"ft",
".",
... | 29.55 | 14.85 |
def list_ranges(self, share_name, directory_name, file_name,
start_range=None, end_range=None, timeout=None):
'''
Retrieves the valid ranges for a file.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the ... | [
"def",
"list_ranges",
"(",
"self",
",",
"share_name",
",",
"directory_name",
",",
"file_name",
",",
"start_range",
"=",
"None",
",",
"end_range",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"_validate_not_none",
"(",
"'share_name'",
",",
"share_name",
... | 40.704545 | 15.704545 |
def add_tasks(batch_service_client, job_id, loads,
output_container_name, output_container_sas_token,
task_file, acount_name):
"""Adds a task for each input file in the collection to the specified job.
:param batch_service_client: A Batch service client.
:type batch_service_clie... | [
"def",
"add_tasks",
"(",
"batch_service_client",
",",
"job_id",
",",
"loads",
",",
"output_container_name",
",",
"output_container_sas_token",
",",
"task_file",
",",
"acount_name",
")",
":",
"_log",
".",
"info",
"(",
"'Adding {} tasks to job [{}]...'",
".",
"format",
... | 41.979592 | 18.653061 |
def tz_convert(self, tz):
"""
Convert tz-aware Datetime Array/Index from one time zone to another.
Parameters
----------
tz : str, pytz.timezone, dateutil.tz.tzfile or None
Time zone for time. Corresponding timestamps would be converted
to this time zone ... | [
"def",
"tz_convert",
"(",
"self",
",",
"tz",
")",
":",
"tz",
"=",
"timezones",
".",
"maybe_get_tz",
"(",
"tz",
")",
"if",
"self",
".",
"tz",
"is",
"None",
":",
"# tz naive, use tz_localize",
"raise",
"TypeError",
"(",
"'Cannot convert tz-naive timestamps, use '"... | 36.256757 | 23.067568 |
def plot_ell(fignum, pars, col, lower, plot):
"""
function to calcualte/plot points on an ellipse about Pdec,Pdip with angle beta,gamma
Parameters
_________
fignum : matplotlib figure number
pars : list of [Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc ]
where P is direction, Bdec,Bin... | [
"def",
"plot_ell",
"(",
"fignum",
",",
"pars",
",",
"col",
",",
"lower",
",",
"plot",
")",
":",
"plt",
".",
"figure",
"(",
"num",
"=",
"fignum",
")",
"rad",
"=",
"old_div",
"(",
"np",
".",
"pi",
",",
"180.",
")",
"Pdec",
",",
"Pinc",
",",
"beta... | 34.207317 | 15.54878 |
def update(self, callback=None, errback=None, **kwargs):
"""
Update record configuration. Pass list of keywords and their values to
update. For the list of keywords available for zone configuration, see
:attr:`ns1.rest.records.Records.INT_FIELDS`,
:attr:`ns1.rest.records.Records.... | [
"def",
"update",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"data",
":",
"raise",
"RecordException",
"(",
"'record not loaded'",
")",
"def",
"success",
"(",
"resu... | 40.25 | 19.05 |
def insert_before(self, text):
"""
Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync.
"""
selection_state = self.selection
if selection_state:
selection_state = SelectionState(
... | [
"def",
"insert_before",
"(",
"self",
",",
"text",
")",
":",
"selection_state",
"=",
"self",
".",
"selection",
"if",
"selection_state",
":",
"selection_state",
"=",
"SelectionState",
"(",
"original_cursor_position",
"=",
"selection_state",
".",
"original_cursor_positio... | 37.75 | 16.5 |
async def message(self, msg, msg_type=None, use_version=None):
"""
Loads/dumps message
:param msg:
:param msg_type:
:param use_version:
:return:
"""
elem_type = msg_type if msg_type is not None else msg.__class__
version = await self.version(elem_t... | [
"async",
"def",
"message",
"(",
"self",
",",
"msg",
",",
"msg_type",
"=",
"None",
",",
"use_version",
"=",
"None",
")",
":",
"elem_type",
"=",
"msg_type",
"if",
"msg_type",
"is",
"not",
"None",
"else",
"msg",
".",
"__class__",
"version",
"=",
"await",
... | 36.88 | 20.32 |
def stdev(requestContext, seriesList, points, windowTolerance=0.1):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Draw the Standard Deviation of all metrics passed for the past N
datapoints. If the ratio of null points in the window is greater than
windowTolerance, skip the... | [
"def",
"stdev",
"(",
"requestContext",
",",
"seriesList",
",",
"points",
",",
"windowTolerance",
"=",
"0.1",
")",
":",
"# For this we take the standard deviation in terms of the moving average",
"# and the moving average of series squares.",
"for",
"seriesIndex",
",",
"series",... | 38.785714 | 20.9 |
def print_tree_recursive(tree_obj, node_index, attribute_names=None):
"""
Recursively writes a string representation of a decision tree object.
Parameters
----------
tree_obj : sklearn.tree._tree.Tree object
A base decision tree object
node_index : int
Index of the node being pr... | [
"def",
"print_tree_recursive",
"(",
"tree_obj",
",",
"node_index",
",",
"attribute_names",
"=",
"None",
")",
":",
"tree_str",
"=",
"\"\"",
"if",
"node_index",
"==",
"0",
":",
"tree_str",
"+=",
"\"{0:d}\\n\"",
".",
"format",
"(",
"tree_obj",
".",
"node_count",
... | 47.977778 | 27.666667 |
def reset_store(self):
'''
Clears out the current store and gets a cookie. Set the cross site
request forgery token for each subsequent request.
:return: A response having cleared the current store.
:rtype: requests.Response
'''
response = self.__get('/Store/Rese... | [
"def",
"reset_store",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"__get",
"(",
"'/Store/Reset'",
")",
"token",
"=",
"self",
".",
"session",
".",
"cookies",
"[",
"'XSRF-TOKEN'",
"]",
"self",
".",
"session",
".",
"headers",
".",
"update",
"(",
... | 32 | 23.428571 |
def get_model(self):
"""
Returns the model instance of the ProbModel.
Return
---------------
model: an instance of BayesianModel.
Examples
-------
>>> reader = ProbModelXMLReader()
>>> reader.get_model()
"""
if self.probnet.get('t... | [
"def",
"get_model",
"(",
"self",
")",
":",
"if",
"self",
".",
"probnet",
".",
"get",
"(",
"'type'",
")",
"==",
"\"BayesianNetwork\"",
":",
"model",
"=",
"BayesianModel",
"(",
")",
"model",
".",
"add_nodes_from",
"(",
"self",
".",
"probnet",
"[",
"'Variab... | 40.74 | 21.38 |
def import_users(self):
""" save users to local DB """
self.message('saving users into local DB')
saved_users = self.saved_admins
# loop over all extracted unique email addresses
for email in self.email_set:
owner = self.users_dict[email].get('owner')
#... | [
"def",
"import_users",
"(",
"self",
")",
":",
"self",
".",
"message",
"(",
"'saving users into local DB'",
")",
"saved_users",
"=",
"self",
".",
"saved_admins",
"# loop over all extracted unique email addresses",
"for",
"email",
"in",
"self",
".",
"email_set",
":",
... | 40.736842 | 19.157895 |
def plot(self, X=None, n=0, ax=None, envelopes=[1, 3], base_alpha=0.375,
return_prediction=False, return_std=True, full_output=False,
plot_kwargs={}, **kwargs):
"""Plots the Gaussian process using the current hyperparameters. Only for num_dim <= 2.
Parameters
-... | [
"def",
"plot",
"(",
"self",
",",
"X",
"=",
"None",
",",
"n",
"=",
"0",
",",
"ax",
"=",
"None",
",",
"envelopes",
"=",
"[",
"1",
",",
"3",
"]",
",",
"base_alpha",
"=",
"0.375",
",",
"return_prediction",
"=",
"False",
",",
"return_std",
"=",
"True"... | 47.042373 | 22.025424 |
def info(self, **kwargs):
"""
Get the primary information about a TV episode by combination of a
season and episode number.
Args:
language: (optional) ISO 639 code.
append_to_response: (optional) Comma separated, any TV series
meth... | [
"def",
"info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_series_id_season_number_episode_number_path",
"(",
"'info'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs... | 33.055556 | 19.611111 |
def _next_month(self):
"""Update calendar to show the next month."""
self._canvas.place_forget()
year, month = self._date.year, self._date.month
self._date = self._date + self.timedelta(
days=calendar.monthrange(year, month)[1] + 1)
self._date = self.datetime(self._d... | [
"def",
"_next_month",
"(",
"self",
")",
":",
"self",
".",
"_canvas",
".",
"place_forget",
"(",
")",
"year",
",",
"month",
"=",
"self",
".",
"_date",
".",
"year",
",",
"self",
".",
"_date",
".",
"month",
"self",
".",
"_date",
"=",
"self",
".",
"_dat... | 41.444444 | 16.222222 |
def pre_fork(self, process_manager):
'''
Pre-fork we need to create the zmq router device
'''
salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
if USE_LOAD_BALANCER:
self.socket_queue = multiprocessing.Queue()
process_manager.add... | [
"def",
"pre_fork",
"(",
"self",
",",
"process_manager",
")",
":",
"salt",
".",
"transport",
".",
"mixins",
".",
"auth",
".",
"AESReqServerMixin",
".",
"pre_fork",
"(",
"self",
",",
"process_manager",
")",
"if",
"USE_LOAD_BALANCER",
":",
"self",
".",
"socket_... | 49.1875 | 21.8125 |
def unmount(self, path):
"""
Remove a mountpoint from the filesystem.
"""
del self._mountpoints[self._join_chunks(self._normalize_path(path))] | [
"def",
"unmount",
"(",
"self",
",",
"path",
")",
":",
"del",
"self",
".",
"_mountpoints",
"[",
"self",
".",
"_join_chunks",
"(",
"self",
".",
"_normalize_path",
"(",
"path",
")",
")",
"]"
] | 34 | 12 |
def _is_valid_url(url):
""" Helper function to validate that URLs are well formed, i.e that it contains a valid
protocol and a valid domain. It does not actually check if the URL exists
"""
try:
parsed = urlparse(url)
mandatory_parts = [parsed.scheme, parsed.n... | [
"def",
"_is_valid_url",
"(",
"url",
")",
":",
"try",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"mandatory_parts",
"=",
"[",
"parsed",
".",
"scheme",
",",
"parsed",
".",
"netloc",
"]",
"return",
"all",
"(",
"mandatory_parts",
")",
"except",
":",
... | 39.8 | 15.8 |
def save(self):
"""save PlayerRecord settings to disk"""
data = str.encode( json.dumps(self.simpleAttrs, indent=4, sort_keys=True) )
with open(self.filename, "wb") as f:
f.write(data) | [
"def",
"save",
"(",
"self",
")",
":",
"data",
"=",
"str",
".",
"encode",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"simpleAttrs",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
")",
"with",
"open",
"(",
"self",
".",
"filename",
"... | 43 | 17.4 |
def inverse(self):
"""Invert all instructions."""
for index, instruction in enumerate(self.instructions):
self.instructions[index] = instruction.inverse()
return self | [
"def",
"inverse",
"(",
"self",
")",
":",
"for",
"index",
",",
"instruction",
"in",
"enumerate",
"(",
"self",
".",
"instructions",
")",
":",
"self",
".",
"instructions",
"[",
"index",
"]",
"=",
"instruction",
".",
"inverse",
"(",
")",
"return",
"self"
] | 39.6 | 17.2 |
def active_io(self, iocb):
"""Called by a handler to notify the controller that a request is
being processed."""
if _debug: IOController._debug("active_io %r", iocb)
# requests should be idle or pending before coming active
if (iocb.ioState != IDLE) and (iocb.ioState != PENDING)... | [
"def",
"active_io",
"(",
"self",
",",
"iocb",
")",
":",
"if",
"_debug",
":",
"IOController",
".",
"_debug",
"(",
"\"active_io %r\"",
",",
"iocb",
")",
"# requests should be idle or pending before coming active",
"if",
"(",
"iocb",
".",
"ioState",
"!=",
"IDLE",
"... | 41.909091 | 21.727273 |
def numericshape(self):
"""Shape of the array of temporary values required for the numerical
solver actually being selected."""
try:
numericshape = [self.subseqs.seqs.model.numconsts.nmb_stages]
except AttributeError:
objecttools.augment_excmessage(
... | [
"def",
"numericshape",
"(",
"self",
")",
":",
"try",
":",
"numericshape",
"=",
"[",
"self",
".",
"subseqs",
".",
"seqs",
".",
"model",
".",
"numconsts",
".",
"nmb_stages",
"]",
"except",
"AttributeError",
":",
"objecttools",
".",
"augment_excmessage",
"(",
... | 51.133333 | 16.866667 |
def p_function_expr_1(self, p):
"""
function_expr \
: FUNCTION LPAREN RPAREN LBRACE function_body RBRACE
| FUNCTION LPAREN formal_parameter_list RPAREN \
LBRACE function_body RBRACE
"""
if len(p) == 7:
p[0] = ast.FuncExpr(
... | [
"def",
"p_function_expr_1",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"7",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"FuncExpr",
"(",
"identifier",
"=",
"None",
",",
"parameters",
"=",
"None",
",",
"elements",
"=",
"p",
... | 36.230769 | 13.923077 |
def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub user.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:par... | [
"def",
"ghuser_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"{",
"}",
",",
"content",
"=",
"[",
"]",
")",
":",
"# app = inliner.document.settings.env.app",
"#app.info('user link %r' % text)",
"ref",
"=",
... | 43.25 | 18.75 |
def coverage(c, html=True):
"""
Run coverage with coverage.py.
"""
# NOTE: this MUST use coverage itself, and not pytest-cov, because the
# latter is apparently unable to prevent pytest plugins from being loaded
# before pytest-cov itself is able to start up coverage.py! The result is
# that... | [
"def",
"coverage",
"(",
"c",
",",
"html",
"=",
"True",
")",
":",
"# NOTE: this MUST use coverage itself, and not pytest-cov, because the",
"# latter is apparently unable to prevent pytest plugins from being loaded",
"# before pytest-cov itself is able to start up coverage.py! The result is",... | 47.4375 | 18.6875 |
def binary_hash(self, project, patch_file):
""" Gathers sha256 hashes from binary lists """
global il
exception_file = None
try:
project_exceptions = il.get('project_exceptions')
except KeyError:
logger.info('project_exceptions missing in %s for %s', ignor... | [
"def",
"binary_hash",
"(",
"self",
",",
"project",
",",
"patch_file",
")",
":",
"global",
"il",
"exception_file",
"=",
"None",
"try",
":",
"project_exceptions",
"=",
"il",
".",
"get",
"(",
"'project_exceptions'",
")",
"except",
"KeyError",
":",
"logger",
"."... | 44.264706 | 16.176471 |
def callproc(self, procname, parameters=(), quiet=False, expect_return_value=False):
"""Calls a MySQL stored procedure procname and returns the return values. This uses DictCursor.
To get return values back out of a stored procedure, prefix the parameter with a @ character.
"""
self.... | [
"def",
"callproc",
"(",
"self",
",",
"procname",
",",
"parameters",
"=",
"(",
")",
",",
"quiet",
"=",
"False",
",",
"expect_return_value",
"=",
"False",
")",
":",
"self",
".",
"procedures_run",
"+=",
"1",
"i",
"=",
"0",
"errcode",
"=",
"0",
"caughte",
... | 42.773585 | 20.132075 |
def detach_from_all(self, bIgnoreExceptions = False):
"""
Detaches from all processes currently being debugged.
@note: To better handle last debugging event, call L{stop} instead.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may... | [
"def",
"detach_from_all",
"(",
"self",
",",
"bIgnoreExceptions",
"=",
"False",
")",
":",
"for",
"pid",
"in",
"self",
".",
"get_debugee_pids",
"(",
")",
":",
"self",
".",
"detach",
"(",
"pid",
",",
"bIgnoreExceptions",
"=",
"bIgnoreExceptions",
")"
] | 38.666667 | 19.6 |
def write_string(value, buff, byteorder='big'):
"""Write a string to a file-like object."""
data = value.encode('utf-8')
write_numeric(USHORT, len(data), buff, byteorder)
buff.write(data) | [
"def",
"write_string",
"(",
"value",
",",
"buff",
",",
"byteorder",
"=",
"'big'",
")",
":",
"data",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"write_numeric",
"(",
"USHORT",
",",
"len",
"(",
"data",
")",
",",
"buff",
",",
"byteorder",
")",
"b... | 40.6 | 9.8 |
def to_vec4(self, isPoint):
"""Converts this vector3 into a vector4 instance."""
vec4 = Vector4()
vec4.x = self.x
vec4.y = self.y
vec4.z = self.z
if isPoint:
vec4.w = 1
else:
vec4.w = 0
return vec4 | [
"def",
"to_vec4",
"(",
"self",
",",
"isPoint",
")",
":",
"vec4",
"=",
"Vector4",
"(",
")",
"vec4",
".",
"x",
"=",
"self",
".",
"x",
"vec4",
".",
"y",
"=",
"self",
".",
"y",
"vec4",
".",
"z",
"=",
"self",
".",
"z",
"if",
"isPoint",
":",
"vec4"... | 22.916667 | 18.75 |
def peakdelta(v, delta, x=None):
"""
Returns two arrays
function [maxtab, mintab]=peakdelta(v, delta, x)
%PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = peakdelta(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consist... | [
"def",
"peakdelta",
"(",
"v",
",",
"delta",
",",
"x",
"=",
"None",
")",
":",
"maxtab",
"=",
"[",
"]",
"mintab",
"=",
"[",
"]",
"if",
"x",
"is",
"None",
":",
"x",
"=",
"arange",
"(",
"len",
"(",
"v",
")",
")",
"v",
"=",
"asarray",
"(",
"v",
... | 28.179104 | 21.313433 |
def _to_numpy(Z):
"""Converts a None, list, np.ndarray, or torch.Tensor to np.ndarray;
also handles converting sparse input to dense."""
if Z is None:
return Z
elif issparse(Z):
return Z.toarray()
elif isinstance(Z, np.ndarray):
return Z
... | [
"def",
"_to_numpy",
"(",
"Z",
")",
":",
"if",
"Z",
"is",
"None",
":",
"return",
"Z",
"elif",
"issparse",
"(",
"Z",
")",
":",
"return",
"Z",
".",
"toarray",
"(",
")",
"elif",
"isinstance",
"(",
"Z",
",",
"np",
".",
"ndarray",
")",
":",
"return",
... | 33.263158 | 13 |
def xarrayfunc(func):
"""Make a function compatible with xarray.DataArray.
This function is intended to be used as a decorator like::
>>> @dc.xarrayfunc
>>> def func(array):
... # do something
... return newarray
>>>
>>> result = func(array)
Args:
... | [
"def",
"xarrayfunc",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"arg",
",",
"xr",
".",
"DataArray",
")",
"for",
"arg",
"in",
... | 28.029412 | 19.588235 |
def stratify_s(self):
"""
Stratifies the sample based on propensity score using the
bin selection procedure suggested by [1]_.
The bin selection algorithm is based on a sequence of
two-sample t tests performed on the log-odds ratio.
This method should only be executed after the propensity score
has bee... | [
"def",
"stratify_s",
"(",
"self",
")",
":",
"pscore_order",
"=",
"self",
".",
"raw_data",
"[",
"'pscore'",
"]",
".",
"argsort",
"(",
")",
"pscore",
"=",
"self",
".",
"raw_data",
"[",
"'pscore'",
"]",
"[",
"pscore_order",
"]",
"D",
"=",
"self",
".",
"... | 28.214286 | 19.642857 |
def __send_command(self, command, args=[]):
'''Send a raw command.'''
self.ws.send(json.dumps({"op": command, "args": args})) | [
"def",
"__send_command",
"(",
"self",
",",
"command",
",",
"args",
"=",
"[",
"]",
")",
":",
"self",
".",
"ws",
".",
"send",
"(",
"json",
".",
"dumps",
"(",
"{",
"\"op\"",
":",
"command",
",",
"\"args\"",
":",
"args",
"}",
")",
")"
] | 46.333333 | 11 |
def stop_trace(frame=None, close_on_exit=False):
"""Stop tracing"""
log.info('Stopping trace')
wdb = Wdb.get(True) # Do not create an istance if there's None
if wdb and (not wdb.stepping or close_on_exit):
log.info('Stopping trace')
wdb.stop_trace(frame or sys._getframe().f_back)
... | [
"def",
"stop_trace",
"(",
"frame",
"=",
"None",
",",
"close_on_exit",
"=",
"False",
")",
":",
"log",
".",
"info",
"(",
"'Stopping trace'",
")",
"wdb",
"=",
"Wdb",
".",
"get",
"(",
"True",
")",
"# Do not create an istance if there's None",
"if",
"wdb",
"and",... | 36.7 | 13.7 |
def hdd_disk_interface(self, hdd_disk_interface):
"""
Sets the hdd disk interface for this QEMU VM.
:param hdd_disk_interface: QEMU hdd disk interface
"""
self._hdd_disk_interface = hdd_disk_interface
log.info('QEMU VM "{name}" [{id}] has set the QEMU hdd disk interface... | [
"def",
"hdd_disk_interface",
"(",
"self",
",",
"hdd_disk_interface",
")",
":",
"self",
".",
"_hdd_disk_interface",
"=",
"hdd_disk_interface",
"log",
".",
"info",
"(",
"'QEMU VM \"{name}\" [{id}] has set the QEMU hdd disk interface to {interface}'",
".",
"format",
"(",
"name... | 54.727273 | 34.545455 |
def set_euk_hmm(self, args):
'Set the hmm used by graftM to cross check for euks.'
if hasattr(args, 'euk_hmm_file'):
pass
elif not hasattr(args, 'euk_hmm_file'):
# set to path based on the location of bin/graftM, which has
# a more stable relative path to the ... | [
"def",
"set_euk_hmm",
"(",
"self",
",",
"args",
")",
":",
"if",
"hasattr",
"(",
"args",
",",
"'euk_hmm_file'",
")",
":",
"pass",
"elif",
"not",
"hasattr",
"(",
"args",
",",
"'euk_hmm_file'",
")",
":",
"# set to path based on the location of bin/graftM, which has",... | 50.909091 | 26.363636 |
def reset(self, source):
""" Reset scanner's state.
:param source: Source for parsing
"""
self.tokens = []
self.source = source
self.pos = 0 | [
"def",
"reset",
"(",
"self",
",",
"source",
")",
":",
"self",
".",
"tokens",
"=",
"[",
"]",
"self",
".",
"source",
"=",
"source",
"self",
".",
"pos",
"=",
"0"
] | 20.222222 | 16.111111 |
def tradingStatusSSE(symbols=None, on_data=None, token='', version=''):
'''The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news ... | [
"def",
"tradingStatusSSE",
"(",
"symbols",
"=",
"None",
",",
"on_data",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"return",
"_runSSE",
"(",
"'trading-status'",
",",
"symbols",
",",
"on_data",
",",
"token",
",",
"version",... | 63.222222 | 51.814815 |
def node_rank(self):
"""
Returns the maximum rank for each **topological node** in the
``DictGraph``. The rank of a node is defined as the number of edges
between the node and a node which has rank 0. A **topological node**
has rank 0 if it has no incoming edges.
... | [
"def",
"node_rank",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"postorder",
"(",
")",
"node_rank",
"=",
"{",
"}",
"for",
"node",
"in",
"nodes",
":",
"max_rank",
"=",
"0",
"for",
"child",
"in",
"self",
"[",
"node",
"]",
".",
"nodes",
"(",
"... | 37 | 15.235294 |
def load_watch():
'''
Loads some of the 6-axis inertial sensor data from my smartwatch project. The sensor data was
recorded as study subjects performed sets of 20 shoulder exercise repetitions while wearing a
smartwatch. It is a multivariate time series.
The study can be found here: https://arxiv.... | [
"def",
"load_watch",
"(",
")",
":",
"module_path",
"=",
"dirname",
"(",
"__file__",
")",
"data",
"=",
"np",
".",
"load",
"(",
"module_path",
"+",
"\"/data/watch_dataset.npy\"",
")",
".",
"item",
"(",
")",
"return",
"data"
] | 35.735294 | 20.558824 |
def GetItemContainerLink(link):
"""Gets the document collection link
:param str link:
Resource link
:return:
Document collection link.
:rtype: str
"""
link = TrimBeginningAndEndingSlashes(link) + '/'
index = IndexOfNth(link, '/', 4)
if index != -1:
return... | [
"def",
"GetItemContainerLink",
"(",
"link",
")",
":",
"link",
"=",
"TrimBeginningAndEndingSlashes",
"(",
"link",
")",
"+",
"'/'",
"index",
"=",
"IndexOfNth",
"(",
"link",
",",
"'/'",
",",
"4",
")",
"if",
"index",
"!=",
"-",
"1",
":",
"return",
"link",
... | 21.473684 | 22.368421 |
def get_request_token(self, request, callback):
"""Fetch the OAuth request token. Only required for OAuth 1.0."""
callback = force_text(request.build_absolute_uri(callback))
try:
response = self.request('post', self.request_token_url, oauth_callback=callback)
response.rai... | [
"def",
"get_request_token",
"(",
"self",
",",
"request",
",",
"callback",
")",
":",
"callback",
"=",
"force_text",
"(",
"request",
".",
"build_absolute_uri",
"(",
"callback",
")",
")",
"try",
":",
"response",
"=",
"self",
".",
"request",
"(",
"'post'",
","... | 46.090909 | 18.363636 |
def _create_get_request(self, resource, billomat_id='', command=None, params=None):
"""
Creates a get request and return the response data
"""
if not params:
params = {}
if not command:
command = ''
else:
command = '/' + command
... | [
"def",
"_create_get_request",
"(",
"self",
",",
"resource",
",",
"billomat_id",
"=",
"''",
",",
"command",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"if",
"not",
"command",
":",
"command",
... | 31.291667 | 20.875 |
def query(self, query):
"""
Query bugzilla and return a list of matching bugs.
query must be a dict with fields like those in in querydata['fields'].
Returns a list of Bug objects.
Also see the _query() method for details about the underlying
implementation.
"""
... | [
"def",
"query",
"(",
"self",
",",
"query",
")",
":",
"try",
":",
"r",
"=",
"self",
".",
"_proxy",
".",
"Bug",
".",
"search",
"(",
"query",
")",
"except",
"Fault",
"as",
"e",
":",
"# Try to give a hint in the error message if url_to_query",
"# isn't supported b... | 40.8 | 17.92 |
def pickAChannel(self, ra_deg, dec_deg):
"""Returns the channel number closest to a given (ra, dec) coordinate.
"""
# Could improve speed by doing this in the projection plane
# instead of sky coords
cRa = self.currentRaDec[:, 3] # Ra of each channel corner
cDec = self.c... | [
"def",
"pickAChannel",
"(",
"self",
",",
"ra_deg",
",",
"dec_deg",
")",
":",
"# Could improve speed by doing this in the projection plane",
"# instead of sky coords",
"cRa",
"=",
"self",
".",
"currentRaDec",
"[",
":",
",",
"3",
"]",
"# Ra of each channel corner",
"cDec"... | 40.071429 | 17.714286 |
def _round_frac(x, precision):
"""
Round the fractional part of the given number
"""
if not np.isfinite(x) or x == 0:
return x
else:
frac, whole = np.modf(x)
if whole == 0:
digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision
else:
digi... | [
"def",
"_round_frac",
"(",
"x",
",",
"precision",
")",
":",
"if",
"not",
"np",
".",
"isfinite",
"(",
"x",
")",
"or",
"x",
"==",
"0",
":",
"return",
"x",
"else",
":",
"frac",
",",
"whole",
"=",
"np",
".",
"modf",
"(",
"x",
")",
"if",
"whole",
... | 27.538462 | 13.692308 |
def set_image(self, image):
"""Set display buffer to Python Image Library image. Red pixels (r=255,
g=0, b=0) will map to red LEDs, green pixels (r=0, g=255, b=0) will map to
green LEDs, and yellow pixels (r=255, g=255, b=0) will map to yellow LEDs.
All other pixel values will map to an... | [
"def",
"set_image",
"(",
"self",
",",
"image",
")",
":",
"imwidth",
",",
"imheight",
"=",
"image",
".",
"size",
"if",
"imwidth",
"!=",
"8",
"or",
"imheight",
"!=",
"8",
":",
"raise",
"ValueError",
"(",
"'Image must be an 8x8 pixels in size.'",
")",
"# Conver... | 48.6 | 11.28 |
def _compute_site_term(self, C, vs30):
"""
Compute site term as a function of vs30: 4th, 5th and 6th terms in
equation 2 page 462.
"""
# for rock values the site term is zero
site_term = np.zeros_like(vs30)
# hard soil
site_term[(vs30 >= 360) & (vs30 < 80... | [
"def",
"_compute_site_term",
"(",
"self",
",",
"C",
",",
"vs30",
")",
":",
"# for rock values the site term is zero",
"site_term",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"# hard soil",
"site_term",
"[",
"(",
"vs30",
">=",
"360",
")",
"&",
"(",
"vs30... | 26.888889 | 18.222222 |
def num_connected_components(self, unitary_only=False):
"""How many non-entangled subcircuits can the circuit be factored to.
Args:
unitary_only (bool): Compute only unitary part of graph.
Returns:
int: Number of connected components in circuit.
"""
# Co... | [
"def",
"num_connected_components",
"(",
"self",
",",
"unitary_only",
"=",
"False",
")",
":",
"# Convert registers to ints (as done in depth).",
"reg_offset",
"=",
"0",
"reg_map",
"=",
"{",
"}",
"if",
"unitary_only",
":",
"regs",
"=",
"self",
".",
"qregs",
"else",
... | 39.139241 | 15.64557 |
def _get_cache_key(self, obj):
"""Derive cache key for given object."""
if obj is not None:
# Make sure that key is REALLY unique.
return '{}-{}'.format(id(self), obj.pk)
return "{}-None".format(id(self)) | [
"def",
"_get_cache_key",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
"is",
"not",
"None",
":",
"# Make sure that key is REALLY unique.",
"return",
"'{}-{}'",
".",
"format",
"(",
"id",
"(",
"self",
")",
",",
"obj",
".",
"pk",
")",
"return",
"\"{}-None\"... | 35.285714 | 12.142857 |
def _xml_element_value(el: Element, int_tags: list):
"""
Gets XML Element value.
:param el: Element
:param int_tags: List of tags that should be treated as ints
:return: value of the element (int/str)
"""
# None
if el.text is None:
return None
# int
try:
if el.tag... | [
"def",
"_xml_element_value",
"(",
"el",
":",
"Element",
",",
"int_tags",
":",
"list",
")",
":",
"# None",
"if",
"el",
".",
"text",
"is",
"None",
":",
"return",
"None",
"# int",
"try",
":",
"if",
"el",
".",
"tag",
"in",
"int_tags",
":",
"return",
"int... | 24.368421 | 16.263158 |
def _validate_sections(cls, sections):
"""Validates sections types and uniqueness."""
names = []
for section in sections:
if not hasattr(section, 'name'):
raise ConfigurationError('`sections` attribute requires a list of Section')
name = section.name
... | [
"def",
"_validate_sections",
"(",
"cls",
",",
"sections",
")",
":",
"names",
"=",
"[",
"]",
"for",
"section",
"in",
"sections",
":",
"if",
"not",
"hasattr",
"(",
"section",
",",
"'name'",
")",
":",
"raise",
"ConfigurationError",
"(",
"'`sections` attribute r... | 34.615385 | 21.538462 |
def generate(env):
"""Add Builders and construction variables for lib to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
SCons.Tool.createSharedLibBuilder(env)
SCons.Tool.createProgBuilder(env)
env['AR'] = 'mwld'
env['ARCOM'] = '$AR $ARFLAGS -library -o $TARGET $SOURCES'
env['LIB... | [
"def",
"generate",
"(",
"env",
")",
":",
"SCons",
".",
"Tool",
".",
"createStaticLibBuilder",
"(",
"env",
")",
"SCons",
".",
"Tool",
".",
"createSharedLibBuilder",
"(",
"env",
")",
"SCons",
".",
"Tool",
".",
"createProgBuilder",
"(",
"env",
")",
"env",
"... | 32.227273 | 15.863636 |
def call(cmd, shell=True, cwd=None, universal_newlines=True, stderr=STDOUT):
"""Just execute a specific command."""
return Shell._run(call, cmd, shell=shell, cwd=cwd, stderr=stderr,
universal_newlines=universal_newlines) | [
"def",
"call",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"cwd",
"=",
"None",
",",
"universal_newlines",
"=",
"True",
",",
"stderr",
"=",
"STDOUT",
")",
":",
"return",
"Shell",
".",
"_run",
"(",
"call",
",",
"cmd",
",",
"shell",
"=",
"shell",
",",... | 64.75 | 23.25 |
def p_extr_lic_name_1(self, p):
"""extr_lic_name : LICS_NAME extr_lic_name_value"""
try:
self.builder.set_lic_name(self.document, p[2])
except OrderError:
self.order_error('LicenseName', 'LicenseID', p.lineno(1))
except CardinalityError:
self.more_than... | [
"def",
"p_extr_lic_name_1",
"(",
"self",
",",
"p",
")",
":",
"try",
":",
"self",
".",
"builder",
".",
"set_lic_name",
"(",
"self",
".",
"document",
",",
"p",
"[",
"2",
"]",
")",
"except",
"OrderError",
":",
"self",
".",
"order_error",
"(",
"'LicenseNam... | 43.875 | 16.25 |
def publish(build):
""" publish the package itself """
build.packages.install("wheel")
build.packages.install("twine")
build.executables.run([
"python", "setup.py",
"sdist", "bdist_wheel", "--universal", "--release"
])
build.executables.run([
"twine", "upload", "dist/*"
... | [
"def",
"publish",
"(",
"build",
")",
":",
"build",
".",
"packages",
".",
"install",
"(",
"\"wheel\"",
")",
"build",
".",
"packages",
".",
"install",
"(",
"\"twine\"",
")",
"build",
".",
"executables",
".",
"run",
"(",
"[",
"\"python\"",
",",
"\"setup.py\... | 28.636364 | 14.454545 |
def gc(cn, ns=None, lo=None, iq=None, ico=None, pl=None):
"""
This function is a wrapper for
:meth:`~pywbem.WBEMConnection.GetClass`.
Retrieve a class.
Parameters:
cn (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class to be retrieved (case independent).
... | [
"def",
"gc",
"(",
"cn",
",",
"ns",
"=",
"None",
",",
"lo",
"=",
"None",
",",
"iq",
"=",
"None",
",",
"ico",
"=",
"None",
",",
"pl",
"=",
"None",
")",
":",
"return",
"CONN",
".",
"GetClass",
"(",
"cn",
",",
"ns",
",",
"LocalOnly",
"=",
"lo",
... | 32.166667 | 24.351852 |
def find_slack_bus(sub_network):
"""Find the slack bus in a connected sub-network."""
gens = sub_network.generators()
if len(gens) == 0:
logger.warning("No generators in sub-network {}, better hope power is already balanced".format(sub_network.name))
sub_network.slack_generator = None
... | [
"def",
"find_slack_bus",
"(",
"sub_network",
")",
":",
"gens",
"=",
"sub_network",
".",
"generators",
"(",
")",
"if",
"len",
"(",
"gens",
")",
"==",
"0",
":",
"logger",
".",
"warning",
"(",
"\"No generators in sub-network {}, better hope power is already balanced\""... | 45.1875 | 34.4375 |
def get_all_leaves(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
... | [
"def",
"get_all_leaves",
"(",
"self",
",",
"item_ids",
"=",
"None",
",",
"language",
"=",
"None",
",",
"forbidden_item_ids",
"=",
"None",
")",
":",
"return",
"sorted",
"(",
"set",
"(",
"flatten",
"(",
"self",
".",
"get_leaves",
"(",
"item_ids",
",",
"lan... | 47.357143 | 30.214286 |
def run_all(logdir, verbose=False):
"""Perform random search over the hyperparameter space.
Arguments:
logdir: The top-level directory into which to write data. This
directory should be empty or nonexistent.
verbose: If true, print out each run's name as it begins.
"""
data = prepare_data()
rng... | [
"def",
"run_all",
"(",
"logdir",
",",
"verbose",
"=",
"False",
")",
":",
"data",
"=",
"prepare_data",
"(",
")",
"rng",
"=",
"random",
".",
"Random",
"(",
"0",
")",
"base_writer",
"=",
"tf",
".",
"summary",
".",
"create_file_writer",
"(",
"logdir",
")",... | 35.023256 | 18.27907 |
def unregister(self, items):
"""
Remove items from registry.
:param items:
"""
items = _listify(items)
# get all members of Registry except private, special or class
meta_names = (m for m in vars(self).iterkeys()
if (not m.startswith('_') an... | [
"def",
"unregister",
"(",
"self",
",",
"items",
")",
":",
"items",
"=",
"_listify",
"(",
"items",
")",
"# get all members of Registry except private, special or class",
"meta_names",
"=",
"(",
"m",
"for",
"m",
"in",
"vars",
"(",
"self",
")",
".",
"iterkeys",
"... | 37.681818 | 15.227273 |
def get(self, twig=None, check_visible=True, check_default=True, **kwargs):
"""
Get a single parameter from this ParameterSet. This works exactly the
same as filter except there must be only a single result, and the Parameter
itself is returned instead of a ParameterSet.
Also s... | [
"def",
"get",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"check_visible",
"=",
"True",
",",
"check_default",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'check_visible'",
"]",
"=",
"check_visible",
"kwargs",
"[",
"'check_default'",
"... | 50.357143 | 22.357143 |
def find_venv_DST():
"""Find where this package should be installed to in this virtualenv.
For example: ``/path-to-venv/lib/python2.7/site-packages/package-name``
"""
dir_path = os.path.dirname(SRC)
if SYS_NAME == "Windows":
DST = os.path.join(dir_path, "Lib", "site-packages", PKG_NAME)
... | [
"def",
"find_venv_DST",
"(",
")",
":",
"dir_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"SRC",
")",
"if",
"SYS_NAME",
"==",
"\"Windows\"",
":",
"DST",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"\"Lib\"",
",",
"\"site-packages\"... | 35.928571 | 21.928571 |
def titleCounts(readsAlignments):
"""
Count the number of times each title in a readsAlignments instance is
matched. This is useful for rapidly discovering what titles were matched
and with what frequency.
@param readsAlignments: A L{dark.alignments.ReadsAlignments} instance.
@return: A C{dict}... | [
"def",
"titleCounts",
"(",
"readsAlignments",
")",
":",
"titles",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"readAlignments",
"in",
"readsAlignments",
":",
"for",
"alignment",
"in",
"readAlignments",
":",
"titles",
"[",
"alignment",
".",
"subjectTitle",
"]",
... | 38.25 | 19 |
def launch_debugger(frame, stream=None):
"""
Interrupt running process, and provide a python prompt for
interactive debugging.
"""
d = {'_frame': frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
import code, traceba... | [
"def",
"launch_debugger",
"(",
"frame",
",",
"stream",
"=",
"None",
")",
":",
"d",
"=",
"{",
"'_frame'",
":",
"frame",
"}",
"# Allow access to frame object.",
"d",
".",
"update",
"(",
"frame",
".",
"f_globals",
")",
"# Unless shadowed by global",
"d",
".",
"... | 30.75 | 17.75 |
def p_let_arr_substr_in_args(p):
""" statement : LET ARRAY_ID LP arguments TO RP EQ expr
| ARRAY_ID LP arguments TO RP EQ expr
"""
i = 2 if p[1].upper() == 'LET' else 1
id_ = p[i]
arg_list = p[i + 2]
substr = (arg_list.children.pop().value,
make_number(gl.MAX_STR... | [
"def",
"p_let_arr_substr_in_args",
"(",
"p",
")",
":",
"i",
"=",
"2",
"if",
"p",
"[",
"1",
"]",
".",
"upper",
"(",
")",
"==",
"'LET'",
"else",
"1",
"id_",
"=",
"p",
"[",
"i",
"]",
"arg_list",
"=",
"p",
"[",
"i",
"+",
"2",
"]",
"substr",
"=",
... | 37 | 16.666667 |
def seek_file_end(file):
'''Seek to the end of the file.'''
try:
file.seek(0, 2)
except ValueError:
# gzip files don't support seek from end
while True:
data = file.read(4096)
if not data:
break | [
"def",
"seek_file_end",
"(",
"file",
")",
":",
"try",
":",
"file",
".",
"seek",
"(",
"0",
",",
"2",
")",
"except",
"ValueError",
":",
"# gzip files don't support seek from end",
"while",
"True",
":",
"data",
"=",
"file",
".",
"read",
"(",
"4096",
")",
"i... | 26.1 | 15.5 |
def mount_medium(self, name, controller_port, device, medium, force):
"""Mounts a medium (:py:class:`IMedium` , identified
by the given UUID @a id) to the given storage controller
(:py:class:`IStorageController` , identified by @a name),
at the indicated port and device. The device must ... | [
"def",
"mount_medium",
"(",
"self",
",",
"name",
",",
"controller_port",
",",
"device",
",",
"medium",
",",
"force",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be an instance of ty... | 45.935484 | 24.274194 |
def generate_log_between_tags(self, older_tag, newer_tag):
"""
Generate log between 2 specified tags.
:param dict older_tag: All issues before this tag's date will be
excluded. May be special value, if new tag is
the first tag. (Mean... | [
"def",
"generate_log_between_tags",
"(",
"self",
",",
"older_tag",
",",
"newer_tag",
")",
":",
"filtered_issues",
",",
"filtered_pull_requests",
"=",
"self",
".",
"filter_issues_for_tags",
"(",
"newer_tag",
",",
"older_tag",
")",
"older_tag_name",
"=",
"older_tag",
... | 43.423077 | 21.192308 |
def get_port_switch_bindings(port_id, switch_ip):
"""List all vm/vlan bindings on a Nexus switch port."""
LOG.debug("get_port_switch_bindings() called, "
"port:'%(port_id)s', switch:'%(switch_ip)s'",
{'port_id': port_id, 'switch_ip': switch_ip})
try:
return _lookup_all_ne... | [
"def",
"get_port_switch_bindings",
"(",
"port_id",
",",
"switch_ip",
")",
":",
"LOG",
".",
"debug",
"(",
"\"get_port_switch_bindings() called, \"",
"\"port:'%(port_id)s', switch:'%(switch_ip)s'\"",
",",
"{",
"'port_id'",
":",
"port_id",
",",
"'switch_ip'",
":",
"switch_ip... | 45.9 | 16 |
def _titan_cn_file(cnr_file, work_dir, data):
"""Convert CNVkit or GATK4 normalized input into TitanCNA ready format.
"""
out_file = os.path.join(work_dir, "%s.cn" % (utils.splitext_plus(os.path.basename(cnr_file))[0]))
support_cols = {"cnvkit": ["chromosome", "start", "end", "log2"],
... | [
"def",
"_titan_cn_file",
"(",
"cnr_file",
",",
"work_dir",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s.cn\"",
"%",
"(",
"utils",
".",
"splitext_plus",
"(",
"os",
".",
"path",
".",
"basename",
"(",... | 56.833333 | 19.388889 |
def generate(self, output_dir, minimum_size):
"""Generates sequence reports and writes them to the output directory.
:param output_dir: directory to output reports to
:type output_dir: `str`
:param minimum_size: minimum size of n-grams to create sequences for
:type minimum_size:... | [
"def",
"generate",
"(",
"self",
",",
"output_dir",
",",
"minimum_size",
")",
":",
"self",
".",
"_output_dir",
"=",
"output_dir",
"# Get a list of the files in the matches, grouped by label",
"# (ordered by number of works).",
"labels",
"=",
"list",
"(",
"self",
".",
"_m... | 47.172414 | 16.931034 |
def factory(opts, **kwargs):
'''
Creates and returns the cache class.
If memory caching is enabled by opts MemCache class will be instantiated.
If not Cache class will be returned.
'''
if opts.get('memcache_expire_seconds', 0):
cls = MemCache
else:
cls = Cache
return cls(... | [
"def",
"factory",
"(",
"opts",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"opts",
".",
"get",
"(",
"'memcache_expire_seconds'",
",",
"0",
")",
":",
"cls",
"=",
"MemCache",
"else",
":",
"cls",
"=",
"Cache",
"return",
"cls",
"(",
"opts",
",",
"*",
"*",... | 29.545455 | 18.272727 |
def assertDateTimesLagEqual(self, sequence, lag, msg=None):
'''Fail unless max element in ``sequence`` is separated from
the present by ``lag`` as determined by the '==' operator.
If the max element is a datetime, "present" is defined as
``datetime.now()``; if the max element is a date,... | [
"def",
"assertDateTimesLagEqual",
"(",
"self",
",",
"sequence",
",",
"lag",
",",
"msg",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"sequence",
",",
"collections",
".",
"Iterable",
")",
":",
"raise",
"TypeError",
"(",
"'First argument is not iterabl... | 36.977273 | 22.295455 |
def on_background_source(self, *args):
"""When I get a new ``background_source``, load it as an
:class:`Image` and store that in ``background_image``.
"""
if self.background_source:
self.background_image = Image(source=self.background_source) | [
"def",
"on_background_source",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"background_source",
":",
"self",
".",
"background_image",
"=",
"Image",
"(",
"source",
"=",
"self",
".",
"background_source",
")"
] | 40.142857 | 14.571429 |
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_ge... | [
"def",
"fromTerm",
"(",
"cls",
",",
"term",
")",
":",
"if",
"isinstance",
"(",
"term",
",",
"Term",
")",
":",
"term",
"=",
"term",
".",
"handle",
"elif",
"not",
"isinstance",
"(",
"term",
",",
"(",
"c_void_p",
",",
"int",
")",
")",
":",
"raise",
... | 35.6 | 15.3 |
def update(self):
"""
Updates the bundle
"""
with self._lock:
# Was it active ?
restart = self._state == Bundle.ACTIVE
# Send the update event
self._fire_bundle_event(BundleEvent.UPDATE_BEGIN)
try:
# Stop the b... | [
"def",
"update",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"# Was it active ?",
"restart",
"=",
"self",
".",
"_state",
"==",
"Bundle",
".",
"ACTIVE",
"# Send the update event",
"self",
".",
"_fire_bundle_event",
"(",
"BundleEvent",
".",
"UPDATE... | 37.059524 | 18.464286 |
def search(self,q):
""" Search. """
import re
pattern = re.compile("%s" % q)
result = {}
for i in self.allstockno:
b = re.search(pattern, self.allstockno[i])
try:
b.group()
result[i] = self.allstockno[i]
except:
pass
return result | [
"def",
"search",
"(",
"self",
",",
"q",
")",
":",
"import",
"re",
"pattern",
"=",
"re",
".",
"compile",
"(",
"\"%s\"",
"%",
"q",
")",
"result",
"=",
"{",
"}",
"for",
"i",
"in",
"self",
".",
"allstockno",
":",
"b",
"=",
"re",
".",
"search",
"(",... | 20.285714 | 19.357143 |
def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query):
"""
Return the request params we would send to the api.
"""
url, params = self._prepare_request(command, query)
return {
"url": url, "params": params, "files": files, "stream": u... | [
"def",
"do",
"(",
"self",
",",
"command",
",",
"files",
"=",
"None",
",",
"use_long_polling",
"=",
"False",
",",
"request_timeout",
"=",
"None",
",",
"*",
"*",
"query",
")",
":",
"url",
",",
"params",
"=",
"self",
".",
"_prepare_request",
"(",
"command... | 47.7 | 24.9 |
def add_logging_parser(main_parser):
"Build an argparse argument parser to parse the command line."
main_parser.set_defaults(setup_logging=set_logging_level)
verbosity_group = main_parser.add_mutually_exclusive_group(required=False)
verbosity_group.add_argument(
'--verbose',
'-v',
... | [
"def",
"add_logging_parser",
"(",
"main_parser",
")",
":",
"main_parser",
".",
"set_defaults",
"(",
"setup_logging",
"=",
"set_logging_level",
")",
"verbosity_group",
"=",
"main_parser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
"False",
")",
"verbosi... | 33.88 | 22.52 |
def get_config(self):
"""Save configurations of metric. Can be recreated
from configs with metric.create(``**config``)
"""
config = self._kwargs.copy()
config.update({
'metric': self.__class__.__name__,
'name': self.name,
'output_names': self.o... | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"_kwargs",
".",
"copy",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'metric'",
":",
"self",
".",
"__class__",
".",
"__name__",
",",
"'name'",
":",
"self",
".",
"name",
",",
"... | 35.454545 | 9 |
def add(self, *args):
"""
This function adds strings to the keyboard, while not exceeding row_width.
E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]}
when row_width is set to 1.
When row_width is set to 2, the following is the r... | [
"def",
"add",
"(",
"self",
",",
"*",
"args",
")",
":",
"i",
"=",
"1",
"row",
"=",
"[",
"]",
"for",
"button",
"in",
"args",
":",
"row",
".",
"append",
"(",
"button",
".",
"to_dic",
"(",
")",
")",
"if",
"i",
"%",
"self",
".",
"row_width",
"==",... | 41.368421 | 19.894737 |
def _process_newline(self, char):
""" Process a newline character.
"""
state = self._state
# inside string, just append char to token
if state == self.ST_STRING:
self._token_chars.append(char)
else:
# otherwise, add new token
self... | [
"def",
"_process_newline",
"(",
"self",
",",
"char",
")",
":",
"state",
"=",
"self",
".",
"_state",
"# inside string, just append char to token",
"if",
"state",
"==",
"self",
".",
"ST_STRING",
":",
"self",
".",
"_token_chars",
".",
"append",
"(",
"char",
")",
... | 26.5 | 14.444444 |
def files_have_same_point_format_id(las_files):
""" Returns true if all the files have the same points format id
"""
point_format_found = {las.header.point_format_id for las in las_files}
return len(point_format_found) == 1 | [
"def",
"files_have_same_point_format_id",
"(",
"las_files",
")",
":",
"point_format_found",
"=",
"{",
"las",
".",
"header",
".",
"point_format_id",
"for",
"las",
"in",
"las_files",
"}",
"return",
"len",
"(",
"point_format_found",
")",
"==",
"1"
] | 47 | 8.4 |
def set_mask_selection(self, selection, value, fields=None):
"""Modify a selection of individual items, by providing a Boolean array of the
same shape as the array against which the selection is being made, where True
values indicate a selected item.
Parameters
----------
... | [
"def",
"set_mask_selection",
"(",
"self",
",",
"selection",
",",
"value",
",",
"fields",
"=",
"None",
")",
":",
"# guard conditions",
"if",
"self",
".",
"_read_only",
":",
"err_read_only",
"(",
")",
"# refresh metadata",
"if",
"not",
"self",
".",
"_cache_metad... | 32.648649 | 20.310811 |
def _compute_mean(self, C, g, mag, hypo_depth, dists, imt):
"""
Compute mean according to equation on Table 2, page 2275.
"""
delta = 0.00750 * 10 ** (0.507 * mag)
# computing R for different values of mag
if mag < 6.5:
R = np.sqrt(dists.rhypo ** 2 + delta *... | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"g",
",",
"mag",
",",
"hypo_depth",
",",
"dists",
",",
"imt",
")",
":",
"delta",
"=",
"0.00750",
"*",
"10",
"**",
"(",
"0.507",
"*",
"mag",
")",
"# computing R for different values of mag",
"if",
"mag",... | 28.166667 | 16.233333 |
def request_sensor_list(self, req, msg):
"""Request the list of sensors.
The list of sensors is sent as a sequence of #sensor-list informs.
Parameters
----------
name : str, optional
Name of the sensor to list (the default is to list all sensors).
If nam... | [
"def",
"request_sensor_list",
"(",
"self",
",",
"req",
",",
"msg",
")",
":",
"exact",
",",
"name_filter",
"=",
"construct_name_filter",
"(",
"msg",
".",
"arguments",
"[",
"0",
"]",
"if",
"msg",
".",
"arguments",
"else",
"None",
")",
"sensors",
"=",
"[",
... | 35.731343 | 23.014925 |
def get_vhost(self, name):
"""
Details about an individual vhost.
:param name: The vhost name
:type name: str
"""
return self._api_get('/api/vhosts/{0}'.format(
urllib.parse.quote_plus(name)
)) | [
"def",
"get_vhost",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_api_get",
"(",
"'/api/vhosts/{0}'",
".",
"format",
"(",
"urllib",
".",
"parse",
".",
"quote_plus",
"(",
"name",
")",
")",
")"
] | 25.3 | 12.3 |
def split_string(x: str, n: int) -> List[str]:
"""
Split string into chunks of length n
"""
# https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa
return [x[i:i+n] for i in range(0, len(x), n)] | [
"def",
"split_string",
"(",
"x",
":",
"str",
",",
"n",
":",
"int",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa",
"return",
"[",
"x",
"[",
"i",
":",
"i",
"+",
"n",
"]",
"for",
... | 40 | 11 |
def set_root(self, index):
"""Set the given index as root index of the combobox
:param index: the new root index
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None
"""
if not index.isValid():
self.setCurrentIndex(-1)
... | [
"def",
"set_root",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"self",
".",
"setCurrentIndex",
"(",
"-",
"1",
")",
"return",
"if",
"self",
".",
"model",
"(",
")",
"!=",
"index",
".",
"model",
"(",
")"... | 29.789474 | 9.842105 |
def convert_via_profile(self, data_np, order, inprof_name, outprof_name):
"""Convert the given RGB data from the working ICC profile
to the output profile in-place.
Parameters
----------
data_np : ndarray
RGB image data to be displayed.
order : str
... | [
"def",
"convert_via_profile",
"(",
"self",
",",
"data_np",
",",
"order",
",",
"inprof_name",
",",
"outprof_name",
")",
":",
"# get rest of necessary conversion parameters",
"to_intent",
"=",
"self",
".",
"t_",
".",
"get",
"(",
"'icc_output_intent'",
",",
"'perceptua... | 41.326087 | 23.173913 |
def saveXml(self, xml):
"""
Saves the settings for this edit to the xml parent.
:param xparent | <xml.etree.ElementTree>
"""
# save grouping
xtree = ElementTree.SubElement(xml, 'tree')
self.uiRecordTREE.saveXml(xtree)
# sav... | [
"def",
"saveXml",
"(",
"self",
",",
"xml",
")",
":",
"# save grouping\r",
"xtree",
"=",
"ElementTree",
".",
"SubElement",
"(",
"xml",
",",
"'tree'",
")",
"self",
".",
"uiRecordTREE",
".",
"saveXml",
"(",
"xtree",
")",
"# save the query\r",
"query",
"=",
"s... | 30.714286 | 15 |
def createdb(args):
"""
cldf createdb <DATASET> <SQLITE_DB_PATH>
Load CLDF dataset <DATASET> into a SQLite DB, where <DATASET> may be the path to
- a CLDF metadata file
- a CLDF core data file
"""
if len(args.args) < 2:
raise ParserError('not enough arguments')
ds = _get_dataset... | [
"def",
"createdb",
"(",
"args",
")",
":",
"if",
"len",
"(",
"args",
".",
"args",
")",
"<",
"2",
":",
"raise",
"ParserError",
"(",
"'not enough arguments'",
")",
"ds",
"=",
"_get_dataset",
"(",
"args",
")",
"db",
"=",
"Database",
"(",
"ds",
",",
"fnam... | 31.285714 | 15 |
def _pythonized_comments(tokens):
"""
Similar to tokens but converts strings after a colon (:) to comments.
"""
is_after_colon = True
for token_type, token_text in tokens:
if is_after_colon and (token_type in pygments.token.String):
token_type = pygments.token.Comment
eli... | [
"def",
"_pythonized_comments",
"(",
"tokens",
")",
":",
"is_after_colon",
"=",
"True",
"for",
"token_type",
",",
"token_text",
"in",
"tokens",
":",
"if",
"is_after_colon",
"and",
"(",
"token_type",
"in",
"pygments",
".",
"token",
".",
"String",
")",
":",
"to... | 39.6 | 10.8 |
def get_render_data(self, **kwargs):
"""
Because of the way mixin inheritance works
we can't have a default implementation of
get_context_data on the this class, so this
calls that method if available and returns
the resulting context.
"""
if hasattr(self,... | [
"def",
"get_render_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'get_context_data'",
")",
":",
"data",
"=",
"self",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"data",
"=",
"kwargs",... | 33.846154 | 10.153846 |
def value_counts(arg, metric_name='count'):
"""
Compute a frequency table for this value expression
Parameters
----------
Returns
-------
counts : TableExpr
Aggregated table
"""
base = ir.find_base_table(arg)
metric = base.count().name(metric_name)
try:
arg.g... | [
"def",
"value_counts",
"(",
"arg",
",",
"metric_name",
"=",
"'count'",
")",
":",
"base",
"=",
"ir",
".",
"find_base_table",
"(",
"arg",
")",
"metric",
"=",
"base",
".",
"count",
"(",
")",
".",
"name",
"(",
"metric_name",
")",
"try",
":",
"arg",
".",
... | 20.190476 | 19.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.