text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def do_alarm_history_list(mc, args):
'''List alarms state history.'''
fields = {}
if args.dimensions:
fields['dimensions'] = utils.format_parameters(args.dimensions)
if args.starttime:
_translate_starttime(args)
fields['start_time'] = args.starttime
if args.endtime:
f... | [
"def",
"do_alarm_history_list",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"if",
"args",
".",
"dimensions",
":",
"fields",
"[",
"'dimensions'",
"]",
"=",
"utils",
".",
"format_parameters",
"(",
"args",
".",
"dimensions",
")",
"if",
"args"... | 34.55 | 0.001408 |
def dateAt( self, point ):
"""
Returns the date at the given point.
:param point | <QPoint>
"""
for date, data in self._dateGrid.items():
if ( data[1].contains(point) ):
return QDate.fromJulianDay(date)
return QDate() | [
"def",
"dateAt",
"(",
"self",
",",
"point",
")",
":",
"for",
"date",
",",
"data",
"in",
"self",
".",
"_dateGrid",
".",
"items",
"(",
")",
":",
"if",
"(",
"data",
"[",
"1",
"]",
".",
"contains",
"(",
"point",
")",
")",
":",
"return",
"QDate",
".... | 30.7 | 0.022152 |
def live(self, url, resource_class, resource_args, params=None):
"""Get a live endpoint.
Args:
url(string): URL for the request
resource_class(class): The class to use for entries coming
from the live endpoint.
resource_args(dict): Additional argum... | [
"def",
"live",
"(",
"self",
",",
"url",
",",
"resource_class",
",",
"resource_args",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"adapter",
".",
"live",
"(",
"self",
",",
"url",
",",
"resource_class",
",",
"resource_args",
",",
"params",... | 31.407407 | 0.002288 |
def add_filter_function(self, name, new_function):
"""
name : hashable object
The object to be used as the key for
this filter function. Use this object
to remove the filter function in the future.
Typically this is a self descriptive string.
new_... | [
"def",
"add_filter_function",
"(",
"self",
",",
"name",
",",
"new_function",
")",
":",
"self",
".",
"_filter_functions",
"[",
"name",
"]",
"=",
"new_function",
"self",
".",
"invalidateFilter",
"(",
")"
] | 38.285714 | 0.002427 |
def equals_as(self, value_type, other):
"""
Compares this object value to specified specified value.
When direct comparison gives negative results it converts
values to type specified by type code and compare them again.
:param value_type: the Typecode type that defined the type... | [
"def",
"equals_as",
"(",
"self",
",",
"value_type",
",",
"other",
")",
":",
"if",
"other",
"==",
"None",
"and",
"self",
".",
"value",
"==",
"None",
":",
"return",
"True",
"if",
"other",
"==",
"None",
"or",
"self",
".",
"value",
"==",
"None",
":",
"... | 31.633333 | 0.010225 |
def betting_market_rules_update(
self, rules_id, names, descriptions, account=None, **kwargs
):
""" Update betting market rules
:param str rules_id: Id of the betting market rules to update
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['... | [
"def",
"betting_market_rules_update",
"(",
"self",
",",
"rules_id",
",",
"names",
",",
"descriptions",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"names",
",",
"list",
")",
"assert",
"isinstance",
"(",
"des... | 40.424242 | 0.002196 |
def Animation_seekAnimations(self, animations, currentTime):
"""
Function path: Animation.seekAnimations
Domain: Animation
Method name: seekAnimations
Parameters:
Required arguments:
'animations' (type: array) -> List of animation ids to seek.
'currentTime' (type: number) -> Set the curren... | [
"def",
"Animation_seekAnimations",
"(",
"self",
",",
"animations",
",",
"currentTime",
")",
":",
"assert",
"isinstance",
"(",
"animations",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"\"Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'\"",... | 39.478261 | 0.039785 |
def read_pickles (self):
"""Generate a sequence of objects by opening the path and unpickling items
until EOF is reached.
"""
try:
import cPickle as pickle
except ImportError:
import pickle
with self.open (mode='rb') as f:
while True:... | [
"def",
"read_pickles",
"(",
"self",
")",
":",
"try",
":",
"import",
"cPickle",
"as",
"pickle",
"except",
"ImportError",
":",
"import",
"pickle",
"with",
"self",
".",
"open",
"(",
"mode",
"=",
"'rb'",
")",
"as",
"f",
":",
"while",
"True",
":",
"try",
... | 26.588235 | 0.012821 |
def getATR(self):
"""Return card ATR"""
CardConnection.getATR(self)
if None == self.hcard:
raise CardConnectionException('Card not connected')
hresult, reader, state, protocol, atr = SCardStatus(self.hcard)
if hresult != 0:
raise CardConnectionException(
... | [
"def",
"getATR",
"(",
"self",
")",
":",
"CardConnection",
".",
"getATR",
"(",
"self",
")",
"if",
"None",
"==",
"self",
".",
"hcard",
":",
"raise",
"CardConnectionException",
"(",
"'Card not connected'",
")",
"hresult",
",",
"reader",
",",
"state",
",",
"pr... | 38.090909 | 0.009324 |
def blank_lines(logical_line, blank_lines, indent_level, line_number,
blank_before, previous_logical,
previous_unindented_logical_line, previous_indent_level,
lines):
r"""Separate top-level function and class definitions with two blank lines.
Method definitions i... | [
"def",
"blank_lines",
"(",
"logical_line",
",",
"blank_lines",
",",
"indent_level",
",",
"line_number",
",",
"blank_before",
",",
"previous_logical",
",",
"previous_unindented_logical_line",
",",
"previous_indent_level",
",",
"lines",
")",
":",
"if",
"line_number",
"<... | 49.733333 | 0.000329 |
def readDB(self):
"""Datamodel includes the following files: config.dat, devices.dat
"""
self.dm = DataModel(directory = tools.getConfigDir())
if (self.first_start):
print(pre, "readDB : first start")
self.dm.clearAll()
self.dm.saveAll()
# If ... | [
"def",
"readDB",
"(",
"self",
")",
":",
"self",
".",
"dm",
"=",
"DataModel",
"(",
"directory",
"=",
"tools",
".",
"getConfigDir",
"(",
")",
")",
"if",
"(",
"self",
".",
"first_start",
")",
":",
"print",
"(",
"pre",
",",
"\"readDB : first start\"",
")",... | 35.75 | 0.009091 |
def stop(self):
"""
Stops the timer.
"""
self._lock.acquire()
try:
# Stop the timer
if self._timer != None:
self._timer.stop()
self._timer = None
# Unset started flag
self.started = False... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"# Stop the timer",
"if",
"self",
".",
"_timer",
"!=",
"None",
":",
"self",
".",
"_timer",
".",
"stop",
"(",
")",
"self",
".",
"_timer",
"=",
"None",
... | 23.733333 | 0.010811 |
def get_user_id(remote, email):
"""Get the Globus identity for a users given email.
A Globus ID is a UUID that can uniquely identify a Globus user. See the
docs here for v2/api/identities
https://docs.globus.org/api/auth/reference/
"""
try:
url = '{}?usernames={}'.format(GLOBUS_USER_ID_... | [
"def",
"get_user_id",
"(",
"remote",
",",
"email",
")",
":",
"try",
":",
"url",
"=",
"'{}?usernames={}'",
".",
"format",
"(",
"GLOBUS_USER_ID_URL",
",",
"email",
")",
"user_id",
"=",
"get_dict_from_response",
"(",
"remote",
".",
"get",
"(",
"url",
")",
")"... | 46 | 0.001332 |
def get_extended_stats(self, data):
"""
Get more exhaustive statistics for the current user
data -- A dictionary with the range of dates you want the stats for {'from': '2010/01/01', 'to': '2010/01/10'}
"""
return self._call('GET', self._generate_url_path('extended-stats') + '?' + self._urlencode(d... | [
"def",
"get_extended_stats",
"(",
"self",
",",
"data",
")",
":",
"return",
"self",
".",
"_call",
"(",
"'GET'",
",",
"self",
".",
"_generate_url_path",
"(",
"'extended-stats'",
")",
"+",
"'?'",
"+",
"self",
".",
"_urlencode",
"(",
"data",
")",
")"
] | 53.333333 | 0.012308 |
def read_xso(src, xsomap):
"""
Read a single XSO from a binary file-like input `src` containing an XML
document.
`xsomap` must be a mapping which maps :class:`~.XSO` subclasses
to callables. These will be registered at a newly created
:class:`.xso.XSOParser` instance which will be used to parse... | [
"def",
"read_xso",
"(",
"src",
",",
"xsomap",
")",
":",
"xso_parser",
"=",
"xso",
".",
"XSOParser",
"(",
")",
"for",
"class_",
",",
"cb",
"in",
"xsomap",
".",
"items",
"(",
")",
":",
"xso_parser",
".",
"add_class",
"(",
"class_",
",",
"cb",
")",
"d... | 28.774194 | 0.001085 |
def scale(self, data, unit):
"""Scales quantity to obtain dimensionful quantity.
Args:
data (numpy.array): the quantity that should be scaled.
dim (str): the dimension of data as defined in phyvars.
Return:
(float, str): scaling factor and unit string.
... | [
"def",
"scale",
"(",
"self",
",",
"data",
",",
"unit",
")",
":",
"if",
"self",
".",
"par",
"[",
"'switches'",
"]",
"[",
"'dimensional_units'",
"]",
"or",
"not",
"conf",
".",
"scaling",
".",
"dimensional",
"or",
"unit",
"==",
"'1'",
":",
"return",
"da... | 40 | 0.001744 |
def _write_udf_descs(self, descs, outfp, progress):
# type: (PyCdlib._UDFDescriptors, BinaryIO, PyCdlib._Progress) -> None
'''
An internal method to write out a UDF Descriptor sequence.
Parameters:
descs - The UDF Descriptors object to write out.
outfp - The output fil... | [
"def",
"_write_udf_descs",
"(",
"self",
",",
"descs",
",",
"outfp",
",",
"progress",
")",
":",
"# type: (PyCdlib._UDFDescriptors, BinaryIO, PyCdlib._Progress) -> None",
"log_block_size",
"=",
"self",
".",
"pvd",
".",
"logical_block_size",
"(",
")",
"outfp",
".",
"seek... | 38.348837 | 0.001774 |
def multiplied(*values):
"""
Returns the product of all supplied values. One or more *values* can be
specified. For example, to light a :class:`~gpiozero.PWMLED` as the product
(i.e. multiplication) of several potentiometers connected to an
:class:`~gpiozero.MCP3008`
ADC::
from gpiozero... | [
"def",
"multiplied",
"(",
"*",
"values",
")",
":",
"values",
"=",
"[",
"_normalize",
"(",
"v",
")",
"for",
"v",
"in",
"values",
"]",
"def",
"_product",
"(",
"it",
")",
":",
"p",
"=",
"1",
"for",
"n",
"in",
"it",
":",
"p",
"*=",
"n",
"return",
... | 27.172414 | 0.002451 |
def get_servers(self):
"""
Create the list of Server object inside the Datacenter objects.
Build an internal list of VM Objects (pro or smart) as iterator.
:return: bool
"""
json_scheme = self.gen_def_json_scheme('GetServers')
json_obj = self.call_method_post(meth... | [
"def",
"get_servers",
"(",
"self",
")",
":",
"json_scheme",
"=",
"self",
".",
"gen_def_json_scheme",
"(",
"'GetServers'",
")",
"json_obj",
"=",
"self",
".",
"call_method_post",
"(",
"method",
"=",
"'GetServers'",
",",
"json_scheme",
"=",
"json_scheme",
")",
"s... | 42.833333 | 0.00163 |
def treeboost(self, data: ['SASdata', str] = None,
assess: str = None,
code: str = None,
freq: str = None,
importance: str = None,
input: [str, list, dict] = None,
performance: str = None,
save:... | [
"def",
"treeboost",
"(",
"self",
",",
"data",
":",
"[",
"'SASdata'",
",",
"str",
"]",
"=",
"None",
",",
"assess",
":",
"str",
"=",
"None",
",",
"code",
":",
"str",
"=",
"None",
",",
"freq",
":",
"str",
"=",
"None",
",",
"importance",
":",
"str",
... | 59.685714 | 0.009892 |
def mouseMoveEvent(self, ev):
"""Update line with last point and current coordinates."""
pos = self.transformPos(ev.pos())
# Update coordinates in status bar if image is opened
window = self.parent().window()
if window.filePath is not None:
self.parent().window().lab... | [
"def",
"mouseMoveEvent",
"(",
"self",
",",
"ev",
")",
":",
"pos",
"=",
"self",
".",
"transformPos",
"(",
"ev",
".",
"pos",
"(",
")",
")",
"# Update coordinates in status bar if image is opened",
"window",
"=",
"self",
".",
"parent",
"(",
")",
".",
"window",
... | 42.428571 | 0.000877 |
def get_target_errors(self):
"""Just get a single error characterization based on the index relative to the target
:param i: list index
:type i: int
:returns: list of base-wise errors
:rtype: list of HPA groups
"""
if self._target_errors: return self._target_errors
v = []
for i in... | [
"def",
"get_target_errors",
"(",
"self",
")",
":",
"if",
"self",
".",
"_target_errors",
":",
"return",
"self",
".",
"_target_errors",
"v",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_target_hpas",
")",
")",
":",
"v",
"."... | 26.066667 | 0.009877 |
def set_application_language(params):
"""Set the locale and translation for a pywws program.
This function reads the language from the configuration file, then
calls :func:`set_locale` and :func:`set_translation`.
:param params: a :class:`pywws.storage.params` object.
:type params: object
""... | [
"def",
"set_application_language",
"(",
"params",
")",
":",
"lang",
"=",
"params",
".",
"get",
"(",
"'config'",
",",
"'language'",
",",
"None",
")",
"if",
"lang",
":",
"set_locale",
"(",
"lang",
")",
"set_translation",
"(",
"lang",
")"
] | 28.333333 | 0.002278 |
def _value(self, obj, cls=None):
"""The state value (called from the wrapper)"""
if obj is not None:
return getattr(obj, self.propname)
else:
return getattr(cls, self.propname) | [
"def",
"_value",
"(",
"self",
",",
"obj",
",",
"cls",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"not",
"None",
":",
"return",
"getattr",
"(",
"obj",
",",
"self",
".",
"propname",
")",
"else",
":",
"return",
"getattr",
"(",
"cls",
",",
"self",
"."... | 36.5 | 0.008929 |
def clear(self, store=True):
"""Clears (locks) the achievement.
:rtype: bool
"""
result = self._iface.ach_lock(self.name)
result and store and self._store()
return result | [
"def",
"clear",
"(",
"self",
",",
"store",
"=",
"True",
")",
":",
"result",
"=",
"self",
".",
"_iface",
".",
"ach_lock",
"(",
"self",
".",
"name",
")",
"result",
"and",
"store",
"and",
"self",
".",
"_store",
"(",
")",
"return",
"result"
] | 26.5 | 0.009132 |
def is_ip_addr(value):
"""
Check that the supplied value is an Internet Protocol address, v.4,
represented by a dotted-quad string, i.e. '1.2.3.4'.
>>> vtor = Validator()
>>> vtor.check('ip_addr', '1 ')
'1'
>>> vtor.check('ip_addr', ' 1.2')
'1.2'
>>> vtor.check('ip_addr', ' 1.2.3 ')... | [
"def",
"is_ip_addr",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"raise",
"VdtTypeError",
"(",
"value",
")",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"try",
":",
"dottedQuadToNum",
"(",
"value",
... | 32.694444 | 0.000825 |
def get_fill_char( maf_status ):
"""
Return the character that should be used to fill between blocks
having a given status
"""
## assert maf_status not in ( maf.MAF_CONTIG_NESTED_STATUS, maf.MAF_NEW_NESTED_STATUS,
## maf.MAF_MAYBE_NEW_NESTED_STATUS ), \
## "Ne... | [
"def",
"get_fill_char",
"(",
"maf_status",
")",
":",
"## assert maf_status not in ( maf.MAF_CONTIG_NESTED_STATUS, maf.MAF_NEW_NESTED_STATUS, ",
"## maf.MAF_MAYBE_NEW_NESTED_STATUS ), \\",
"## \"Nested rows do not make sense in a single coverage MAF (or do they?)\"",
... | 45.157895 | 0.019406 |
def countrate(self,binned=True,range=None,force=False):
"""Calculate effective stimulus in count/s.
Also see :ref:`pysynphot-formula-countrate` and
:ref:`pysynphot-formula-effstim`.
.. note::
This is the calculation performed when the ETC invokes
``countrate``.
... | [
"def",
"countrate",
"(",
"self",
",",
"binned",
"=",
"True",
",",
"range",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"_binflux",
"is",
"None",
":",
"self",
".",
"initbinflux",
"(",
")",
"myfluxunits",
"=",
"self",
".",
"... | 35.526316 | 0.010089 |
def is_numeric_v_string_like(a, b):
"""
Check if we are comparing a string-like object to a numeric ndarray.
NumPy doesn't like to compare such objects, especially numeric arrays
and scalar string-likes.
Parameters
----------
a : array-like, scalar
The first object to check.
b ... | [
"def",
"is_numeric_v_string_like",
"(",
"a",
",",
"b",
")",
":",
"is_a_array",
"=",
"isinstance",
"(",
"a",
",",
"np",
".",
"ndarray",
")",
"is_b_array",
"=",
"isinstance",
"(",
"b",
",",
"np",
".",
"ndarray",
")",
"is_a_numeric_array",
"=",
"is_a_array",
... | 32.553571 | 0.000532 |
def print_featurelist(feature_list):
"""
Print the feature_list in a human-readable form.
Parameters
----------
feature_list : list
feature objects
"""
input_features = sum(map(lambda n: n.get_dimension(), feature_list))
print("## Features (%i)" % input_features)
print("```"... | [
"def",
"print_featurelist",
"(",
"feature_list",
")",
":",
"input_features",
"=",
"sum",
"(",
"map",
"(",
"lambda",
"n",
":",
"n",
".",
"get_dimension",
"(",
")",
",",
"feature_list",
")",
")",
"print",
"(",
"\"## Features (%i)\"",
"%",
"input_features",
")"... | 26.533333 | 0.002427 |
def loads(data):
"""Parser entry point. Parses the output of a traceroute execution"""
data += "\n_EOS_" # Append EOS token. Helps to match last RE_HOP
# Get headers
match_dest = RE_HEADER.search(data)
dest_name = match_dest.group(1)
dest_ip = match_dest.group(2)
# The Traceroute is the ro... | [
"def",
"loads",
"(",
"data",
")",
":",
"data",
"+=",
"\"\\n_EOS_\"",
"# Append EOS token. Helps to match last RE_HOP",
"# Get headers",
"match_dest",
"=",
"RE_HEADER",
".",
"search",
"(",
"data",
")",
"dest_name",
"=",
"match_dest",
".",
"group",
"(",
"1",
")",
... | 34.422535 | 0.001591 |
def bulkBatchDF(symbols, fields=None, range_='1m', last=10, token='', version=''):
'''Optimized batch to fetch as much as possible at once
https://iexcloud.io/docs/api/#batch-requests
Args:
symbols (list); List of tickers to request
fields (list); List of fields to request
range_ ... | [
"def",
"bulkBatchDF",
"(",
"symbols",
",",
"fields",
"=",
"None",
",",
"range_",
"=",
"'1m'",
",",
"last",
"=",
"10",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"dat",
"=",
"bulkBatch",
"(",
"symbols",
",",
"fields",
",",
"range_... | 29 | 0.002225 |
def _get_serial_number(self):
"""
Retrieves the FTDI device serial number.
:returns: string containing the device serial number
"""
return usb.util.get_string(self._device.usb_dev, 64, self._device.usb_dev.iSerialNumber) | [
"def",
"_get_serial_number",
"(",
"self",
")",
":",
"return",
"usb",
".",
"util",
".",
"get_string",
"(",
"self",
".",
"_device",
".",
"usb_dev",
",",
"64",
",",
"self",
".",
"_device",
".",
"usb_dev",
".",
"iSerialNumber",
")"
] | 36.428571 | 0.011494 |
def get_cache(self, decorated_function, *args, **kwargs):
""" :meth:`WCacheStorage.get_cache` method implementation
"""
self.__check(decorated_function, *args, **kwargs)
if decorated_function in self._storage:
for i in self._storage[decorated_function]:
if i['instance']() == args[0]:
result = i['res... | [
"def",
"get_cache",
"(",
"self",
",",
"decorated_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__check",
"(",
"decorated_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"decorated_function",
"in",
"self",
... | 31.263158 | 0.029412 |
def typed_subpart_iterator(msg, maintype='text', subtype=None):
"""Iterate over the subparts with a given MIME type.
Use `maintype' as the main MIME type to match against; this defaults to
"text". Optional `subtype' is the MIME subtype to match against; if
omitted, only the main type is matched.
"... | [
"def",
"typed_subpart_iterator",
"(",
"msg",
",",
"maintype",
"=",
"'text'",
",",
"subtype",
"=",
"None",
")",
":",
"for",
"subpart",
"in",
"msg",
".",
"walk",
"(",
")",
":",
"if",
"subpart",
".",
"get_content_maintype",
"(",
")",
"==",
"maintype",
":",
... | 45.818182 | 0.001946 |
def compute_ihh_gaps(pos, map_pos, gap_scale, max_gap, is_accessible):
"""Compute spacing between variants for integrating haplotype
homozygosity.
Parameters
----------
pos : array_like, int, shape (n_variants,)
Variant positions (physical distance).
map_pos : array_like, float, shape (... | [
"def",
"compute_ihh_gaps",
"(",
"pos",
",",
"map_pos",
",",
"gap_scale",
",",
"max_gap",
",",
"is_accessible",
")",
":",
"# check inputs",
"if",
"map_pos",
"is",
"None",
":",
"# integrate over physical distance",
"map_pos",
"=",
"pos",
"else",
":",
"map_pos",
"=... | 31.411765 | 0.000454 |
def photparse(tab):
"""
Parse through a photometry table to group by source_id
Parameters
----------
tab: list
SQL query dictionary list from running query_dict.execute()
Returns
-------
newtab: list
Dictionary list after parsing to group together sources
"""
# Ch... | [
"def",
"photparse",
"(",
"tab",
")",
":",
"# Check that source_id column is present",
"if",
"'source_id'",
"not",
"in",
"tab",
"[",
"0",
"]",
".",
"keys",
"(",
")",
":",
"raise",
"KeyError",
"(",
"'phot=TRUE requires the source_id columb be included'",
")",
"# Loop ... | 25.171429 | 0.001093 |
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_inst... | [
"def",
"request_instance",
"(",
"vm_",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"# Technically this function may be called other ways too, but it",
"# definitely cannot be called with --function.",
"raise",
"Salt... | 40.725 | 0.0006 |
def determine_struct_tree_subtype(self, data_type, obj):
"""
Searches through the JSON-object-compatible dict using the data type
definition to determine which of the enumerated subtypes `obj` is.
"""
if '.tag' not in obj:
raise bv.ValidationError("missing '.tag' key"... | [
"def",
"determine_struct_tree_subtype",
"(",
"self",
",",
"data_type",
",",
"obj",
")",
":",
"if",
"'.tag'",
"not",
"in",
"obj",
":",
"raise",
"bv",
".",
"ValidationError",
"(",
"\"missing '.tag' key\"",
")",
"if",
"not",
"isinstance",
"(",
"obj",
"[",
"'.ta... | 49.705882 | 0.002322 |
def oq_server_context_processor(request):
"""
A custom context processor which allows injection of additional
context variables.
"""
context = {}
context['oq_engine_server_url'] = ('//' +
request.META.get('HTTP_HOST',
... | [
"def",
"oq_server_context_processor",
"(",
"request",
")",
":",
"context",
"=",
"{",
"}",
"context",
"[",
"'oq_engine_server_url'",
"]",
"=",
"(",
"'//'",
"+",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_HOST'",
",",
"'localhost:8800'",
")",
")",
"# this... | 36.25 | 0.001681 |
def phi( n ):
"""Return the Euler totient function of n."""
assert isinstance( n, integer_types )
if n < 3: return 1
result = 1
ff = factorization( n )
for f in ff:
e = f[1]
if e > 1:
result = result * f[0] ** (e-1) * ( f[0] - 1 )
else:
result = result * ( f[0] - 1 )
return resu... | [
"def",
"phi",
"(",
"n",
")",
":",
"assert",
"isinstance",
"(",
"n",
",",
"integer_types",
")",
"if",
"n",
"<",
"3",
":",
"return",
"1",
"result",
"=",
"1",
"ff",
"=",
"factorization",
"(",
"n",
")",
"for",
"f",
"in",
"ff",
":",
"e",
"=",
"f",
... | 19.1875 | 0.065217 |
def determine_file_extension_based_on_format(format_specifier):
""" returns file extension string """
if format_specifier == FMT_INI:
return 'ini'
if format_specifier == FMT_DELIMITED:
return ''
if format_specifier == FMT_XML:
return 'xml'
if format_specifier == FMT_JSON:
return 'json'
if format_specifier... | [
"def",
"determine_file_extension_based_on_format",
"(",
"format_specifier",
")",
":",
"if",
"format_specifier",
"==",
"FMT_INI",
":",
"return",
"'ini'",
"if",
"format_specifier",
"==",
"FMT_DELIMITED",
":",
"return",
"''",
"if",
"format_specifier",
"==",
"FMT_XML",
":... | 31.615385 | 0.030733 |
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
... | [
"def",
"modify_node",
"(",
"hostname",
",",
"username",
",",
"password",
",",
"name",
",",
"connection_limit",
"=",
"None",
",",
"description",
"=",
"None",
",",
"dynamic_ratio",
"=",
"None",
",",
"logging",
"=",
"None",
",",
"monitor",
"=",
"None",
",",
... | 32.40625 | 0.00156 |
def conv_Pb_bound(R,dfree,Ck,SNRdB,hard_soft,M=2):
"""
Coded bit error probabilty
Convolution coding bit error probability upper bound
according to Ziemer & Peterson 7-16, p. 507
Mark Wickert November 2014
Parameters
----------
R: Code rate
dfree: Free distance of ... | [
"def",
"conv_Pb_bound",
"(",
"R",
",",
"dfree",
",",
"Ck",
",",
"SNRdB",
",",
"hard_soft",
",",
"M",
"=",
"2",
")",
":",
"Pb",
"=",
"np",
".",
"zeros_like",
"(",
"SNRdB",
")",
"SNR",
"=",
"10.",
"**",
"(",
"SNRdB",
"/",
"10.",
")",
"for",
"n",
... | 34.758621 | 0.011095 |
def get_instance(self, payload):
"""
Build an instance of MonthlyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance
:rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance
... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"MonthlyInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"
] | 42.1 | 0.011628 |
def assert_order_met(self, finalize=False):
"""assert that calls have been made in the right order."""
error = None
actual_call_len = len(self._actual_calls)
expected_call_len = len(self._call_order)
if actual_call_len == 0:
error = "Not enough calls were made"
... | [
"def",
"assert_order_met",
"(",
"self",
",",
"finalize",
"=",
"False",
")",
":",
"error",
"=",
"None",
"actual_call_len",
"=",
"len",
"(",
"self",
".",
"_actual_calls",
")",
"expected_call_len",
"=",
"len",
"(",
"self",
".",
"_call_order",
")",
"if",
"actu... | 39.02439 | 0.001829 |
def __read_config(self):
"""读取 config"""
self.config = helpers.file2dict(self.config_path)
self.global_config = helpers.file2dict(self.global_config_path)
self.config.update(self.global_config) | [
"def",
"__read_config",
"(",
"self",
")",
":",
"self",
".",
"config",
"=",
"helpers",
".",
"file2dict",
"(",
"self",
".",
"config_path",
")",
"self",
".",
"global_config",
"=",
"helpers",
".",
"file2dict",
"(",
"self",
".",
"global_config_path",
")",
"self... | 44.2 | 0.008889 |
def _make_entity_from_id(entity_cls, entity_obj_or_id, server_config):
"""Given an entity object or an ID, return an entity object.
If the value passed in is an object that is a subclass of :class:`Entity`,
return that value. Otherwise, create an object of the type that ``field``
references, give that ... | [
"def",
"_make_entity_from_id",
"(",
"entity_cls",
",",
"entity_obj_or_id",
",",
"server_config",
")",
":",
"if",
"isinstance",
"(",
"entity_obj_or_id",
",",
"entity_cls",
")",
":",
"return",
"entity_obj_or_id",
"return",
"entity_cls",
"(",
"server_config",
",",
"id"... | 41.833333 | 0.001299 |
def _xpathDict(xml, xpath, cls, parent, **kwargs):
""" Returns a default Dict given certain information
:param xml: An xml tree
:type xml: etree
:param xpath: XPath to find children
:type xpath: str
:param cls: Class identifying children
:type cls: inventory.Resource
:param parent: Pare... | [
"def",
"_xpathDict",
"(",
"xml",
",",
"xpath",
",",
"cls",
",",
"parent",
",",
"*",
"*",
"kwargs",
")",
":",
"children",
"=",
"[",
"]",
"for",
"child",
"in",
"xml",
".",
"xpath",
"(",
"xpath",
",",
"namespaces",
"=",
"XPATH_NAMESPACES",
")",
":",
"... | 30.954545 | 0.001425 |
def get_requirements(filename='requirements.txt'):
"""
Get the contents of a file listing the requirements.
:param filename: path to a requirements file
:type filename: str
:returns: the list of requirements
:return type: list
"""
with open(filename) as f:
return [
... | [
"def",
"get_requirements",
"(",
"filename",
"=",
"'requirements.txt'",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"return",
"[",
"line",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"'#'",
")",
"[",
"0",
"]",
"for",
"line",
"in",
... | 26.3125 | 0.002294 |
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
C = self.COEFFS[imt]
... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# extracting dictionary of coefficients",
"C",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"]",
"mag",
"=",
"self",
".",
"_convert_mag... | 36.633333 | 0.001773 |
def add(self, sentence_text, **kwargs):
''' Parse a text string and add it to this doc '''
sent = MeCabSent.parse(sentence_text, **kwargs)
self.sents.append(sent)
return sent | [
"def",
"add",
"(",
"self",
",",
"sentence_text",
",",
"*",
"*",
"kwargs",
")",
":",
"sent",
"=",
"MeCabSent",
".",
"parse",
"(",
"sentence_text",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"sents",
".",
"append",
"(",
"sent",
")",
"return",
"sent"
] | 40.4 | 0.009709 |
def git_info():
"""
A hash of Git data that can be used to display more information to users.
Example:
"git": {
"head": {
"id": "5e837ce92220be64821128a70f6093f836dd2c05",
"author_name": "Wil Gieseler",
"author_email": "wil@example.com",
... | [
"def",
"git_info",
"(",
")",
":",
"try",
":",
"branch",
"=",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'APPVEYOR_REPO_BRANCH'",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"'BUILDKITE_BRANCH'",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(... | 38.347222 | 0.000353 |
def urlopen(url, session, referrer=None, max_content_bytes=None,
timeout=ConnectionTimeoutSecs, raise_for_status=True,
stream=False, data=None, useragent=UserAgent):
"""Open an URL and return the response object."""
out.debug(u'Open URL %s' % url)
headers = {'User-Agent': useragent}
... | [
"def",
"urlopen",
"(",
"url",
",",
"session",
",",
"referrer",
"=",
"None",
",",
"max_content_bytes",
"=",
"None",
",",
"timeout",
"=",
"ConnectionTimeoutSecs",
",",
"raise_for_status",
"=",
"True",
",",
"stream",
"=",
"False",
",",
"data",
"=",
"None",
",... | 35.675676 | 0.000737 |
def query_recent(num=8, **kwargs):
'''
query recent posts.
'''
order_by_create = kwargs.get('order_by_create', False)
kind = kwargs.get('kind', None)
if order_by_create:
if kind:
recent_recs = TabPost.select().where(
(TabPos... | [
"def",
"query_recent",
"(",
"num",
"=",
"8",
",",
"*",
"*",
"kwargs",
")",
":",
"order_by_create",
"=",
"kwargs",
".",
"get",
"(",
"'order_by_create'",
",",
"False",
")",
"kind",
"=",
"kwargs",
".",
"get",
"(",
"'kind'",
",",
"None",
")",
"if",
"orde... | 34.727273 | 0.001698 |
def label_suspicious(self, reason):
"""Add suspicion reason and set the suspicious flag."""
self.suspicion_reasons.append(reason)
self.is_suspect = True | [
"def",
"label_suspicious",
"(",
"self",
",",
"reason",
")",
":",
"self",
".",
"suspicion_reasons",
".",
"append",
"(",
"reason",
")",
"self",
".",
"is_suspect",
"=",
"True"
] | 43.25 | 0.011364 |
def merge_tags(left, right, factory=Tags):
"""
Merge two sets of tags into a new troposphere object
Args:
left (Union[dict, troposphere.Tags]): dictionary or Tags object to be
merged with lower priority
right (Union[dict, troposphere.Tags]): dictionary or Tags object to be
... | [
"def",
"merge_tags",
"(",
"left",
",",
"right",
",",
"factory",
"=",
"Tags",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"Mapping",
")",
":",
"tags",
"=",
"dict",
"(",
"left",
")",
"elif",
"hasattr",
"(",
"left",
",",
"'tags'",
")",
":",
"tags"... | 29.892857 | 0.001157 |
def stop_refresh(self):
"""Stop redrawing the canvas at the previously set timed interval.
"""
self.logger.debug("stopping timed refresh")
self.rf_flags['done'] = True
self.rf_timer.clear() | [
"def",
"stop_refresh",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"stopping timed refresh\"",
")",
"self",
".",
"rf_flags",
"[",
"'done'",
"]",
"=",
"True",
"self",
".",
"rf_timer",
".",
"clear",
"(",
")"
] | 37.333333 | 0.008734 |
def factory(fileobject, jfs, parentpath): # fileobject from lxml.objectify
'Class method to get the correct file class instatiated'
if hasattr(fileobject, 'currentRevision'): # a normal file
return JFSFile(fileobject, jfs, parentpath)
elif str(fileobject.latestRevision.state) == Prot... | [
"def",
"factory",
"(",
"fileobject",
",",
"jfs",
",",
"parentpath",
")",
":",
"# fileobject from lxml.objectify",
"if",
"hasattr",
"(",
"fileobject",
",",
"'currentRevision'",
")",
":",
"# a normal file",
"return",
"JFSFile",
"(",
"fileobject",
",",
"jfs",
",",
... | 68.3 | 0.008671 |
def ObjectEnum(ctx):
"""Object Enumeration.
Should export the whole list from the game for the best accuracy.
"""
return Enum(
ctx,
villager_male=83,
villager_female=293,
scout_cavalry=448,
eagle_warrior=751,
king=434,
flare=332,
relic=285... | [
"def",
"ObjectEnum",
"(",
"ctx",
")",
":",
"return",
"Enum",
"(",
"ctx",
",",
"villager_male",
"=",
"83",
",",
"villager_female",
"=",
"293",
",",
"scout_cavalry",
"=",
"448",
",",
"eagle_warrior",
"=",
"751",
",",
"king",
"=",
"434",
",",
"flare",
"="... | 21.202703 | 0.000609 |
def records( self ):
"""
Returns the record list that ist linked with this combo box.
:return [<orb.Table>, ..]
"""
records = []
for i in range(self.count()):
record = self.recordAt(i)
if record:
records.appen... | [
"def",
"records",
"(",
"self",
")",
":",
"records",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"count",
"(",
")",
")",
":",
"record",
"=",
"self",
".",
"recordAt",
"(",
"i",
")",
"if",
"record",
":",
"records",
".",
"append",
"... | 28.5 | 0.014164 |
def _validate_minlength(self, min_length, field, value):
""" {'type': 'integer'} """
if isinstance(value, Iterable) and len(value) < min_length:
self._error(field, errors.MIN_LENGTH, len(value)) | [
"def",
"_validate_minlength",
"(",
"self",
",",
"min_length",
",",
"field",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Iterable",
")",
"and",
"len",
"(",
"value",
")",
"<",
"min_length",
":",
"self",
".",
"_error",
"(",
"field",
",... | 54.75 | 0.009009 |
def _publish_internal(self, push_messages):
"""Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
... | [
"def",
"_publish_internal",
"(",
"self",
",",
"push_messages",
")",
":",
"# Delayed import because this file is immediately read on install, and",
"# the requests library may not be installed yet.",
"import",
"requests",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".... | 37.783133 | 0.000622 |
def get_tree(self, *page_numbers):
"""
Return lxml.etree.ElementTree for entire document, or page numbers
given if any.
"""
cache_key = "_".join(map(str, _flatten(page_numbers)))
tree = self._parse_tree_cacher.get(cache_key)
if tree is None:
... | [
"def",
"get_tree",
"(",
"self",
",",
"*",
"page_numbers",
")",
":",
"cache_key",
"=",
"\"_\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"_flatten",
"(",
"page_numbers",
")",
")",
")",
"tree",
"=",
"self",
".",
"_parse_tree_cacher",
".",
"get",
"(",
... | 44.673913 | 0.001429 |
def get_insert_idx(pos_dict, name):
"Return the position to insert a given function doc in a notebook."
keys,i = list(pos_dict.keys()),0
while i < len(keys) and str.lower(keys[i]) < str.lower(name): i+=1
if i == len(keys): return -1
else: return pos_dict[keys[i]] | [
"def",
"get_insert_idx",
"(",
"pos_dict",
",",
"name",
")",
":",
"keys",
",",
"i",
"=",
"list",
"(",
"pos_dict",
".",
"keys",
"(",
")",
")",
",",
"0",
"while",
"i",
"<",
"len",
"(",
"keys",
")",
"and",
"str",
".",
"lower",
"(",
"keys",
"[",
"i"... | 48.5 | 0.027027 |
def generate(self, title=None, version=None, base_path=None,
info=None, swagger=None, **kwargs):
"""Generate a Swagger 2.0 documentation. Keyword arguments may be used
to provide additional information to build methods as such ignores.
:param title:
The name present... | [
"def",
"generate",
"(",
"self",
",",
"title",
"=",
"None",
",",
"version",
"=",
"None",
",",
"base_path",
"=",
"None",
",",
"info",
"=",
"None",
",",
"swagger",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"title",
"=",
"title",
"or",
"self",
... | 37.95 | 0.00214 |
def exact_cftime_datetime_difference(a, b):
"""Exact computation of b - a
Assumes:
a = a_0 + a_m
b = b_0 + b_m
Here a_0, and b_0 represent the input dates rounded
down to the nearest second, and a_m, and b_m represent
the remaining microseconds associated with date a and
date ... | [
"def",
"exact_cftime_datetime_difference",
"(",
"a",
",",
"b",
")",
":",
"seconds",
"=",
"b",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
"-",
"a",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
"seconds",
"=",
"int",
"(",
"round",
"(",
"s... | 29.921053 | 0.000852 |
def mkrngs(self):
"""
Transform boolean arrays into list of limit pairs.
Gets Time limits of signal/background boolean arrays and stores them as
sigrng and bkgrng arrays. These arrays can be saved by 'save_ranges' in
the analyse object.
"""
bbool = bool_2_indices... | [
"def",
"mkrngs",
"(",
"self",
")",
":",
"bbool",
"=",
"bool_2_indices",
"(",
"self",
".",
"bkg",
")",
"if",
"bbool",
"is",
"not",
"None",
":",
"self",
".",
"bkgrng",
"=",
"self",
".",
"Time",
"[",
"bbool",
"]",
"else",
":",
"self",
".",
"bkgrng",
... | 31.911765 | 0.001789 |
def from_array(self, coeffs, normalization='4pi', csphase=1, lmax=None,
copy=True):
"""
Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHCoeffs.from_array(array, [normalization, csphase, lmax, copy])
... | [
"def",
"from_array",
"(",
"self",
",",
"coeffs",
",",
"normalization",
"=",
"'4pi'",
",",
"csphase",
"=",
"1",
",",
"lmax",
"=",
"None",
",",
"copy",
"=",
"True",
")",
":",
"if",
"_np",
".",
"iscomplexobj",
"(",
"coeffs",
")",
":",
"kind",
"=",
"'c... | 39.413333 | 0.00099 |
def lsr_pairwise(n_items, data, alpha=0.0, initial_params=None):
"""Compute the LSR estimate of model parameters.
This function implements the Luce Spectral Ranking inference algorithm
[MG15]_ for pairwise-comparison data (see :ref:`data-pairwise`).
The argument ``initial_params`` can be used to itera... | [
"def",
"lsr_pairwise",
"(",
"n_items",
",",
"data",
",",
"alpha",
"=",
"0.0",
",",
"initial_params",
"=",
"None",
")",
":",
"weights",
",",
"chain",
"=",
"_init_lsr",
"(",
"n_items",
",",
"alpha",
",",
"initial_params",
")",
"for",
"winner",
",",
"loser"... | 37.916667 | 0.000714 |
def print_lh(self, joint=True):
"""
Print the total likelihood of the tree given the constrained leaves
Parameters
----------
joint : bool
If true, print joint LH, else print marginal LH
"""
try:
u_lh = self.tree.unconstrained_sequence_... | [
"def",
"print_lh",
"(",
"self",
",",
"joint",
"=",
"True",
")",
":",
"try",
":",
"u_lh",
"=",
"self",
".",
"tree",
".",
"unconstrained_sequence_LH",
"if",
"joint",
":",
"s_lh",
"=",
"self",
".",
"tree",
".",
"sequence_joint_LH",
"t_lh",
"=",
"self",
".... | 37.1 | 0.010508 |
def unit_defs_from_sheet(sheet, column_names):
"""A generator that parses a worksheet containing UNECE code definitions.
Args:
sheet: An xldr.sheet object representing a UNECE code worksheet.
column_names: A list/tuple with the expected column names corresponding to
the unit name, code an... | [
"def",
"unit_defs_from_sheet",
"(",
"sheet",
",",
"column_names",
")",
":",
"seen",
"=",
"set",
"(",
")",
"try",
":",
"col_indices",
"=",
"{",
"}",
"rows",
"=",
"sheet",
".",
"get_rows",
"(",
")",
"# Find the indices for the columns we care about.",
"for",
"id... | 36.351351 | 0.010862 |
def StartExecServer():
"""Opens a socket in /tmp, execs data from it and writes results back."""
sockdir = '/tmp/pyringe_%s' % os.getpid()
if not os.path.isdir(sockdir):
os.mkdir(sockdir)
socket_path = ('%s/%s.execsock' %
(sockdir, threading.current_thread().ident))
if os.path.exists(soc... | [
"def",
"StartExecServer",
"(",
")",
":",
"sockdir",
"=",
"'/tmp/pyringe_%s'",
"%",
"os",
".",
"getpid",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"sockdir",
")",
":",
"os",
".",
"mkdir",
"(",
"sockdir",
")",
"socket_path",
"=",
"("... | 31.317073 | 0.018882 |
def from_dict(input_dict):
"""
Instantiate an object of a derived class using the information
in input_dict (built by the to_dict method of the derived class).
More specifically, after reading the derived class from input_dict,
it calls the method _build_from_input_dict of the de... | [
"def",
"from_dict",
"(",
"input_dict",
")",
":",
"import",
"copy",
"input_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"input_dict",
")",
"link_class",
"=",
"input_dict",
".",
"pop",
"(",
"'class'",
")",
"import",
"GPy",
"link_class",
"=",
"eval",
"(",
"link_... | 43.842105 | 0.00235 |
def get_infobox(ptree, boxterm="box"):
"""
Returns parse tree template with title containing <boxterm> as dict:
<box> = {<name>: <value>, ...}
If simple transform fails, attempts more general assembly:
<box> = {'boxes': [{<title>: <parts>}, ...],
'count': <len(boxes)>}
... | [
"def",
"get_infobox",
"(",
"ptree",
",",
"boxterm",
"=",
"\"box\"",
")",
":",
"boxes",
"=",
"[",
"]",
"for",
"item",
"in",
"lxml",
".",
"etree",
".",
"fromstring",
"(",
"ptree",
")",
".",
"xpath",
"(",
"\"//template\"",
")",
":",
"title",
"=",
"item"... | 26.814815 | 0.001333 |
def dumps_list(l, *, escape=True, token='%\n', mapper=None, as_content=True):
r"""Try to generate a LaTeX string of a list that can contain anything.
Args
----
l : list
A list of objects to be converted into a single string.
escape : bool
Whether to escape special LaTeX characters i... | [
"def",
"dumps_list",
"(",
"l",
",",
"*",
",",
"escape",
"=",
"True",
",",
"token",
"=",
"'%\\n'",
",",
"mapper",
"=",
"None",
",",
"as_content",
"=",
"True",
")",
":",
"strings",
"=",
"(",
"_latex_item_to_string",
"(",
"i",
",",
"escape",
"=",
"escap... | 30.862745 | 0.001232 |
def add_file(self, name="", hashalg="", hash="", comClasses=None,
typelibs=None, comInterfaceProxyStubs=None,
windowClasses=None):
""" Shortcut for manifest.files.append """
self.files.append(File(name, hashalg, hash, comClasses,
typelibs, c... | [
"def",
"add_file",
"(",
"self",
",",
"name",
"=",
"\"\"",
",",
"hashalg",
"=",
"\"\"",
",",
"hash",
"=",
"\"\"",
",",
"comClasses",
"=",
"None",
",",
"typelibs",
"=",
"None",
",",
"comInterfaceProxyStubs",
"=",
"None",
",",
"windowClasses",
"=",
"None",
... | 58.833333 | 0.019553 |
def map_crt_to_pol(aryXCrds, aryYrds):
"""Remap coordinates from cartesian to polar
Parameters
----------
aryXCrds : 1D numpy array
Array with x coordinate values.
aryYrds : 1D numpy array
Array with y coordinate values.
Returns
-------
aryTht : 1D numpy array
A... | [
"def",
"map_crt_to_pol",
"(",
"aryXCrds",
",",
"aryYrds",
")",
":",
"aryRad",
"=",
"np",
".",
"sqrt",
"(",
"aryXCrds",
"**",
"2",
"+",
"aryYrds",
"**",
"2",
")",
"aryTht",
"=",
"np",
".",
"arctan2",
"(",
"aryYrds",
",",
"aryXCrds",
")",
"return",
"ar... | 22.772727 | 0.001916 |
def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):
"""A block of standard 1d convolutions."""
return conv_block_internal(conv1d, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | [
"def",
"conv1d_block",
"(",
"inputs",
",",
"filters",
",",
"dilation_rates_and_kernel_sizes",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"conv_block_internal",
"(",
"conv1d",
",",
"inputs",
",",
"filters",
",",
"dilation_rates_and_kernel_sizes",
",",
"*",
"*",
... | 61.25 | 0.012097 |
def get_message_plain_text(msg: Message):
"""
Converts an HTML message to plain text.
:param msg: A :class:`~flask_mail.Message`
:return: The plain text message.
"""
if msg.body:
return msg.body
if BeautifulSoup is None or not msg.html:
return msg.html
plain_text = '\n... | [
"def",
"get_message_plain_text",
"(",
"msg",
":",
"Message",
")",
":",
"if",
"msg",
".",
"body",
":",
"return",
"msg",
".",
"body",
"if",
"BeautifulSoup",
"is",
"None",
"or",
"not",
"msg",
".",
"html",
":",
"return",
"msg",
".",
"html",
"plain_text",
"... | 29.375 | 0.002062 |
def list(self, filter_guid=None, filter_ids=None, detailed=None, page=None):
"""
This API endpoint returns a paginated list of the plugins associated
with your New Relic account.
Plugins can be filtered by their name or by a list of IDs.
:type filter_guid: str
:param fi... | [
"def",
"list",
"(",
"self",
",",
"filter_guid",
"=",
"None",
",",
"filter_ids",
"=",
"None",
",",
"detailed",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"filters",
"=",
"[",
"'filter[guid]={0}'",
".",
"format",
"(",
"filter_guid",
")",
"if",
"fil... | 38.172043 | 0.001373 |
def get_dir(path_name, *, greedy=False, override=None, identity=None):
"""
Gets the directory path of the given path name. If the argument 'greedy'
is specified as True, then if the path name represents a directory itself,
the function will return the whole path
"""
if identity is None:
... | [
"def",
"get_dir",
"(",
"path_name",
",",
"*",
",",
"greedy",
"=",
"False",
",",
"override",
"=",
"None",
",",
"identity",
"=",
"None",
")",
":",
"if",
"identity",
"is",
"None",
":",
"identity",
"=",
"identify",
"(",
"path_name",
",",
"override",
"=",
... | 34.333333 | 0.00189 |
def parse_http_accept_header(header):
"""
Return a list of content types listed in the HTTP Accept header
ordered by quality.
:param header: A string describing the contents of the HTTP Accept header.
"""
components = [item.strip() for item in header.split(',')]
l = []
for component in... | [
"def",
"parse_http_accept_header",
"(",
"header",
")",
":",
"components",
"=",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"header",
".",
"split",
"(",
"','",
")",
"]",
"l",
"=",
"[",
"]",
"for",
"component",
"in",
"components",
":",
"i... | 25.46875 | 0.009456 |
def _encode_decode_decorator(func):
"""decorator for encoding and decoding geoms"""
def wrapper(*args):
"""error catching"""
try:
processed_geom = func(*args)
return processed_geom
except ImportError as err:
raise ImportError('The Python package `shape... | [
"def",
"_encode_decode_decorator",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"\"\"\"error catching\"\"\"",
"try",
":",
"processed_geom",
"=",
"func",
"(",
"*",
"args",
")",
"return",
"processed_geom",
"except",
"ImportError",
"as",
"... | 39.166667 | 0.002079 |
def _number_shapes_ancestors(self, topoTypeA, topoTypeB, topologicalEntity):
'''returns the number of shape ancestors
If you want to know how many edges a faces has:
_number_shapes_ancestors(self, TopAbs_EDGE, TopAbs_FACE, edg)
will return the number of edges a faces has
@pa... | [
"def",
"_number_shapes_ancestors",
"(",
"self",
",",
"topoTypeA",
",",
"topoTypeB",
",",
"topologicalEntity",
")",
":",
"topo_set",
"=",
"set",
"(",
")",
"_map",
"=",
"TopTools_IndexedDataMapOfShapeListOfShape",
"(",
")",
"topexp_MapShapesAndAncestors",
"(",
"self",
... | 45.1 | 0.002172 |
def get_trans_mat(r_axis, angle, normal=False, trans_cry=np.eye(3), lat_type='c',
ratio=None, surface=None, max_search=20, quick_gen=False):
"""
Find the two transformation matrix for each grain from given rotation axis,
GB plane, rotation angle and corresponding ratio (see... | [
"def",
"get_trans_mat",
"(",
"r_axis",
",",
"angle",
",",
"normal",
"=",
"False",
",",
"trans_cry",
"=",
"np",
".",
"eye",
"(",
"3",
")",
",",
"lat_type",
"=",
"'c'",
",",
"ratio",
"=",
"None",
",",
"surface",
"=",
"None",
",",
"max_search",
"=",
"... | 51.854875 | 0.002446 |
def _process_pathway(self, row):
"""
Process row of CTD data from CTD_genes_pathways.tsv.gz
and generate triples
Args:
:param row (list): row of CTD data
Returns:
:return None
"""
model = Model(self.graph)
self._check_list_len(row, ... | [
"def",
"_process_pathway",
"(",
"self",
",",
"row",
")",
":",
"model",
"=",
"Model",
"(",
"self",
".",
"graph",
")",
"self",
".",
"_check_list_len",
"(",
"row",
",",
"4",
")",
"(",
"gene_symbol",
",",
"gene_id",
",",
"pathway_name",
",",
"pathway_id",
... | 33.897436 | 0.001471 |
def _GetAction(self, action, text):
"""Parse the well known actions for easy reading.
Args:
action (str): the function or action called by the agent.
text (str): mac Wifi log text.
Returns:
str: a formatted string representing the known (or common) action.
If the action is no... | [
"def",
"_GetAction",
"(",
"self",
",",
"action",
",",
"text",
")",
":",
"# TODO: replace \"x in y\" checks by startswith if possible.",
"if",
"'airportdProcessDLILEvent'",
"in",
"action",
":",
"interface",
"=",
"text",
".",
"split",
"(",
")",
"[",
"0",
"]",
"retur... | 31.47619 | 0.008804 |
def _yarn_cluster_metrics(self, rm_address, instance, addl_tags):
"""
Get metrics related to YARN cluster
"""
metrics_json = self._rest_request_to_json(rm_address, instance, YARN_CLUSTER_METRICS_PATH, addl_tags)
if metrics_json:
yarn_metrics = metrics_json[YARN_CLUS... | [
"def",
"_yarn_cluster_metrics",
"(",
"self",
",",
"rm_address",
",",
"instance",
",",
"addl_tags",
")",
":",
"metrics_json",
"=",
"self",
".",
"_rest_request_to_json",
"(",
"rm_address",
",",
"instance",
",",
"YARN_CLUSTER_METRICS_PATH",
",",
"addl_tags",
")",
"if... | 38.916667 | 0.008368 |
def parse(cls, trust_root):
"""
This method creates a C{L{TrustRoot}} instance from the given
input, if possible.
@param trust_root: This is the trust root to parse into a
C{L{TrustRoot}} object.
@type trust_root: C{str}
@return: A C{L{TrustRoot}} instance if... | [
"def",
"parse",
"(",
"cls",
",",
"trust_root",
")",
":",
"url_parts",
"=",
"_parseURL",
"(",
"trust_root",
")",
"if",
"url_parts",
"is",
"None",
":",
"return",
"None",
"proto",
",",
"host",
",",
"port",
",",
"path",
"=",
"url_parts",
"# check for valid pro... | 26.098039 | 0.001448 |
def get_dict(self, exclude_keys=None, include_keys=None):
"""
return dictionary of keys and values corresponding to this model's
data - if include_keys is null the function will return all keys
:param exclude_keys: (optional) is a list of columns from model that
should not be re... | [
"def",
"get_dict",
"(",
"self",
",",
"exclude_keys",
"=",
"None",
",",
"include_keys",
"=",
"None",
")",
":",
"d",
"=",
"{",
"}",
"exclude_keys_list",
"=",
"exclude_keys",
"or",
"[",
"]",
"include_keys_list",
"=",
"include_keys",
"or",
"[",
"]",
"for",
"... | 39.85 | 0.002451 |
def to_n_ref(self, fill=0, dtype='i1'):
"""Transform each genotype call into the number of
reference alleles.
Parameters
----------
fill : int, optional
Use this value to represent missing calls.
dtype : dtype, optional
Output dtype.
Retu... | [
"def",
"to_n_ref",
"(",
"self",
",",
"fill",
"=",
"0",
",",
"dtype",
"=",
"'i1'",
")",
":",
"# count number of alternate alleles",
"out",
"=",
"np",
".",
"empty",
"(",
"self",
".",
"shape",
"[",
":",
"-",
"1",
"]",
",",
"dtype",
"=",
"dtype",
")",
... | 27.316667 | 0.001178 |
def Seq(sequence, annotations=None, block_length=10, blocks_per_line=6,
style=DEFAULT_STYLE):
"""
Pretty-printed sequence object that's displayed nicely in the IPython
Notebook.
:arg style: Custom CSS as a `format string`, where a selector for the
top-level ``<pre>`` element is substitu... | [
"def",
"Seq",
"(",
"sequence",
",",
"annotations",
"=",
"None",
",",
"block_length",
"=",
"10",
",",
"blocks_per_line",
"=",
"6",
",",
"style",
"=",
"DEFAULT_STYLE",
")",
":",
"seq_id",
"=",
"'monoseq-'",
"+",
"binascii",
".",
"hexlify",
"(",
"os",
".",
... | 41.52 | 0.000942 |
def _filter_stmts(self, stmts, frame, offset):
"""Filter the given list of statements to remove ignorable statements.
If self is not a frame itself and the name is found in the inner
frame locals, statements will be filtered to remove ignorable
statements according to self's location.
... | [
"def",
"_filter_stmts",
"(",
"self",
",",
"stmts",
",",
"frame",
",",
"offset",
")",
":",
"# if offset == -1, my actual frame is not the inner frame but its parent",
"#",
"# class A(B): pass",
"#",
"# we need this to resolve B correctly",
"if",
"offset",
"==",
"-",
"1",
"... | 40.17931 | 0.001508 |
def eps_logo( matrix, base_width, height, colors=DNA_DEFAULT_COLORS ):
"""
Return an EPS document containing a sequence logo for matrix where each
bases is shown as a column of `base_width` points and the total logo
height is `height` points. If `colors` is provided it is a mapping from
characters t... | [
"def",
"eps_logo",
"(",
"matrix",
",",
"base_width",
",",
"height",
",",
"colors",
"=",
"DNA_DEFAULT_COLORS",
")",
":",
"alphabet",
"=",
"matrix",
".",
"sorted_alphabet",
"rval",
"=",
"StringIO",
"(",
")",
"# Read header ans substitute in width / height",
"header",
... | 46.457143 | 0.033133 |
def install(self, release_id, upgrade=False):
"""Install target packages into a virtual environment.
If the virtual environment for the given release ID does not
exist on the remote system, it will be created. The virtual
environment will be created according to the standard Tunic
... | [
"def",
"install",
"(",
"self",
",",
"release_id",
",",
"upgrade",
"=",
"False",
")",
":",
"release_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_releases",
",",
"release_id",
")",
"if",
"not",
"self",
".",
"_runner",
".",
"exists",
... | 44.947368 | 0.001146 |
def finder(package):
"""
Return a resource finder for a package.
:param package: The name of the package.
:return: A :class:`ResourceFinder` instance for the package.
"""
if package in _finder_cache:
result = _finder_cache[package]
else:
if package not in sys.modules:
... | [
"def",
"finder",
"(",
"package",
")",
":",
"if",
"package",
"in",
"_finder_cache",
":",
"result",
"=",
"_finder_cache",
"[",
"package",
"]",
"else",
":",
"if",
"package",
"not",
"in",
"sys",
".",
"modules",
":",
"__import__",
"(",
"package",
")",
"module... | 38.521739 | 0.001101 |
def set_default_waveset(minwave=500, maxwave=26000, num=10000,
delta=None, log=True):
"""Set the default wavelength set, ``pysynphot.refs._default_waveset``.
Parameters
----------
minwave, maxwave : float, optional
The start (inclusive) and end (exclusive) points of the ... | [
"def",
"set_default_waveset",
"(",
"minwave",
"=",
"500",
",",
"maxwave",
"=",
"26000",
",",
"num",
"=",
"10000",
",",
"delta",
"=",
"None",
",",
"log",
"=",
"True",
")",
":",
"global",
"_default_waveset",
"global",
"_default_waveset_str",
"# Must be int for n... | 30.965517 | 0.00054 |
def _always_running_service(name):
'''
Check if the service should always be running based on the KeepAlive Key
in the service plist.
:param str name: Service label, file name, or full path
:return: True if the KeepAlive key is set to True, False if set to False or
not set in the plist at ... | [
"def",
"_always_running_service",
"(",
"name",
")",
":",
"# get all the info from the launchctl service",
"service_info",
"=",
"show",
"(",
"name",
")",
"# get the value for the KeepAlive key in service plist",
"try",
":",
"keep_alive",
"=",
"service_info",
"[",
"'plist'",
... | 27.105263 | 0.000937 |
def brpop(self, keys, timeout=0):
"""Emulate brpop"""
return self._blocking_pop(self.rpop, keys, timeout) | [
"def",
"brpop",
"(",
"self",
",",
"keys",
",",
"timeout",
"=",
"0",
")",
":",
"return",
"self",
".",
"_blocking_pop",
"(",
"self",
".",
"rpop",
",",
"keys",
",",
"timeout",
")"
] | 39.666667 | 0.016529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.