text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def iter_ensure_instance(iterable, types):
"""
Iterate over object and check each item type
>>> iter_ensure_instance([1,2,3], [str])
Traceback (most recent call last):
TypeError:
>>> iter_ensure_instance([1,2,3], int)
>>> iter_ensure_instance(1, int)
Traceback (most recent call last):
... | [
"def",
"iter_ensure_instance",
"(",
"iterable",
",",
"types",
")",
":",
"ensure_instance",
"(",
"iterable",
",",
"Iterable",
")",
"[",
"ensure_instance",
"(",
"item",
",",
"types",
")",
"for",
"item",
"in",
"iterable",
"]"
] | 30.428571 | 9.571429 |
def initialize(self, configfile=None):
"""Initialize and load the Fortran library (and model, if applicable).
The Fortran library is loaded and ctypes is used to annotate functions
inside the library. The Fortran library's initialization is called.
Normally a path to an ``*.ini`` model... | [
"def",
"initialize",
"(",
"self",
",",
"configfile",
"=",
"None",
")",
":",
"if",
"configfile",
"is",
"not",
"None",
":",
"self",
".",
"configfile",
"=",
"configfile",
"try",
":",
"self",
".",
"configfile",
"except",
"AttributeError",
":",
"raise",
"ValueE... | 43.628571 | 20.914286 |
def on_data(self, data):
"""
This is the function called by the handler object upon
receipt of incoming client data.
The data is passed to the responder's parser class (via the
:method:`consume` method), which digests and stores the HTTP
data.
Upon completion of ... | [
"def",
"on_data",
"(",
"self",
",",
"data",
")",
":",
"# Headers have not been read in yet",
"if",
"len",
"(",
"self",
".",
"headers",
")",
"==",
"0",
":",
"# forward data to the parser",
"data",
"=",
"self",
".",
"parser",
".",
"consume",
"(",
"data",
")",
... | 40.038462 | 23 |
def exponential_backoff(attempt: int, cap: int=1200) -> timedelta:
"""Calculate a delay to retry using an exponential backoff algorithm.
It is an exponential backoff with random jitter to prevent failures
from being retried at the same time. It is a good fit for most
applications.
:arg attempt: th... | [
"def",
"exponential_backoff",
"(",
"attempt",
":",
"int",
",",
"cap",
":",
"int",
"=",
"1200",
")",
"->",
"timedelta",
":",
"base",
"=",
"3",
"temp",
"=",
"min",
"(",
"base",
"*",
"2",
"**",
"attempt",
",",
"cap",
")",
"return",
"timedelta",
"(",
"... | 39.692308 | 19.846154 |
def _get_vlan_body_on_trunk_int(self, nexus_host, vlanid, intf_type,
interface, is_native, is_delete,
add_mode):
"""Prepares an XML snippet for VLAN on a trunk interface.
:param nexus_host: IP address of Nexus switch
:param... | [
"def",
"_get_vlan_body_on_trunk_int",
"(",
"self",
",",
"nexus_host",
",",
"vlanid",
",",
"intf_type",
",",
"interface",
",",
"is_native",
",",
"is_delete",
",",
"add_mode",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"LOG",
".",
"debug",
"(... | 36.333333 | 16.403509 |
def wash_for_xml(text, xml_version='1.0'):
"""Remove any character which isn't a allowed characters for XML.
The allowed characters depends on the version
of XML.
- XML 1.0:
<http://www.w3.org/TR/REC-xml/#charsets>
- XML 1.1:
<http://www.w3.org/TR/xml11/#charsets>
... | [
"def",
"wash_for_xml",
"(",
"text",
",",
"xml_version",
"=",
"'1.0'",
")",
":",
"if",
"xml_version",
"==",
"'1.0'",
":",
"return",
"RE_ALLOWED_XML_1_0_CHARS",
".",
"sub",
"(",
"''",
",",
"unicode",
"(",
"text",
",",
"'utf-8'",
")",
")",
".",
"encode",
"(... | 34 | 16.857143 |
def from_ligolw_table(cls, table, columns=None, cast_to_dtypes=None):
"""Converts the given ligolw table into an FieldArray. The `tableName`
attribute is copied to the array's `name`.
Parameters
----------
table : LIGOLw table instance
The table to convert.
c... | [
"def",
"from_ligolw_table",
"(",
"cls",
",",
"table",
",",
"columns",
"=",
"None",
",",
"cast_to_dtypes",
"=",
"None",
")",
":",
"name",
"=",
"table",
".",
"tableName",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"if",
"columns",
"is",
"None",
":",... | 41.788462 | 17.846154 |
def send(self, host_message_class, *args):
"""Send a host message.
:param type host_message_class: a subclass of
:class:`AYABImterface.communication.host_messages.Message`
:param args: additional arguments that shall be passed to the
:paramref:`host_message_class` as argumen... | [
"def",
"send",
"(",
"self",
",",
"host_message_class",
",",
"*",
"args",
")",
":",
"message",
"=",
"host_message_class",
"(",
"self",
".",
"_file",
",",
"self",
",",
"*",
"args",
")",
"with",
"self",
".",
"lock",
":",
"message",
".",
"send",
"(",
")"... | 39.615385 | 14.538462 |
def extract_iface_name_from_path(path, name):
"""
Extract the 'real' interface name from the path name. Basically this
puts the '@' back in the name in place of the underscore, where the name
contains a '.' or contains 'macvtap' or 'macvlan'.
Examples:
+------------------+-----------------+
... | [
"def",
"extract_iface_name_from_path",
"(",
"path",
",",
"name",
")",
":",
"if",
"name",
"in",
"path",
":",
"ifname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
".",
"split",
"(",
"\"_\"",
",",
"2",
")",
"[",
"-",
"1",
"]",
".",
"... | 38.36 | 12.68 |
def delete_webhook(self, policy, webhook):
"""
Deletes the specified webhook from the specified policy.
"""
return self.manager.delete_webhook(self, policy, webhook) | [
"def",
"delete_webhook",
"(",
"self",
",",
"policy",
",",
"webhook",
")",
":",
"return",
"self",
".",
"manager",
".",
"delete_webhook",
"(",
"self",
",",
"policy",
",",
"webhook",
")"
] | 38.6 | 10.2 |
def init(self):
"""
Initialize a new password db store
"""
self.y = {"version": int(time.time())}
recipient_email = raw_input("Enter Email ID: ")
self.import_key(emailid=recipient_email)
self.encrypt(emailid_list=[recipient_email]) | [
"def",
"init",
"(",
"self",
")",
":",
"self",
".",
"y",
"=",
"{",
"\"version\"",
":",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"}",
"recipient_email",
"=",
"raw_input",
"(",
"\"Enter Email ID: \"",
")",
"self",
".",
"import_key",
"(",
"emailid",... | 35 | 8.5 |
def create_build_context(self, variant, build_type, build_path):
"""Create a context to build the variant within."""
request = variant.get_requires(build_requires=True,
private_build_requires=True)
req_strs = map(str, request)
quoted_req_strs = map... | [
"def",
"create_build_context",
"(",
"self",
",",
"variant",
",",
"build_type",
",",
"build_path",
")",
":",
"request",
"=",
"variant",
".",
"get_requires",
"(",
"build_requires",
"=",
"True",
",",
"private_build_requires",
"=",
"True",
")",
"req_strs",
"=",
"m... | 40.166667 | 20.694444 |
def _normalize_histogram2d(self, counts, type):
"""Normalize the values of the counts for a 2D histogram.
This normalizes the values of a numpy array to the range 0-255.
:param counts: a NumPy array which is to be rescaled.
:param type: either 'bw' or 'reverse_bw'.
"""
... | [
"def",
"_normalize_histogram2d",
"(",
"self",
",",
"counts",
",",
"type",
")",
":",
"counts",
"=",
"(",
"255",
"*",
"(",
"counts",
"-",
"np",
".",
"nanmin",
"(",
"counts",
")",
")",
"/",
"(",
"np",
".",
"nanmax",
"(",
"counts",
")",
"-",
"np",
".... | 32.4375 | 19.8125 |
def parsesamplesheet(self):
"""Parses the sample sheet (SampleSheet.csv) to determine certain values
important for the creation of the assembly report"""
# Open the sample sheet
with open(self.samplesheet, "r") as samplesheet:
# Iterate through the sample sheet
sa... | [
"def",
"parsesamplesheet",
"(",
"self",
")",
":",
"# Open the sample sheet",
"with",
"open",
"(",
"self",
".",
"samplesheet",
",",
"\"r\"",
")",
"as",
"samplesheet",
":",
"# Iterate through the sample sheet",
"samples",
",",
"prev",
",",
"header",
"=",
"False",
... | 67.033898 | 28.050847 |
def debug_query(self, sql: str, *args) -> None:
"""Executes SQL and writes the result to the log."""
rows = self.fetchall(sql, *args)
debug_query_result(rows) | [
"def",
"debug_query",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"None",
":",
"rows",
"=",
"self",
".",
"fetchall",
"(",
"sql",
",",
"*",
"args",
")",
"debug_query_result",
"(",
"rows",
")"
] | 44.75 | 3.75 |
def max(x, y, context=None):
"""
Return the maximum of x and y.
If x and y are both NaN, return NaN. If exactly one of x and y is NaN,
return the non-NaN value. If x and y are zeros of different signs, return
+0.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr... | [
"def",
"max",
"(",
"x",
",",
"y",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_max",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
"BigFloat",
".",
"... | 24.611111 | 20.722222 |
def printdata(self) -> None:
""" Prints data to stdout """
np.set_printoptions(threshold=np.nan)
print(self.data)
np.set_printoptions(threshold=1000) | [
"def",
"printdata",
"(",
"self",
")",
"->",
"None",
":",
"np",
".",
"set_printoptions",
"(",
"threshold",
"=",
"np",
".",
"nan",
")",
"print",
"(",
"self",
".",
"data",
")",
"np",
".",
"set_printoptions",
"(",
"threshold",
"=",
"1000",
")"
] | 35.4 | 7.2 |
def _fluent_params(self, fluents, ordering) -> FluentParamsList:
'''Returns the instantiated `fluents` for the given `ordering`.
For each fluent in `fluents`, it instantiates each parameter
type w.r.t. the contents of the object table.
Returns:
Sequence[Tuple[str, List[str]... | [
"def",
"_fluent_params",
"(",
"self",
",",
"fluents",
",",
"ordering",
")",
"->",
"FluentParamsList",
":",
"variables",
"=",
"[",
"]",
"for",
"fluent_id",
"in",
"ordering",
":",
"fluent",
"=",
"fluents",
"[",
"fluent_id",
"]",
"param_types",
"=",
"fluent",
... | 41.807692 | 19.653846 |
def create_blueprint(self):
""" Create blueprint and register rules
:return: Blueprint of the current nemo app
:rtype: flask.Blueprint
"""
self.register_plugins()
self.blueprint = Blueprint(
self.name,
"nemo",
url_prefix=self.prefix,
... | [
"def",
"create_blueprint",
"(",
"self",
")",
":",
"self",
".",
"register_plugins",
"(",
")",
"self",
".",
"blueprint",
"=",
"Blueprint",
"(",
"self",
".",
"name",
",",
"\"nemo\"",
",",
"url_prefix",
"=",
"self",
".",
"prefix",
",",
"template_folder",
"=",
... | 35.745455 | 20.218182 |
def svdd(self, data: ['SASdata', str] = None,
code: str = None,
id: str = None,
input: [str, list, dict] = None,
kernel: str = None,
savestate: str = None,
solver: str = None,
weight: str = None,
procopts: str = None... | [
"def",
"svdd",
"(",
"self",
",",
"data",
":",
"[",
"'SASdata'",
",",
"str",
"]",
"=",
"None",
",",
"code",
":",
"str",
"=",
"None",
",",
"id",
":",
"str",
"=",
"None",
",",
"input",
":",
"[",
"str",
",",
"list",
",",
"dict",
"]",
"=",
"None",... | 51.965517 | 24.724138 |
def lparse(inlist, delim, nmax):
"""
Parse a list of items delimited by a single character.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lparse_c.html
:param inlist: list of items delimited by delim.
:type inlist: list
:param delim: Single character used to delimit items.
:type ... | [
"def",
"lparse",
"(",
"inlist",
",",
"delim",
",",
"nmax",
")",
":",
"delim",
"=",
"stypes",
".",
"stringToCharP",
"(",
"delim",
")",
"lenout",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"(",
"inlist",
")",
")",
"inlist",
"=",
"stypes",
".",
"stringToC... | 35.916667 | 15 |
def earthquake_contour_preprocessor(impact_function):
"""Preprocessor to create contour from an earthquake
:param impact_function: Impact function to run.
:type impact_function: ImpactFunction
:return: The contour layer.
:rtype: QgsMapLayer
"""
contour_path = create_smooth_contour(impact_f... | [
"def",
"earthquake_contour_preprocessor",
"(",
"impact_function",
")",
":",
"contour_path",
"=",
"create_smooth_contour",
"(",
"impact_function",
".",
"hazard",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"contour_path",
")",
":",
"from",
"safe",
".",
"gis... | 33.642857 | 16.285714 |
def models(self):
"""Return self.application models."""
Model_ = self.app.config['PEEWEE_MODELS_CLASS']
ignore = self.app.config['PEEWEE_MODELS_IGNORE']
models = []
if Model_ is not Model:
try:
mod = import_module(self.app.config['PEEWEE_MODELS_MODULE... | [
"def",
"models",
"(",
"self",
")",
":",
"Model_",
"=",
"self",
".",
"app",
".",
"config",
"[",
"'PEEWEE_MODELS_CLASS'",
"]",
"ignore",
"=",
"self",
".",
"app",
".",
"config",
"[",
"'PEEWEE_MODELS_IGNORE'",
"]",
"models",
"=",
"[",
"]",
"if",
"Model_",
... | 37.25 | 15.7 |
def simxGetObjectHandle(clientID, objectName, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
handle = ct.c_int()
if (sys.version_info[0] == 3) and (type(objectName) is str):
objectName=objectName.encode('utf-8')
return c_GetO... | [
"def",
"simxGetObjectHandle",
"(",
"clientID",
",",
"objectName",
",",
"operationMode",
")",
":",
"handle",
"=",
"ct",
".",
"c_int",
"(",
")",
"if",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
")",
"and",
"(",
"type",
"(",
"objectName",
... | 49.125 | 29.875 |
def _get_token(self, regex=None):
""" Consumes the next token in the token stream.
`regex`
Validate against the specified `re.compile()` regex instance.
Returns token string.
* Raises a ``ParseError`` exception if stream is empty or regex
matc... | [
"def",
"_get_token",
"(",
"self",
",",
"regex",
"=",
"None",
")",
":",
"item",
"=",
"self",
".",
"_lexer",
".",
"get_token",
"(",
")",
"if",
"not",
"item",
":",
"raise",
"ParseError",
"(",
"u'Unexpected end of file'",
")",
"else",
":",
"line_no",
",",
... | 31.875 | 22.333333 |
def decode_buffer(buffer: dict) -> np.ndarray:
"""
Translate a DataBuffer into a numpy array.
:param buffer: Dictionary with 'data' byte array, 'dtype', and 'shape' fields
:return: NumPy array of decoded data
"""
buf = np.frombuffer(buffer['data'], dtype=buffer['dtype'])
return buf.reshape(... | [
"def",
"decode_buffer",
"(",
"buffer",
":",
"dict",
")",
"->",
"np",
".",
"ndarray",
":",
"buf",
"=",
"np",
".",
"frombuffer",
"(",
"buffer",
"[",
"'data'",
"]",
",",
"dtype",
"=",
"buffer",
"[",
"'dtype'",
"]",
")",
"return",
"buf",
".",
"reshape",
... | 36.444444 | 12.888889 |
def opHaltStatus(symbol=None, token='', version=''):
'''The Exchange may suspend trading of one or more securities on IEX for operational reasons and indicates such operational halt using the Operational halt status message.
IEX disseminates a full pre-market spin of Operational halt status messages indicating... | [
"def",
"opHaltStatus",
"(",
"symbol",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"_raiseIfNotStr",
"(",
"symbol",
")",
"if",
"symbol",
":",
"return",
"_getJson",
"(",
"'deep/op-halt-status?symbols='",
"+",
"symbol",
",",
"to... | 56.869565 | 48.086957 |
def get_image(self):
"""
Gets first image from post set.
"""
posts_with_images = self.post_set.filter(image__gt='')
if posts_with_images:
return posts_with_images[0].image | [
"def",
"get_image",
"(",
"self",
")",
":",
"posts_with_images",
"=",
"self",
".",
"post_set",
".",
"filter",
"(",
"image__gt",
"=",
"''",
")",
"if",
"posts_with_images",
":",
"return",
"posts_with_images",
"[",
"0",
"]",
".",
"image"
] | 31.857143 | 8.142857 |
def maximum(lhs, rhs):
"""Returns element-wise maximum of the input arrays with broadcasting.
Equivalent to ``mx.nd.broadcast_maximum(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a com... | [
"def",
"maximum",
"(",
"lhs",
",",
"rhs",
")",
":",
"# pylint: disable= no-member, protected-access",
"return",
"_ufunc_helper",
"(",
"lhs",
",",
"rhs",
",",
"op",
".",
"broadcast_maximum",
",",
"lambda",
"x",
",",
"y",
":",
"x",
"if",
"x",
">",
"y",
"else... | 28.777778 | 17.537037 |
def _scale(self, mode):
"""
Returns value scaling coefficient for the given mode.
"""
if mode in self._mode_scale:
scale = self._mode_scale[mode]
else:
scale = 10**(-self.decimals)
self._mode_scale[mode] = scale
return scale | [
"def",
"_scale",
"(",
"self",
",",
"mode",
")",
":",
"if",
"mode",
"in",
"self",
".",
"_mode_scale",
":",
"scale",
"=",
"self",
".",
"_mode_scale",
"[",
"mode",
"]",
"else",
":",
"scale",
"=",
"10",
"**",
"(",
"-",
"self",
".",
"decimals",
")",
"... | 27.181818 | 12.090909 |
def getDataHandler(self, measurementId, deviceId):
"""
finds the handler.
:param measurementId: the measurement
:param deviceId: the device.
:return: active measurement and handler
"""
am = next((m for m in self.activeMeasurements if m.id == measurementId), None)
... | [
"def",
"getDataHandler",
"(",
"self",
",",
"measurementId",
",",
"deviceId",
")",
":",
"am",
"=",
"next",
"(",
"(",
"m",
"for",
"m",
"in",
"self",
".",
"activeMeasurements",
"if",
"m",
".",
"id",
"==",
"measurementId",
")",
",",
"None",
")",
"if",
"a... | 35.1875 | 13.0625 |
def fifo_async(wrst, rrst, wclk, rclk, wfull, we, wdata, rempty, re, rdata, depth=None, width=None):
''' Asynchronous FIFO
Implements the design described in:
Clifford E. Cummings, "Simulation and Synthesis Techniques for Asynchronous FIFO Design," SNUG 2002 (Synopsys
Users Group Co... | [
"def",
"fifo_async",
"(",
"wrst",
",",
"rrst",
",",
"wclk",
",",
"rclk",
",",
"wfull",
",",
"we",
",",
"wdata",
",",
"rempty",
",",
"re",
",",
"rdata",
",",
"depth",
"=",
"None",
",",
"width",
"=",
"None",
")",
":",
"if",
"(",
"width",
"==",
"N... | 37.067901 | 21.32716 |
def m_s(ms2, scale, f, alphasMZ=0.1185, loop=3):
r"""Get running s quark mass in the MSbar scheme at the scale `scale`
in the theory with `f` dynamical quark flavours starting from $m_s(2 \,\text{GeV})$"""
if scale == 2 and f == 3:
return ms2 # nothing to do
_sane(scale, f)
crd = rundec.CRu... | [
"def",
"m_s",
"(",
"ms2",
",",
"scale",
",",
"f",
",",
"alphasMZ",
"=",
"0.1185",
",",
"loop",
"=",
"3",
")",
":",
"if",
"scale",
"==",
"2",
"and",
"f",
"==",
"3",
":",
"return",
"ms2",
"# nothing to do",
"_sane",
"(",
"scale",
",",
"f",
")",
"... | 39.793103 | 17.965517 |
def _iter_descendants_levelorder(self, is_leaf_fn=None):
""" Iterate over all desdecendant nodes."""
tovisit = deque([self])
while len(tovisit) > 0:
node = tovisit.popleft()
yield node
if not is_leaf_fn or not is_leaf_fn(node):
tovisit.extend(n... | [
"def",
"_iter_descendants_levelorder",
"(",
"self",
",",
"is_leaf_fn",
"=",
"None",
")",
":",
"tovisit",
"=",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"len",
"(",
"tovisit",
")",
">",
"0",
":",
"node",
"=",
"tovisit",
".",
"popleft",
"(",
")",
"... | 40.75 | 9.375 |
def do_reload(self, args):
"""Reload a module in to the framework"""
if args.module is not None:
if args.module not in self.frmwk.modules:
self.print_error('Invalid Module Selected.')
return
module = self.frmwk.modules[args.module]
elif self.frmwk.current_module:
module = self.frmwk.current_modul... | [
"def",
"do_reload",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
".",
"module",
"is",
"not",
"None",
":",
"if",
"args",
".",
"module",
"not",
"in",
"self",
".",
"frmwk",
".",
"modules",
":",
"self",
".",
"print_error",
"(",
"'Invalid Module Select... | 31.153846 | 12.615385 |
def _post_query(self, **query_dict):
"""Perform a POST query against Solr and return the response as a Python
dict."""
param_dict = query_dict.copy()
return self._send_query(do_post=True, **param_dict) | [
"def",
"_post_query",
"(",
"self",
",",
"*",
"*",
"query_dict",
")",
":",
"param_dict",
"=",
"query_dict",
".",
"copy",
"(",
")",
"return",
"self",
".",
"_send_query",
"(",
"do_post",
"=",
"True",
",",
"*",
"*",
"param_dict",
")"
] | 45.8 | 5 |
def array_violations(array, events, slots, beta=None):
"""Take a schedule in array form and return any violated constraints
Parameters
----------
array : np.array
a schedule in array form
events : list or tuple
of resources.Event instances
slots : list or tup... | [
"def",
"array_violations",
"(",
"array",
",",
"events",
",",
"slots",
",",
"beta",
"=",
"None",
")",
":",
"return",
"(",
"c",
".",
"label",
"for",
"c",
"in",
"constraints",
".",
"all_constraints",
"(",
"events",
",",
"slots",
",",
"array",
",",
"beta",... | 29.192308 | 19 |
def deploy_api_gateway( self,
api_id,
stage_name,
stage_description="",
description="",
cache_cluster_enabled=False,
cache_cluster_size='0.5',
... | [
"def",
"deploy_api_gateway",
"(",
"self",
",",
"api_id",
",",
"stage_name",
",",
"stage_description",
"=",
"\"\"",
",",
"description",
"=",
"\"\"",
",",
"cache_cluster_enabled",
"=",
"False",
",",
"cache_cluster_size",
"=",
"'0.5'",
",",
"variables",
"=",
"None"... | 40.489362 | 18.191489 |
def capture_update_from_model(cls, table_name, record_id, *, update_fields=()):
"""
Create a fresh update record from the current model state in the database.
For read-write connected models, this will lead to the attempted update of the values of
a corresponding object in Salesforce.
... | [
"def",
"capture_update_from_model",
"(",
"cls",
",",
"table_name",
",",
"record_id",
",",
"*",
",",
"update_fields",
"=",
"(",
")",
")",
":",
"include_cols",
"=",
"(",
")",
"if",
"update_fields",
":",
"model_cls",
"=",
"get_connected_model_for_table_name",
"(",
... | 43.5 | 25.325 |
def tree(self):
"""
:rtype: cmdtree.tree.CmdTree
"""
from cmdtree.tree import CmdTree
if self._tree is None:
self._tree = CmdTree()
return self._tree | [
"def",
"tree",
"(",
"self",
")",
":",
"from",
"cmdtree",
".",
"tree",
"import",
"CmdTree",
"if",
"self",
".",
"_tree",
"is",
"None",
":",
"self",
".",
"_tree",
"=",
"CmdTree",
"(",
")",
"return",
"self",
".",
"_tree"
] | 25.25 | 7.5 |
def begin_span(self, name, span_type, context=None, leaf=False, tags=None):
"""
Begin a new span
:param name: name of the span
:param span_type: type of the span
:param context: a context dict
:param leaf: True if this is a leaf span
:param tags: a flat string/str... | [
"def",
"begin_span",
"(",
"self",
",",
"name",
",",
"span_type",
",",
"context",
"=",
"None",
",",
"leaf",
"=",
"False",
",",
"tags",
"=",
"None",
")",
":",
"return",
"self",
".",
"_begin_span",
"(",
"name",
",",
"span_type",
",",
"context",
"=",
"co... | 43.636364 | 14.181818 |
def ApprovalSymlinkUrnBuilder(approval_type, subject_id, user, approval_id):
"""Build an approval symlink URN."""
return aff4.ROOT_URN.Add("users").Add(user).Add("approvals").Add(
approval_type).Add(subject_id).Add(approval_id) | [
"def",
"ApprovalSymlinkUrnBuilder",
"(",
"approval_type",
",",
"subject_id",
",",
"user",
",",
"approval_id",
")",
":",
"return",
"aff4",
".",
"ROOT_URN",
".",
"Add",
"(",
"\"users\"",
")",
".",
"Add",
"(",
"user",
")",
".",
"Add",
"(",
"\"approvals\"",
")... | 60 | 20 |
def _return_rows(self, table, cols, values, return_type):
"""Return fetched rows in the desired type."""
if return_type is dict:
# Pack each row into a dictionary
cols = self.get_columns(table) if cols is '*' else cols
if len(values) > 0 and isinstance(values[0], (set... | [
"def",
"_return_rows",
"(",
"self",
",",
"table",
",",
"cols",
",",
"values",
",",
"return_type",
")",
":",
"if",
"return_type",
"is",
"dict",
":",
"# Pack each row into a dictionary",
"cols",
"=",
"self",
".",
"get_columns",
"(",
"table",
")",
"if",
"cols",... | 44.461538 | 15.692308 |
def push_url(interface):
'''
Decorates a function returning the url of translation API.
Creates and maintains HTTP connection state
Returns a dict response object from the server containing the translated
text and metadata of the request body
:param interface: Callable Request Interface
:t... | [
"def",
"push_url",
"(",
"interface",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"interface",
")",
"def",
"connection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Extends and wraps a HTTP interface.\n\n :return: Response Content\n ... | 31.305556 | 21.805556 |
def remove(self, steamid):
"""
Remove a friend
:param steamid: their steamid
:type steamid: :class:`int`, :class:`.SteamID`, :class:`.SteamUser`
"""
if isinstance(steamid, SteamUser):
steamid = steamid.steam_id
self._steam.send(MsgProto(EMsg.ClientRe... | [
"def",
"remove",
"(",
"self",
",",
"steamid",
")",
":",
"if",
"isinstance",
"(",
"steamid",
",",
"SteamUser",
")",
":",
"steamid",
"=",
"steamid",
".",
"steam_id",
"self",
".",
"_steam",
".",
"send",
"(",
"MsgProto",
"(",
"EMsg",
".",
"ClientRemoveFriend... | 31.363636 | 17.727273 |
def find_mature(x, y, win=10):
"""
Window apprach to find hills in the expression profile
"""
previous = min(y)
peaks = []
intervals = range(x, y, win)
for pos in intervals:
if y[pos] > previous * 10:
previous = y[pos]
peaks.add(pos)
peaks = _summarize_pea... | [
"def",
"find_mature",
"(",
"x",
",",
"y",
",",
"win",
"=",
"10",
")",
":",
"previous",
"=",
"min",
"(",
"y",
")",
"peaks",
"=",
"[",
"]",
"intervals",
"=",
"range",
"(",
"x",
",",
"y",
",",
"win",
")",
"for",
"pos",
"in",
"intervals",
":",
"i... | 26.5 | 11 |
def init_app(self, app):
""" Initialize the application and register the blueprint
:param app: Flask Application
:return: Blueprint of the current nemo app
:rtype: flask.Blueprint
"""
self.app = app
self.__blueprint__ = Blueprint(
self.__name__,
... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"app",
"=",
"app",
"self",
".",
"__blueprint__",
"=",
"Blueprint",
"(",
"self",
".",
"__name__",
",",
"self",
".",
"__name__",
",",
"url_prefix",
"=",
"self",
".",
"__prefix__",
",",
... | 28.64 | 15.52 |
def simple_lesk(context_sentence: str, ambiguous_word: str,
pos: str = None, lemma=True, stem=False, hyperhypo=True,
stop=True, context_is_lemmatized=False,
nbest=False, keepscore=False, normalizescore=False,
from_cache=True) -> "wn.Synset":
"""
Si... | [
"def",
"simple_lesk",
"(",
"context_sentence",
":",
"str",
",",
"ambiguous_word",
":",
"str",
",",
"pos",
":",
"str",
"=",
"None",
",",
"lemma",
"=",
"True",
",",
"stem",
"=",
"False",
",",
"hyperhypo",
"=",
"True",
",",
"stop",
"=",
"True",
",",
"co... | 51.666667 | 18.777778 |
def boundary_maximum_division(graph, xxx_todo_changeme5):
r"""
Boundary term processing adjacent voxels maximum value using a division relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
The same as `bound... | [
"def",
"boundary_maximum_division",
"(",
"graph",
",",
"xxx_todo_changeme5",
")",
":",
"(",
"gradient_image",
",",
"sigma",
",",
"spacing",
")",
"=",
"xxx_todo_changeme5",
"gradient_image",
"=",
"scipy",
".",
"asarray",
"(",
"gradient_image",
")",
"def",
"boundary... | 38.837209 | 22.534884 |
def RechazarCTG(self, carta_porte, ctg, motivo):
"El Destino puede rechazar el CTG a través de la siguiente operatoria"
response = self.client.rechazarCTG(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRep... | [
"def",
"RechazarCTG",
"(",
"self",
",",
"carta_porte",
",",
"ctg",
",",
"motivo",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"rechazarCTG",
"(",
"request",
"=",
"dict",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'s... | 50.705882 | 14.588235 |
def _connect(**kwargs):
'''
Initialise netscaler connection
'''
connargs = dict()
# Shamelessy ripped from the mysql module
def __connarg(name, key=None, default=None):
'''
Add key to connargs, only if name exists in our kwargs or as
netscaler.<name> in __opts__ or __pil... | [
"def",
"_connect",
"(",
"*",
"*",
"kwargs",
")",
":",
"connargs",
"=",
"dict",
"(",
")",
"# Shamelessy ripped from the mysql module",
"def",
"__connarg",
"(",
"name",
",",
"key",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"'''\n Add key to conn... | 34.772727 | 19 |
def histogram2d(x, y, bins, range, weights=None):
"""
Compute a 2D histogram assuming equally spaced bins.
Parameters
----------
x, y : `~numpy.ndarray`
The position of the points to bin in the 2D histogram
bins : int or iterable
The number of bins in each dimension. If given as... | [
"def",
"histogram2d",
"(",
"x",
",",
"y",
",",
"bins",
",",
"range",
",",
"weights",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"bins",
",",
"numbers",
".",
"Integral",
")",
":",
"nx",
"=",
"ny",
"=",
"bins",
"else",
":",
"nx",
",",
"ny",
... | 28.459016 | 22.491803 |
def add_line(preso, x1, y1, x2, y2, width="3pt", color="red"):
"""
Arrow pointing up to right:
context.xml:
office:automatic-styles/
<style:style style:name="gr1" style:family="graphic" style:parent-style-name="objectwithoutfill">
<style:graphic-properties
draw:marker-end="Arrow"
draw:... | [
"def",
"add_line",
"(",
"preso",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"width",
"=",
"\"3pt\"",
",",
"color",
"=",
"\"red\"",
")",
":",
"marker_end_ratio",
"=",
".459",
"/",
"3",
"# .459cm/3pt",
"marker_start_ratio",
"=",
".359",
"/",
"3",
... | 30.257143 | 19.028571 |
def _groups_or_na_fun(regex):
"""Used in both extract_noexpand and extract_frame"""
if regex.groups == 0:
raise ValueError("pattern contains no capture groups")
empty_row = [np.nan] * regex.groups
def f(x):
if not isinstance(x, str):
return empty_row
m = regex.search... | [
"def",
"_groups_or_na_fun",
"(",
"regex",
")",
":",
"if",
"regex",
".",
"groups",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"pattern contains no capture groups\"",
")",
"empty_row",
"=",
"[",
"np",
".",
"nan",
"]",
"*",
"regex",
".",
"groups",
"def",
"... | 30.4 | 18.466667 |
async def CharmInfo(self, url):
'''
url : str
Returns -> typing.Union[_ForwardRef('CharmActions'), typing.Mapping[str, ~CharmOption], _ForwardRef('CharmMeta'), _ForwardRef('CharmMetrics'), int, str]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type... | [
"async",
"def",
"CharmInfo",
"(",
"self",
",",
"url",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Charms'",
",",
"request",
"=",
"'CharmInfo'",
",",
"version",
"=",
"2",
",",
"params... | 36.285714 | 20.857143 |
def pass_multipart(with_completed=False):
"""Decorate to retrieve an object."""
def decorate(f):
@wraps(f)
def inner(self, bucket, key, upload_id, *args, **kwargs):
obj = MultipartObject.get(
bucket, key, upload_id, with_completed=with_completed)
if obj is... | [
"def",
"pass_multipart",
"(",
"with_completed",
"=",
"False",
")",
":",
"def",
"decorate",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"upload_id",
",",
"*",
"args",
",",
"*",
"*",
... | 38.416667 | 14.833333 |
def render_image(self, rgbobj, dst_x, dst_y):
"""Render the image represented by (rgbobj) at dst_x, dst_y
in the pixel space.
*** internal method-- do not use ***
"""
if self.surface is None:
return
self.logger.debug("redraw surface")
# get window con... | [
"def",
"render_image",
"(",
"self",
",",
"rgbobj",
",",
"dst_x",
",",
"dst_y",
")",
":",
"if",
"self",
".",
"surface",
"is",
"None",
":",
"return",
"self",
".",
"logger",
".",
"debug",
"(",
"\"redraw surface\"",
")",
"# get window contents as a buffer and load... | 40.307692 | 13.384615 |
def num_discarded(self):
"""Get the number of values discarded due to exceeding both limits."""
if not self._data:
return 0
n = 0
while n < len(self._data):
if not isinstance(self._data[n], _TensorValueDiscarded):
break
n += 1
return n | [
"def",
"num_discarded",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_data",
":",
"return",
"0",
"n",
"=",
"0",
"while",
"n",
"<",
"len",
"(",
"self",
".",
"_data",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_data",
"[",
"n",
... | 27.2 | 20.6 |
def migrate(self, expression, name_migration_map=None):
""" Migrate an expression created for a different constraint set to self.
Returns an expression that can be used with this constraintSet
All the foreign variables used in the expression are replaced by
variables of this... | [
"def",
"migrate",
"(",
"self",
",",
"expression",
",",
"name_migration_map",
"=",
"None",
")",
":",
"if",
"name_migration_map",
"is",
"None",
":",
"name_migration_map",
"=",
"{",
"}",
"# name_migration_map -> object_migration_map",
"# Based on the name mapping in name_m... | 60.389831 | 31.779661 |
def get_rating_for_user(self, user, ip_address=None, cookies={}):
"""get_rating_for_user(user, ip_address=None, cookie=None)
Returns the rating for a user or anonymous IP."""
kwargs = dict(
content_type = self.get_content_type(),
object_id = self.instanc... | [
"def",
"get_rating_for_user",
"(",
"self",
",",
"user",
",",
"ip_address",
"=",
"None",
",",
"cookies",
"=",
"{",
"}",
")",
":",
"kwargs",
"=",
"dict",
"(",
"content_type",
"=",
"self",
".",
"get_content_type",
"(",
")",
",",
"object_id",
"=",
"self",
... | 38.055556 | 18.916667 |
def vprjp(vin, plane):
"""
Project a vector onto a specified plane, orthogonally.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vprjp_c.html
:param vin: The projected vector.
:type vin: 3-Element Array of floats
:param plane: Plane containing vin.
:type plane: spiceypy.utils.su... | [
"def",
"vprjp",
"(",
"vin",
",",
"plane",
")",
":",
"vin",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"vin",
")",
"vout",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"3",
")",
"libspice",
".",
"vprjp_c",
"(",
"vin",
",",
"ctypes",
".",
"byref",
"("... | 34.294118 | 11.117647 |
def to_normalized_batch(self):
"""Convert this unnormalized batch to an instance of Batch.
As this method is intended to be called before augmentation, it
assumes that none of the ``*_aug`` attributes is yet set.
It will produce an AssertionError otherwise.
The newly created Ba... | [
"def",
"to_normalized_batch",
"(",
"self",
")",
":",
"assert",
"all",
"(",
"[",
"attr",
"is",
"None",
"for",
"attr_name",
",",
"attr",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"attr_name",
".",
"endswith",
"(",
"\"_aug\"",
")",
"]",... | 39.568182 | 19.113636 |
def _find_combo_data(widget, value):
"""
Returns the index in a combo box where itemData == value
Raises a ValueError if data is not found
"""
# Here we check that the result is True, because some classes may overload
# == and return other kinds of objects whether true or false.
for idx in ... | [
"def",
"_find_combo_data",
"(",
"widget",
",",
"value",
")",
":",
"# Here we check that the result is True, because some classes may overload",
"# == and return other kinds of objects whether true or false.",
"for",
"idx",
"in",
"range",
"(",
"widget",
".",
"count",
"(",
")",
... | 39.461538 | 19.307692 |
def SecondsToZuluTS(secs=None):
"""Returns Zulu TS from unix time seconds.
If secs is not provided will convert the current time.
"""
if not secs: secs = int(time.time())
return(datetime.utcfromtimestamp(secs).strftime("%Y-%m-%dT%H:%M:%SZ")) | [
"def",
"SecondsToZuluTS",
"(",
"secs",
"=",
"None",
")",
":",
"if",
"not",
"secs",
":",
"secs",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"return",
"(",
"datetime",
".",
"utcfromtimestamp",
"(",
"secs",
")",
".",
"strftime",
"(",
"\"%Y-%m-... | 26.888889 | 19.666667 |
def seek(self, position, modifier=0):
"""move the cursor on the file descriptor to a different location
:param position:
an integer offset from the location indicated by the modifier
:type position: int
:param modifier:
an indicator of how to find the seek locati... | [
"def",
"seek",
"(",
"self",
",",
"position",
",",
"modifier",
"=",
"0",
")",
":",
"os",
".",
"lseek",
"(",
"self",
".",
"_fileno",
",",
"position",
",",
"modifier",
")",
"# clear out the buffer",
"buf",
"=",
"self",
".",
"_rbuf",
"buf",
".",
"seek",
... | 34.47619 | 20.285714 |
def handle_inform(self, msg):
"""Dispatch an inform message to the appropriate method.
Parameters
----------
msg : Message object
The inform message to dispatch.
"""
method = self._inform_handlers.get(
msg.name, self.__class__.unhandled_inform)
... | [
"def",
"handle_inform",
"(",
"self",
",",
"msg",
")",
":",
"method",
"=",
"self",
".",
"_inform_handlers",
".",
"get",
"(",
"msg",
".",
"name",
",",
"self",
".",
"__class__",
".",
"unhandled_inform",
")",
"try",
":",
"return",
"method",
"(",
"self",
",... | 32.578947 | 17.473684 |
def subvolume_created(name, device, qgroupids=None, set_default=False,
copy_on_write=True, force_set_default=True,
__dest=None):
'''
Makes sure that a btrfs subvolume is present.
name
Name of the subvolume to add
device
Device where to create... | [
"def",
"subvolume_created",
"(",
"name",
",",
"device",
",",
"qgroupids",
"=",
"None",
",",
"set_default",
"=",
"False",
",",
"copy_on_write",
"=",
"True",
",",
"force_set_default",
"=",
"True",
",",
"__dest",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'na... | 32.602564 | 24.602564 |
def avhrr(scans_nb, scan_points,
scan_angle=55.37, frequency=1 / 6.0, apply_offset=True):
"""Definition of the avhrr instrument.
Source: NOAA KLM User's Guide, Appendix J
http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/klm/html/j/app-j.htm
"""
# build the avhrr instrument (scan angles)
... | [
"def",
"avhrr",
"(",
"scans_nb",
",",
"scan_points",
",",
"scan_angle",
"=",
"55.37",
",",
"frequency",
"=",
"1",
"/",
"6.0",
",",
"apply_offset",
"=",
"True",
")",
":",
"# build the avhrr instrument (scan angles)",
"avhrr_inst",
"=",
"np",
".",
"vstack",
"(",... | 38 | 18.68 |
def _heapqmergesorted(key=None, *iterables):
"""Return a single iterator over the given iterables, sorted by the
given `key` function, assuming the input iterables are already sorted by
the same function. (I.e., the merge part of a general merge sort.) Uses
:func:`heapq.merge` for the underlying impleme... | [
"def",
"_heapqmergesorted",
"(",
"key",
"=",
"None",
",",
"*",
"iterables",
")",
":",
"if",
"key",
"is",
"None",
":",
"keyed_iterables",
"=",
"iterables",
"for",
"element",
"in",
"heapq",
".",
"merge",
"(",
"*",
"keyed_iterables",
")",
":",
"yield",
"ele... | 44.866667 | 17.8 |
def lstm_cell(x, h, c, state_size, w_init=None, b_init=None, fix_parameters=False):
"""Long Short-Term Memory.
Long Short-Term Memory, or LSTM, is a building block for recurrent neural networks (RNN) layers.
LSTM unit consists of a cell and input, output, forget gates whose functions are defined as followi... | [
"def",
"lstm_cell",
"(",
"x",
",",
"h",
",",
"c",
",",
"state_size",
",",
"w_init",
"=",
"None",
",",
"b_init",
"=",
"None",
",",
"fix_parameters",
"=",
"False",
")",
":",
"xh",
"=",
"F",
".",
"concatenate",
"(",
"*",
"(",
"x",
",",
"h",
")",
"... | 50.179487 | 35.589744 |
def _getContextFactory(path, workbench):
"""Get a context factory.
If the client already has a credentials at path, use them.
Otherwise, generate them at path. Notifications are reported to
the given workbench.
"""
try:
return succeed(getContextFactory(path))
except IOError:
... | [
"def",
"_getContextFactory",
"(",
"path",
",",
"workbench",
")",
":",
"try",
":",
"return",
"succeed",
"(",
"getContextFactory",
"(",
"path",
")",
")",
"except",
"IOError",
":",
"d",
"=",
"prompt",
"(",
"workbench",
",",
"u\"E-mail entry\"",
",",
"u\"Enter e... | 33.4 | 19.4 |
def _prop0(self, rho, T):
"""Ideal gas properties"""
rhoc = self._constants.get("rhoref", self.rhoc)
Tc = self._constants.get("Tref", self.Tc)
delta = rho/rhoc
tau = Tc/T
ideal = self._phi0(tau, delta)
fio = ideal["fio"]
fiot = ideal["fiot"]
fiott ... | [
"def",
"_prop0",
"(",
"self",
",",
"rho",
",",
"T",
")",
":",
"rhoc",
"=",
"self",
".",
"_constants",
".",
"get",
"(",
"\"rhoref\"",
",",
"self",
".",
"rhoc",
")",
"Tc",
"=",
"self",
".",
"_constants",
".",
"get",
"(",
"\"Tref\"",
",",
"self",
".... | 33.052632 | 11.684211 |
def write_file(self, file):
"""
Writes the editor file content into given file.
:param file: File to write.
:type file: unicode
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Writing '{0}' file.".format(file))
writer = foundations.io.F... | [
"def",
"write_file",
"(",
"self",
",",
"file",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Writing '{0}' file.\"",
".",
"format",
"(",
"file",
")",
")",
"writer",
"=",
"foundations",
".",
"io",
".",
"File",
"(",
"file",
")",
"writer",
".",
"content",
"... | 27 | 15.222222 |
def parse_argv(tokens, options, options_first=False):
"""Parse command-line argument vector.
If options_first:
argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
else:
argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
"""
parsed = []
while tokens.c... | [
"def",
"parse_argv",
"(",
"tokens",
",",
"options",
",",
"options_first",
"=",
"False",
")",
":",
"parsed",
"=",
"[",
"]",
"while",
"tokens",
".",
"current",
"(",
")",
"is",
"not",
"None",
":",
"if",
"tokens",
".",
"current",
"(",
")",
"==",
"'--'",
... | 37.590909 | 19.272727 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# extracting dictionary of coefficients specific to required",
"# intensity measure type.",
"C",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"... | 44.176471 | 15.647059 |
def metadata_wrapper(fn):
"""Save metadata of last api call."""
@functools.wraps(fn)
def wrapped_f(self, *args, **kwargs):
self.last_metadata = {}
self.last_metadata["url"] = self.configuration.host + args[0]
self.last_metadata["method"] = args[1]
... | [
"def",
"metadata_wrapper",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapped_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"last_metadata",
"=",
"{",
"}",
"self",
".",
"last_me... | 39.428571 | 12.928571 |
def update(self, claim, ttl=None, grace=None):
"""
Updates the specified claim with either a new TTL or grace period, or
both.
"""
body = {}
if ttl is not None:
body["ttl"] = ttl
if grace is not None:
body["grace"] = grace
if not bo... | [
"def",
"update",
"(",
"self",
",",
"claim",
",",
"ttl",
"=",
"None",
",",
"grace",
"=",
"None",
")",
":",
"body",
"=",
"{",
"}",
"if",
"ttl",
"is",
"not",
"None",
":",
"body",
"[",
"\"ttl\"",
"]",
"=",
"ttl",
"if",
"grace",
"is",
"not",
"None",... | 38.333333 | 17.133333 |
def move(self, dst):
"Closes then moves the file to dst."
self.close()
shutil.move(self.path, dst) | [
"def",
"move",
"(",
"self",
",",
"dst",
")",
":",
"self",
".",
"close",
"(",
")",
"shutil",
".",
"move",
"(",
"self",
".",
"path",
",",
"dst",
")"
] | 29.75 | 12.25 |
def create_service_module(service_name, apis):
"""
Dynamically creates a module named defined by the PEP-8 version of
the string contained in service_name (from the YAML config). This
module will contain a Client class, a Call Factory, and list of API
definition objects.
"""
service_module = imp.ne... | [
"def",
"create_service_module",
"(",
"service_name",
",",
"apis",
")",
":",
"service_module",
"=",
"imp",
".",
"new_module",
"(",
"service_name",
".",
"lower",
"(",
")",
")",
"for",
"api",
"in",
"apis",
":",
"setattr",
"(",
"service_module",
",",
"api",
".... | 34.684211 | 20.894737 |
def node_assign(self, node, val):
"""Assign a value (not the node.value object) to a node.
This is used by on_assign, but also by for, list comprehension,
etc.
"""
if node.__class__ == ast.Name:
if not valid_symbol_name(node.id) or node.id in self.readonly_symbols:
... | [
"def",
"node_assign",
"(",
"self",
",",
"node",
",",
"val",
")",
":",
"if",
"node",
".",
"__class__",
"==",
"ast",
".",
"Name",
":",
"if",
"not",
"valid_symbol_name",
"(",
"node",
".",
"id",
")",
"or",
"node",
".",
"id",
"in",
"self",
".",
"readonl... | 41.918919 | 16.972973 |
def insert_weave_option_group(parser):
"""
Adds the options used to specify weave options.
Parameters
----------
parser : object
OptionParser instance
"""
optimization_group = parser.add_argument_group("Options for controlling "
"weave")
optim... | [
"def",
"insert_weave_option_group",
"(",
"parser",
")",
":",
"optimization_group",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"Options for controlling \"",
"\"weave\"",
")",
"optimization_group",
".",
"add_argument",
"(",
"\"--per-process-weave-cache\"",
",",
"action"... | 40.72973 | 18.108108 |
def encode(self, *args):
"""encode(value1[, ...]) -> bytes
Encodes the given values to a sequence of bytes according to this
Array's underlying element type
"""
if len(args) != self.nelems:
msg = 'ArrayType %s encode() requires %d values, but received %d.'
... | [
"def",
"encode",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"self",
".",
"nelems",
":",
"msg",
"=",
"'ArrayType %s encode() requires %d values, but received %d.'",
"raise",
"ValueError",
"(",
"msg",
"%",
"(",
"self",
".",
... | 40.272727 | 21.181818 |
def get_hash_for(self, value):
"""Get hash for a given value.
:param value: The value to be indexed
:type value: object
:return: Hashed value
:rtype: str
"""
if isinstance(value,dict) and '__ref__' in value:
return self.get_hash_for(value['__ref__'])... | [
"def",
"get_hash_for",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"'__ref__'",
"in",
"value",
":",
"return",
"self",
".",
"get_hash_for",
"(",
"value",
"[",
"'__ref__'",
"]",
")",
"serialized_value",
"... | 35.833333 | 15.708333 |
def setitem(self, key, value):
"""Maps dictionary keys to values for assignment. Called for
dictionary style access with assignment.
"""
with self.lock:
self.tbl[key] = value | [
"def",
"setitem",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"tbl",
"[",
"key",
"]",
"=",
"value"
] | 35.666667 | 7 |
def add_load(self, lv_load):
"""Adds a LV load to _loads and grid graph if not already existing
Parameters
----------
lv_load :
Description #TODO
"""
if lv_load not in self._loads and isinstance(lv_load,
... | [
"def",
"add_load",
"(",
"self",
",",
"lv_load",
")",
":",
"if",
"lv_load",
"not",
"in",
"self",
".",
"_loads",
"and",
"isinstance",
"(",
"lv_load",
",",
"LVLoadDing0",
")",
":",
"self",
".",
"_loads",
".",
"append",
"(",
"lv_load",
")",
"self",
".",
... | 34.166667 | 14.083333 |
def start_heartbeat(self):
""" Reset hearbeat timer """
self.stop_heartbeat()
self._heartbeat_timer = task.LoopingCall(self._heartbeat)
self._heartbeat_timer.start(self._heartbeat_interval, False) | [
"def",
"start_heartbeat",
"(",
"self",
")",
":",
"self",
".",
"stop_heartbeat",
"(",
")",
"self",
".",
"_heartbeat_timer",
"=",
"task",
".",
"LoopingCall",
"(",
"self",
".",
"_heartbeat",
")",
"self",
".",
"_heartbeat_timer",
".",
"start",
"(",
"self",
"."... | 37.333333 | 19.666667 |
def ra_dec_to_cartesian(
self,
ra,
dec):
"""*Convert an RA, DEC coordinate set to x, y, z cartesian coordinates*
**Key Arguments:**
- ``ra`` -- right ascension in sexegesimal or decimal degress.
- ``dec`` -- declination in sexegesimal or decim... | [
"def",
"ra_dec_to_cartesian",
"(",
"self",
",",
"ra",
",",
"dec",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``ra_dec_to_cartesian`` method'",
")",
"ra",
"=",
"self",
".",
"ra_sexegesimal_to_decimal",
"(",
"ra",
"=",
"ra",
")",
"dec",
"="... | 28 | 21.849057 |
def delete_company(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes specified company.
Prerequisite: The company has no jobs associated with it.
Example:... | [
"def",
"delete_company",
"(",
"self",
",",
"name",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadat... | 41.586207 | 23.827586 |
def run(self):
"""
This method is the actual implementation of the job. By default, it calls
the target function specified in the #Job constructor.
"""
if self.__target is not None:
return self.__target(self, *self.__args, **self.__kwargs)
raise NotImplementedError | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"__target",
"is",
"not",
"None",
":",
"return",
"self",
".",
"__target",
"(",
"self",
",",
"*",
"self",
".",
"__args",
",",
"*",
"*",
"self",
".",
"__kwargs",
")",
"raise",
"NotImplementedError"... | 32 | 18 |
def start(self):
"""Start the app"""
if self.args.debug:
self.app.run(port=self.args.port, debug=self.args.debug, host=self.args.interface)
else:
root = "http://%s:%s" % (self.args.interface, self.args.port)
print("tornado web server running on " + root)
... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"args",
".",
"debug",
":",
"self",
".",
"app",
".",
"run",
"(",
"port",
"=",
"self",
".",
"args",
".",
"port",
",",
"debug",
"=",
"self",
".",
"args",
".",
"debug",
",",
"host",
"=",
"... | 49.071429 | 24.857143 |
def find_contamination(pair, output_folder, databases_folder, forward_id='_R1', threads=1, keep_files=False,
quality_cutoff=20, base_cutoff=2, base_fraction_cutoff=0.05, cgmlst_db=None, Xmx=None, tmpdir=None,
data_type='Illumina', use_rmlst=False):
"""
This needs so... | [
"def",
"find_contamination",
"(",
"pair",
",",
"output_folder",
",",
"databases_folder",
",",
"forward_id",
"=",
"'_R1'",
",",
"threads",
"=",
"1",
",",
"keep_files",
"=",
"False",
",",
"quality_cutoff",
"=",
"20",
",",
"base_cutoff",
"=",
"2",
",",
"base_fr... | 62.368571 | 34.414286 |
def _matrix_add_column(matrix, column, default=0):
"""Given a matrix as a list of lists, add a column to the right, filling in
with a default value if necessary.
"""
height_difference = len(column) - len(matrix)
# The width of the matrix is the length of its longest row.
width = max(len(row) fo... | [
"def",
"_matrix_add_column",
"(",
"matrix",
",",
"column",
",",
"default",
"=",
"0",
")",
":",
"height_difference",
"=",
"len",
"(",
"column",
")",
"-",
"len",
"(",
"matrix",
")",
"# The width of the matrix is the length of its longest row.",
"width",
"=",
"max",
... | 35.46875 | 18.09375 |
def check(self, url_data):
"""Parse PDF data."""
# XXX user authentication from url_data
password = ''
data = url_data.get_content()
# PDFParser needs a seekable file object
fp = StringIO(data)
try:
parser = PDFParser(fp)
doc = PDFDocument(... | [
"def",
"check",
"(",
"self",
",",
"url_data",
")",
":",
"# XXX user authentication from url_data",
"password",
"=",
"''",
"data",
"=",
"url_data",
".",
"get_content",
"(",
")",
"# PDFParser needs a seekable file object",
"fp",
"=",
"StringIO",
"(",
"data",
")",
"t... | 43.25 | 14.8 |
def echo_html_fenye_str(rec_num, fenye_num):
'''
生成分页的导航
'''
pagination_num = int(math.ceil(rec_num * 1.0 / 10))
if pagination_num == 1 or pagination_num == 0:
fenye_str = ''
elif pagination_num > 1:
pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''... | [
"def",
"echo_html_fenye_str",
"(",
"rec_num",
",",
"fenye_num",
")",
":",
"pagination_num",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"rec_num",
"*",
"1.0",
"/",
"10",
")",
")",
"if",
"pagination_num",
"==",
"1",
"or",
"pagination_num",
"==",
"0",
":",
... | 32.907407 | 26.092593 |
def _keep_cursor_in_buffer(self):
""" Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved.
"""
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)... | [
"def",
"_keep_cursor_in_buffer",
"(",
"self",
")",
":",
"moved",
"=",
"not",
"self",
".",
"_in_buffer",
"(",
")",
"if",
"moved",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
... | 38 | 8.2 |
def mark_seen(self):
"""
Mark the selected message or comment as seen.
"""
data = self.get_selected_item()
if data['is_new']:
with self.term.loader('Marking as read'):
data['object'].mark_as_read()
if not self.term.loader.exception:
... | [
"def",
"mark_seen",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"get_selected_item",
"(",
")",
"if",
"data",
"[",
"'is_new'",
"]",
":",
"with",
"self",
".",
"term",
".",
"loader",
"(",
"'Marking as read'",
")",
":",
"data",
"[",
"'object'",
"]",
... | 36 | 8.8 |
def __get_settings(self):
"""
Returns the current search and replace settings.
:return: Settings.
:rtype: dict
"""
return {"case_sensitive": self.Case_Sensitive_checkBox.isChecked(),
"whole_word": self.Whole_Word_checkBox.isChecked(),
"re... | [
"def",
"__get_settings",
"(",
"self",
")",
":",
"return",
"{",
"\"case_sensitive\"",
":",
"self",
".",
"Case_Sensitive_checkBox",
".",
"isChecked",
"(",
")",
",",
"\"whole_word\"",
":",
"self",
".",
"Whole_Word_checkBox",
".",
"isChecked",
"(",
")",
",",
"\"re... | 34.181818 | 22.909091 |
def knx_to_datetime(knxdata):
"""Convert a an 8 byte KNX time and date object to its components"""
if len(knxdata) != 8:
raise KNXException("Can only convert an 8 Byte object to datetime")
year = knxdata[0] + 1900
month = knxdata[1]
day = knxdata[2]
hour = knxdata[3] & 0x1f
minute ... | [
"def",
"knx_to_datetime",
"(",
"knxdata",
")",
":",
"if",
"len",
"(",
"knxdata",
")",
"!=",
"8",
":",
"raise",
"KNXException",
"(",
"\"Can only convert an 8 Byte object to datetime\"",
")",
"year",
"=",
"knxdata",
"[",
"0",
"]",
"+",
"1900",
"month",
"=",
"k... | 28.857143 | 21.142857 |
def from_xso(self, xso):
"""
Construct and return an instance from the given `xso`.
.. note::
This is a static method (classmethod), even though sphinx does not
document it as such.
:param xso: A :xep:`4` data form
:type xso: :class:`~.Data`
:rais... | [
"def",
"from_xso",
"(",
"self",
",",
"xso",
")",
":",
"my_form_type",
"=",
"getattr",
"(",
"self",
",",
"\"FORM_TYPE\"",
",",
"None",
")",
"f",
"=",
"self",
"(",
")",
"for",
"field",
"in",
"xso",
".",
"fields",
":",
"if",
"field",
".",
"var",
"==",... | 37.090909 | 21.844156 |
def post_chat(self, msg, is_me=False, is_a=False):
"""Posts a msg to this room's chat. Set me=True if you want to /me"""
if len(msg) > self.config.max_message:
raise ValueError(
f"Chat message must be at most {self.config.max_message} characters."
)
while... | [
"def",
"post_chat",
"(",
"self",
",",
"msg",
",",
"is_me",
"=",
"False",
",",
"is_a",
"=",
"False",
")",
":",
"if",
"len",
"(",
"msg",
")",
">",
"self",
".",
"config",
".",
"max_message",
":",
"raise",
"ValueError",
"(",
"f\"Chat message must be at most ... | 40.35 | 20.3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.