text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_fastq_dir(fc_dir):
"""Retrieve the fastq directory within Solexa flowcell output.
"""
full_goat_bc = glob.glob(os.path.join(fc_dir, "Data", "*Firecrest*", "Bustard*"))
bustard_bc = glob.glob(os.path.join(fc_dir, "Data", "Intensities", "*Bustard*"))
machine_bc = os.path.join(fc_dir, "Data", "... | [
"def",
"get_fastq_dir",
"(",
"fc_dir",
")",
":",
"full_goat_bc",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"fc_dir",
",",
"\"Data\"",
",",
"\"*Firecrest*\"",
",",
"\"Bustard*\"",
")",
")",
"bustard_bc",
"=",
"glob",
".",
"glob",... | 45 | 0.004082 |
def _NewMatchSection(self, val):
"""Create a new configuration section for each match clause.
Each match clause is added to the main config, and the criterion that will
trigger the match is recorded, as is the configuration.
Args:
val: The value following the 'match' keyword.
"""
section... | [
"def",
"_NewMatchSection",
"(",
"self",
",",
"val",
")",
":",
"section",
"=",
"{",
"\"criterion\"",
":",
"val",
",",
"\"config\"",
":",
"{",
"}",
"}",
"self",
".",
"matches",
".",
"append",
"(",
"section",
")",
"# Now add configuration items to config section ... | 39.266667 | 0.001658 |
def _inline_activate_venv():
"""Built-in venv doesn't have activate_this.py, but doesn't need it anyway.
As long as we find the correct executable, built-in venv sets up the
environment automatically.
See: https://bugs.python.org/issue21496#msg218455
"""
components = []
for name in ("bin",... | [
"def",
"_inline_activate_venv",
"(",
")",
":",
"components",
"=",
"[",
"]",
"for",
"name",
"in",
"(",
"\"bin\"",
",",
"\"Scripts\"",
")",
":",
"bindir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"project",
".",
"virtualenv_location",
",",
"name",
")",
... | 36.4375 | 0.001672 |
def setupQuery(self, query, op, editor):
"""
Returns the value from the editor.
:param op | <str>
editor | <QWidget> || None
:return <bool> | success
"""
try:
registry = self._operatorMap[natives... | [
"def",
"setupQuery",
"(",
"self",
",",
"query",
",",
"op",
",",
"editor",
")",
":",
"try",
":",
"registry",
"=",
"self",
".",
"_operatorMap",
"[",
"nativestring",
"(",
"op",
")",
"]",
"except",
"KeyError",
":",
"return",
"False",
"op",
"=",
"registry",... | 26.038462 | 0.011396 |
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Opt... | [
"def",
"update_subnet",
"(",
"subnet",
",",
"name",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"update_subnet",
"(",
"subnet",
",",
"name",
")"
] | 25.705882 | 0.002208 |
def create_transcripts_xml(video_id, video_el, resource_fs, static_dir):
"""
Creates xml for transcripts.
For each transcript element, an associated transcript file is also created in course OLX.
Arguments:
video_id (str): Video id of the video.
video_el (Element): lxml Element object
... | [
"def",
"create_transcripts_xml",
"(",
"video_id",
",",
"video_el",
",",
"resource_fs",
",",
"static_dir",
")",
":",
"video_transcripts",
"=",
"VideoTranscript",
".",
"objects",
".",
"filter",
"(",
"video__edx_video_id",
"=",
"video_id",
")",
".",
"order_by",
"(",
... | 40.897959 | 0.002924 |
def doGetAttrib(self, attribId):
"""get an attribute
attribId: Identifier for the attribute to get
return: response are the attribute byte array
"""
CardConnection.doGetAttrib(self, attribId)
hresult, response = SCardGetAttrib(self.hcard, attribId)
if hresult ... | [
"def",
"doGetAttrib",
"(",
"self",
",",
"attribId",
")",
":",
"CardConnection",
".",
"doGetAttrib",
"(",
"self",
",",
"attribId",
")",
"hresult",
",",
"response",
"=",
"SCardGetAttrib",
"(",
"self",
".",
"hcard",
",",
"attribId",
")",
"if",
"hresult",
"!="... | 34.384615 | 0.004357 |
def isIdentity(M, tol=1e-06):
"""Check if vtkMatrix4x4 is Identity."""
for i in [0, 1, 2, 3]:
for j in [0, 1, 2, 3]:
e = M.GetElement(i, j)
if i == j:
if np.abs(e - 1) > tol:
return False
elif np.abs(e) > tol:
return... | [
"def",
"isIdentity",
"(",
"M",
",",
"tol",
"=",
"1e-06",
")",
":",
"for",
"i",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
":",
"for",
"j",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
":",
"e",
"=",
"M",
".",
"GetElement",... | 30.181818 | 0.002924 |
def _init_journal(self, permissive=True):
"""Add the initialization lines to the journal.
By default adds JrnObj variable and timestamp to the journal contents.
Args:
permissive (bool): if True most errors in journal will not
cause Revit to stop journ... | [
"def",
"_init_journal",
"(",
"self",
",",
"permissive",
"=",
"True",
")",
":",
"nowstamp",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%d-%b-%Y %H:%M:%S.%f\"",
")",
"[",
":",
"-",
"3",
"]",
"self",
".",
"_add_entry",
"(",
"templates",... | 41.6 | 0.003135 |
def _configure_buffer_sizes():
"""Set up module globals controlling buffer sizes"""
global PIPE_BUF_BYTES
global OS_PIPE_SZ
PIPE_BUF_BYTES = 65536
OS_PIPE_SZ = None
# Teach the 'fcntl' module about 'F_SETPIPE_SZ', which is a Linux-ism,
# but a good one that can drastically reduce the numbe... | [
"def",
"_configure_buffer_sizes",
"(",
")",
":",
"global",
"PIPE_BUF_BYTES",
"global",
"OS_PIPE_SZ",
"PIPE_BUF_BYTES",
"=",
"65536",
"OS_PIPE_SZ",
"=",
"None",
"# Teach the 'fcntl' module about 'F_SETPIPE_SZ', which is a Linux-ism,",
"# but a good one that can drastically reduce the ... | 36.296296 | 0.000994 |
def sdiv(a, b):
"""Safe division: if a == b == 0, sdiv(a, b) == 1"""
if len(a) != len(b):
raise ValueError('Argument a and b does not have the same length')
idx = 0
ret = matrix(0, (len(a), 1), 'd')
for m, n in zip(a, b):
try:
ret[idx] = m / n
except ZeroDivisionE... | [
"def",
"sdiv",
"(",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"raise",
"ValueError",
"(",
"'Argument a and b does not have the same length'",
")",
"idx",
"=",
"0",
"ret",
"=",
"matrix",
"(",
"0",
",",
"(",
... | 27.857143 | 0.002481 |
def _is_potential_multi_index(columns):
"""
Check whether or not the `columns` parameter
could be converted into a MultiIndex.
Parameters
----------
columns : array-like
Object which may or may not be convertible into a MultiIndex
Returns
-------
boolean : Whether or not co... | [
"def",
"_is_potential_multi_index",
"(",
"columns",
")",
":",
"return",
"(",
"len",
"(",
"columns",
")",
"and",
"not",
"isinstance",
"(",
"columns",
",",
"MultiIndex",
")",
"and",
"all",
"(",
"isinstance",
"(",
"c",
",",
"tuple",
")",
"for",
"c",
"in",
... | 29.3125 | 0.002066 |
def feed(self, data):
"""
Add new incoming data to buffer and try to process
"""
self.buffer += data
while len(self.buffer) >= 6:
self.next_packet() | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"buffer",
"+=",
"data",
"while",
"len",
"(",
"self",
".",
"buffer",
")",
">=",
"6",
":",
"self",
".",
"next_packet",
"(",
")"
] | 27.714286 | 0.01 |
def get_activity_ids_by_objective_bank(self, objective_bank_id):
"""Gets the list of ``Activity`` ``Ids`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.id.IdList) - list of related activity ``Ids``
... | [
"def",
"get_activity_ids_by_objective_bank",
"(",
"self",
",",
"objective_bank_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_resource_ids_by_bin",
"id_list",
"=",
"[",
"]",
"for",
"activity",
"in",
"self",
".",
"get_activities_by_obje... | 48 | 0.004301 |
def removeLastRow(self):
"""Removes the last track"""
lastrow = self._segments.pop(len(self._segments)-1)
if len(lastrow) > 0:
raise Exception("Attempt to remove non-empty stimulus track") | [
"def",
"removeLastRow",
"(",
"self",
")",
":",
"lastrow",
"=",
"self",
".",
"_segments",
".",
"pop",
"(",
"len",
"(",
"self",
".",
"_segments",
")",
"-",
"1",
")",
"if",
"len",
"(",
"lastrow",
")",
">",
"0",
":",
"raise",
"Exception",
"(",
"\"Attem... | 44 | 0.008929 |
def runOnExecutor(self, *commands, oper=ACCEPT, defer_shell_expansion=False):
""" This runs in the executor of the current scope.
You cannot magically back out since there are no
gurantees that ssh keys will be in place (they shouldn't be). """
return self.makeOutput(EXE, command... | [
"def",
"runOnExecutor",
"(",
"self",
",",
"*",
"commands",
",",
"oper",
"=",
"ACCEPT",
",",
"defer_shell_expansion",
"=",
"False",
")",
":",
"return",
"self",
".",
"makeOutput",
"(",
"EXE",
",",
"commands",
",",
"oper",
"=",
"oper",
",",
"defer_shell_expan... | 74.8 | 0.007937 |
def saveAsPickleFile(self, path, batchSize=10):
"""
Save this RDD as a SequenceFile of serialized objects. The serializer
used is L{pyspark.serializers.PickleSerializer}, default batch size
is 10.
>>> tmpFile = NamedTemporaryFile(delete=True)
>>> tmpFile.close()
... | [
"def",
"saveAsPickleFile",
"(",
"self",
",",
"path",
",",
"batchSize",
"=",
"10",
")",
":",
"if",
"batchSize",
"==",
"0",
":",
"ser",
"=",
"AutoBatchedSerializer",
"(",
"PickleSerializer",
"(",
")",
")",
"else",
":",
"ser",
"=",
"BatchedSerializer",
"(",
... | 42.647059 | 0.004049 |
def main(args=None):
"""The entry point of the application."""
if args is None:
args = sys.argv[1:]
# Parse command-line
args = docopt(__doc__, argv=args)
# Parse arguments
path, address = resolve(args['<path>'], args['<address>'])
host, port = split_address(address)
# Validat... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"# Parse command-line",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"argv",
"=",
"args",
")",
"# Parse arguments"... | 23.925926 | 0.001488 |
def register_all_shape_checker(shape_checker_function,
arg_types,
exclude=(),
ignore_existing=False):
"""Register a gradient adder for all combinations of given types.
This is a convenience shorthand for calling register_a... | [
"def",
"register_all_shape_checker",
"(",
"shape_checker_function",
",",
"arg_types",
",",
"exclude",
"=",
"(",
")",
",",
"ignore_existing",
"=",
"False",
")",
":",
"for",
"t1",
"in",
"arg_types",
":",
"for",
"t2",
"in",
"arg_types",
":",
"if",
"(",
"t1",
... | 40.32 | 0.006783 |
def generate_kmers(seq, k=4):
"""Return a generator of all the unique substrings (k-mer or q-gram strings) within a sequence/string
Not effiicent for large k and long strings.
Doesn't form substrings that are shorter than k, only exactly k-mers
Used for algorithms like UniqTag for genome unique identi... | [
"def",
"generate_kmers",
"(",
"seq",
",",
"k",
"=",
"4",
")",
":",
"if",
"isinstance",
"(",
"seq",
",",
"basestring",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"seq",
")",
"-",
"k",
"+",
"1",
")",
":",
"yield",
"seq",
"[",
"i",
":... | 41.714286 | 0.005021 |
def make_exception_message(exc):
"""
An exception is passed in and this function
returns the proper string depending on the result
so it is readable enough.
"""
if str(exc):
return '%s: %s\n' % (exc.__class__.__name__, exc)
else:
return '%s\n' % (exc.__class__.__name__) | [
"def",
"make_exception_message",
"(",
"exc",
")",
":",
"if",
"str",
"(",
"exc",
")",
":",
"return",
"'%s: %s\\n'",
"%",
"(",
"exc",
".",
"__class__",
".",
"__name__",
",",
"exc",
")",
"else",
":",
"return",
"'%s\\n'",
"%",
"(",
"exc",
".",
"__class__",... | 30.5 | 0.003185 |
def _observers_for_notification(self, ntype, sender):
"""Find all registered observers that should recieve notification"""
keys = (
(ntype,sender),
(ntype, None),
(None, sender),
(None,None)
)
obs = set(... | [
"def",
"_observers_for_notification",
"(",
"self",
",",
"ntype",
",",
"sender",
")",
":",
"keys",
"=",
"(",
"(",
"ntype",
",",
"sender",
")",
",",
"(",
"ntype",
",",
"None",
")",
",",
"(",
"None",
",",
"sender",
")",
",",
"(",
"None",
",",
"None",
... | 26.866667 | 0.009592 |
def clip_datetime(dt, tz=DEFAULT_TZ, is_dst=None):
"""Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects
>>> from datetime import timedelta
>>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP
True
>>> MAX_TIMESTAMP
... | [
"def",
"clip_datetime",
"(",
"dt",
",",
"tz",
"=",
"DEFAULT_TZ",
",",
"is_dst",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"datetime",
".",
"datetime",
")",
":",
"# TODO: this gives up a day of datetime range due to assumptions about timezone",
"# ... | 40.956522 | 0.005187 |
def default():
"""Default configuration for PPO."""
# General
algorithm = algorithms.PPO
num_agents = 30
eval_episodes = 30
use_gpu = False
# Environment
normalize_ranges = True
# Network
network = networks.feed_forward_gaussian
weight_summaries = dict(
all=r'.*', policy=r'.*/policy/.*', val... | [
"def",
"default",
"(",
")",
":",
"# General",
"algorithm",
"=",
"algorithms",
".",
"PPO",
"num_agents",
"=",
"30",
"eval_episodes",
"=",
"30",
"use_gpu",
"=",
"False",
"# Environment",
"normalize_ranges",
"=",
"True",
"# Network",
"network",
"=",
"networks",
"... | 22.827586 | 0.04058 |
def inject_scheme(self, b16_scheme):
"""Inject string $b16_scheme into self.content."""
# correctly formatted start and end of block should have already been
# ascertained by _get_temp
content_lines = self.content.splitlines()
b16_scheme_lines = b16_scheme.splitlines()
st... | [
"def",
"inject_scheme",
"(",
"self",
",",
"b16_scheme",
")",
":",
"# correctly formatted start and end of block should have already been",
"# ascertained by _get_temp",
"content_lines",
"=",
"self",
".",
"content",
".",
"splitlines",
"(",
")",
"b16_scheme_lines",
"=",
"b16_... | 40.5 | 0.002193 |
def as_representer(resource, content_type):
"""
Adapts the given resource and content type to a representer.
:param resource: resource to adapt.
:param str content_type: content (MIME) type to obtain a representer for.
"""
reg = get_current_registry()
rpr_reg = reg.queryUtility(IRepresenter... | [
"def",
"as_representer",
"(",
"resource",
",",
"content_type",
")",
":",
"reg",
"=",
"get_current_registry",
"(",
")",
"rpr_reg",
"=",
"reg",
".",
"queryUtility",
"(",
"IRepresenterRegistry",
")",
"return",
"rpr_reg",
".",
"create",
"(",
"type",
"(",
"resource... | 37.6 | 0.002597 |
def decimate_mean(self, a, maxpoints, **kwargs):
"""Return data *a* mean-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the weighted average in each bin as the decimated data, using
:func:`numkit.timeseries.mean_histogrammed_function`. The coarse g... | [
"def",
"decimate_mean",
"(",
"self",
",",
"a",
",",
"maxpoints",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_decimate",
"(",
"numkit",
".",
"timeseries",
".",
"mean_histogrammed_function",
",",
"a",
",",
"maxpoints",
",",
"*",
"*",
"kwarg... | 40.421053 | 0.005089 |
def _btc_script_serialize_unit(unit):
"""
Encode one item of a BTC script
Return the encoded item (as a string)
Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools)
by Vitalik Buterin
"""
if isinstance(unit, int):
# cannot be less than -1, since btc_sc... | [
"def",
"_btc_script_serialize_unit",
"(",
"unit",
")",
":",
"if",
"isinstance",
"(",
"unit",
",",
"int",
")",
":",
"# cannot be less than -1, since btc_script_deserialize() never returns such numbers",
"if",
"unit",
"<",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'In... | 37.727273 | 0.00411 |
def _fill_naked_singles(self):
"""Look for naked singles, i.e. cells with ony one possible value.
:return: If any Naked Single has been found.
:rtype: bool
"""
simple_found = False
for i in utils.range_(self.side):
for j in utils.range_(self.side):
... | [
"def",
"_fill_naked_singles",
"(",
"self",
")",
":",
"simple_found",
"=",
"False",
"for",
"i",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"for",
"j",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"if",
"se... | 38 | 0.00489 |
def detect(self):
"""Detect all currently known devices. Returns the root device."""
root = self._actions.detect()
prune_empty_node(root, set())
return root | [
"def",
"detect",
"(",
"self",
")",
":",
"root",
"=",
"self",
".",
"_actions",
".",
"detect",
"(",
")",
"prune_empty_node",
"(",
"root",
",",
"set",
"(",
")",
")",
"return",
"root"
] | 36.8 | 0.010638 |
def export_diagram_plane_elements(root, diagram_attributes, plane_attributes):
"""
Creates 'diagram' and 'plane' elements for exported BPMN XML file.
Returns a tuple (diagram, plane).
:param root: object of Element class, representing a BPMN XML root element ('definitions'),
:pa... | [
"def",
"export_diagram_plane_elements",
"(",
"root",
",",
"diagram_attributes",
",",
"plane_attributes",
")",
":",
"diagram",
"=",
"eTree",
".",
"SubElement",
"(",
"root",
",",
"BpmnDiagramGraphExport",
".",
"bpmndi_namespace",
"+",
"\"BPMNDiagram\"",
")",
"diagram",
... | 59.222222 | 0.007387 |
def random_draw(self, size=None):
"""Draw random samples of the hyperparameters.
Parameters
----------
size : None, int or array-like, optional
The number/shape of samples to draw. If None, only one sample is
returned. Default is None.
"""
... | [
"def",
"random_draw",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"return",
"scipy",
".",
"asarray",
"(",
"[",
"scipy",
".",
"stats",
".",
"gamma",
".",
"rvs",
"(",
"a",
",",
"loc",
"=",
"0",
",",
"scale",
"=",
"1.0",
"/",
"b",
",",
"size"... | 42.5 | 0.009217 |
def orientation(self):
"""
The angle in radians between the ``x`` axis and the major axis
of the 2D Gaussian function that has the same second-order
moments as the source. The angle increases in the
counter-clockwise direction.
"""
a, b, b, c = self.covariance.f... | [
"def",
"orientation",
"(",
"self",
")",
":",
"a",
",",
"b",
",",
"b",
",",
"c",
"=",
"self",
".",
"covariance",
".",
"flat",
"if",
"a",
"<",
"0",
"or",
"c",
"<",
"0",
":",
"# negative variance",
"return",
"np",
".",
"nan",
"*",
"u",
".",
"rad",... | 38.75 | 0.004202 |
def _ewp_iccarm_set(self, ewp_dic, project_dic):
""" C/C++ options (ICCARM) """
index_iccarm = self._get_option(ewp_dic, 'ICCARM')
index_option = self._get_option(ewp_dic[index_iccarm]['data']['option'], 'CCDefines')
self._set_multiple_option(ewp_dic[index_iccarm]['data']['option'][index... | [
"def",
"_ewp_iccarm_set",
"(",
"self",
",",
"ewp_dic",
",",
"project_dic",
")",
":",
"index_iccarm",
"=",
"self",
".",
"_get_option",
"(",
"ewp_dic",
",",
"'ICCARM'",
")",
"index_option",
"=",
"self",
".",
"_get_option",
"(",
"ewp_dic",
"[",
"index_iccarm",
... | 73.818182 | 0.009732 |
def set(self, key, value):
"""Set a value in the `Bison` configuration.
Args:
key (str): The configuration key to set a new value for.
value: The value to set.
"""
# the configuration changes, so we invalidate the cached config
self._full_config = None
... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# the configuration changes, so we invalidate the cached config",
"self",
".",
"_full_config",
"=",
"None",
"self",
".",
"_override",
"[",
"key",
"]",
"=",
"value"
] | 34.4 | 0.005666 |
def check_dict(self, opt, value):
'''Take json as dictionary parameter'''
try:
return json.loads(value)
except:
raise optparse.OptionValueError("Option %s: invalid dict value: %r" % (opt, value)) | [
"def",
"check_dict",
"(",
"self",
",",
"opt",
",",
"value",
")",
":",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"value",
")",
"except",
":",
"raise",
"optparse",
".",
"OptionValueError",
"(",
"\"Option %s: invalid dict value: %r\"",
"%",
"(",
"opt",
... | 35.666667 | 0.022831 |
def run(module_name, args=None, env_vars=None, wait=True, capture_error=False):
# type: (str, list, dict, bool, bool) -> subprocess.Popen
"""Run Python module as a script.
Search sys.path for the named module and execute its contents as the __main__ module.
Since the argument is a module name, you mus... | [
"def",
"run",
"(",
"module_name",
",",
"args",
"=",
"None",
",",
"env_vars",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"capture_error",
"=",
"False",
")",
":",
"# type: (str, list, dict, bool, bool) -> subprocess.Popen",
"args",
"=",
"args",
"or",
"[",
"]",
... | 50.328125 | 0.006699 |
def crown(self, depth=2):
""" Returns a list of leaves, nodes connected to leaves, etc.
"""
nodes = []
for node in self.leaves: nodes += node.flatten(depth-1)
return cluster.unique(nodes) | [
"def",
"crown",
"(",
"self",
",",
"depth",
"=",
"2",
")",
":",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"leaves",
":",
"nodes",
"+=",
"node",
".",
"flatten",
"(",
"depth",
"-",
"1",
")",
"return",
"cluster",
".",
"unique",
"(",
... | 37 | 0.013216 |
def format(self, indent_level, indent_size=4):
"""Format this verifier
Returns:
string: A formatted string
"""
desc = self.format_name('String')
return self.wrap_lines(desc, indent_level, indent_size=indent_size) | [
"def",
"format",
"(",
"self",
",",
"indent_level",
",",
"indent_size",
"=",
"4",
")",
":",
"desc",
"=",
"self",
".",
"format_name",
"(",
"'String'",
")",
"return",
"self",
".",
"wrap_lines",
"(",
"desc",
",",
"indent_level",
",",
"indent_size",
"=",
"ind... | 28.666667 | 0.007519 |
def in_book_search(request):
"""Full text, in-book search."""
results = {}
args = request.matchdict
ident_hash = args['ident_hash']
args['search_term'] = request.params.get('q', '')
query_type = request.params.get('query_type', '')
combiner = ''
if query_type:
if query_type.low... | [
"def",
"in_book_search",
"(",
"request",
")",
":",
"results",
"=",
"{",
"}",
"args",
"=",
"request",
".",
"matchdict",
"ident_hash",
"=",
"args",
"[",
"'ident_hash'",
"]",
"args",
"[",
"'search_term'",
"]",
"=",
"request",
".",
"params",
".",
"get",
"(",... | 33.627451 | 0.000567 |
def assign_highest_value(exposure, hazard):
"""Assign the highest hazard value to an indivisible feature.
For indivisible polygon exposure layers such as buildings, we need to
assigned the greatest hazard that each polygon touches and use that as the
effective hazard class.
Issue https://github.co... | [
"def",
"assign_highest_value",
"(",
"exposure",
",",
"hazard",
")",
":",
"output_layer_name",
"=",
"assign_highest_value_steps",
"[",
"'output_layer_name'",
"]",
"hazard_inasafe_fields",
"=",
"hazard",
".",
"keywords",
"[",
"'inasafe_fields'",
"]",
"if",
"not",
"hazar... | 36.481818 | 0.000243 |
def __threshold(self, ymx_i):
"""
Calculates the difference threshold for a
given difference local maximum.
Parameters
-----------
ymx_i : float
The normalized y value of a local maximum.
"""
return ymx_i - (self.S * np.diff(self.xsn).mean()) | [
"def",
"__threshold",
"(",
"self",
",",
"ymx_i",
")",
":",
"return",
"ymx_i",
"-",
"(",
"self",
".",
"S",
"*",
"np",
".",
"diff",
"(",
"self",
".",
"xsn",
")",
".",
"mean",
"(",
")",
")"
] | 28.090909 | 0.009404 |
def load_gifti(filename, to='auto'):
'''
load_gifti(filename) yields the nibabel gifti data structure loaded by nibabel from the given
filename. Currently, this load method is not particlarly sophisticated and simply returns this
data.
The optional argument to may be used to coerce the resu... | [
"def",
"load_gifti",
"(",
"filename",
",",
"to",
"=",
"'auto'",
")",
":",
"dat",
"=",
"nib",
".",
"load",
"(",
"filename",
")",
"to",
"=",
"'raw'",
"if",
"to",
"is",
"None",
"else",
"to",
".",
"lower",
"(",
")",
"if",
"to",
"in",
"[",
"'raw'",
... | 50.596774 | 0.007505 |
def ge(self, value):
"""Construct a greater than or equal to (``>=``) filter.
:param value: Filter value
:return: :class:`filters.Field <filters.Field>` object
:rtype: filters.Field
"""
self.op = '>='
self.negate_op = '<'
self.value = self._value(value)
... | [
"def",
"ge",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"op",
"=",
"'>='",
"self",
".",
"negate_op",
"=",
"'<'",
"self",
".",
"value",
"=",
"self",
".",
"_value",
"(",
"value",
")",
"return",
"self"
] | 29.818182 | 0.005917 |
def reduce(self, mapped_props, aggregated, value_type, visitor):
"""This reduction is called to combine the mapped slot and collection
item values into a single value for return.
The default implementation tries to behave naturally; you'll almost
always get a dict back when mapping over... | [
"def",
"reduce",
"(",
"self",
",",
"mapped_props",
",",
"aggregated",
",",
"value_type",
",",
"visitor",
")",
":",
"reduced",
"=",
"None",
"if",
"mapped_props",
":",
"reduced",
"=",
"dict",
"(",
"(",
"k",
".",
"name",
",",
"v",
")",
"for",
"k",
",",
... | 41.291667 | 0.002957 |
def sum(self, axis=None, dtype=None, out=None, keepdims=False):
"""Return the sum of ``self``.
See Also
--------
numpy.sum
prod
"""
return self.elem.__array_ufunc__(
np.add, 'reduce', self.elem,
axis=axis, dtype=dtype, out=(out,), keepdims... | [
"def",
"sum",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"return",
"self",
".",
"elem",
".",
"__array_ufunc__",
"(",
"np",
".",
"add",
",",
"'reduce'",
",",
... | 29.090909 | 0.006061 |
def google_analytics(parser, token):
"""
Google Analytics tracking template tag.
Renders Javascript code to track page visits. You must supply
your website property ID (as a string) in the
``GOOGLE_ANALYTICS_PROPERTY_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
... | [
"def",
"google_analytics",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
">",
"1",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes no arguments\"",
"%",
"bits",
"[",
"0"... | 34.083333 | 0.002381 |
def minValue(self, value):
"""gets/sets the min value"""
if isinstance(value, [int, float, long]):
self._rangeMin = value | [
"def",
"minValue",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"[",
"int",
",",
"float",
",",
"long",
"]",
")",
":",
"self",
".",
"_rangeMin",
"=",
"value"
] | 36.5 | 0.013423 |
def nearest_roads(client, points):
"""Find the closest road segments for each point
Takes up to 100 independent coordinates, and returns the closest road
segment for each point. The points passed do not need to be part of a
continuous path.
:param points: The points for which the nearest road segm... | [
"def",
"nearest_roads",
"(",
"client",
",",
"points",
")",
":",
"params",
"=",
"{",
"\"points\"",
":",
"convert",
".",
"location_list",
"(",
"points",
")",
"}",
"return",
"client",
".",
"_request",
"(",
"\"/v1/nearestRoads\"",
",",
"params",
",",
"base_url",... | 37.285714 | 0.004981 |
def has_previous_assessment_section(self, assessment_section_id):
"""Tests if there is a previous assessment section in the assessment following the given assessment section ``Id``.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
return: (boolean)... | [
"def",
"has_previous_assessment_section",
"(",
"self",
",",
"assessment_section_id",
")",
":",
"try",
":",
"self",
".",
"get_previous_assessment_section",
"(",
"assessment_section_id",
")",
"except",
"errors",
".",
"IllegalState",
":",
"return",
"False",
"else",
":",
... | 47.047619 | 0.002976 |
def daemon(self):
"""
Return whether process is a daemon
:return:
"""
if self._process:
return self._process.daemon
else:
return self._pargs.get('daemonic', False) | [
"def",
"daemon",
"(",
"self",
")",
":",
"if",
"self",
".",
"_process",
":",
"return",
"self",
".",
"_process",
".",
"daemon",
"else",
":",
"return",
"self",
".",
"_pargs",
".",
"get",
"(",
"'daemonic'",
",",
"False",
")"
] | 25.222222 | 0.008511 |
def unselect(self, rows, status=True, progress=True):
"Unselect given rows. Don't show progress if progress=False; don't show status if status=False."
before = len(self._selectedRows)
for r in (Progress(rows, 'unselecting') if progress else rows):
self.unselectRow(r)
if statu... | [
"def",
"unselect",
"(",
"self",
",",
"rows",
",",
"status",
"=",
"True",
",",
"progress",
"=",
"True",
")",
":",
"before",
"=",
"len",
"(",
"self",
".",
"_selectedRows",
")",
"for",
"r",
"in",
"(",
"Progress",
"(",
"rows",
",",
"'unselecting'",
")",
... | 60 | 0.00939 |
def accept_default_labels(self, other):
"""Applies labels for default meta labels from other onto self.
Parameters
----------
other : Meta
Meta object to take default labels from
Returns
-------
Meta
"""
self... | [
"def",
"accept_default_labels",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"units_label",
"=",
"other",
".",
"units_label",
"self",
".",
"name_label",
"=",
"other",
".",
"name_label",
"self",
".",
"notes_label",
"=",
"other",
".",
"notes_label",
"self... | 29.2 | 0.006631 |
def get_html(self):
"""Method to convert the repository list to a search results page."""
here = path.abspath(path.dirname(__file__))
env = Environment(loader=FileSystemLoader(path.join(here, "res/")))
suggest = env.get_template("suggest.htm.j2")
return suggest.render(
... | [
"def",
"get_html",
"(",
"self",
")",
":",
"here",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"FileSystemLoader",
"(",
"path",
".",
"join",
"(",
"here",
",",
"\"r... | 35.333333 | 0.004598 |
def laplacian_pca(self, coordinates, num_dims=None, beta=0.5):
'''Graph-Laplacian PCA (CVPR 2013).
coordinates : (n,d) array-like, assumed to be mean-centered.
beta : float in [0,1], scales how much PCA/LapEig contributes.
Returns an approximation of input coordinates, ala PCA.'''
X = np.atleast_2d(... | [
"def",
"laplacian_pca",
"(",
"self",
",",
"coordinates",
",",
"num_dims",
"=",
"None",
",",
"beta",
"=",
"0.5",
")",
":",
"X",
"=",
"np",
".",
"atleast_2d",
"(",
"coordinates",
")",
"L",
"=",
"self",
".",
"laplacian",
"(",
"normed",
"=",
"True",
")",... | 47.375 | 0.003881 |
def query_walkers():
"""Return query walker instances."""
return [
import_string(walker)() if isinstance(walker, six.string_types)
else walker() for walker in current_app.config[
'COLLECTIONS_QUERY_WALKERS']
] | [
"def",
"query_walkers",
"(",
")",
":",
"return",
"[",
"import_string",
"(",
"walker",
")",
"(",
")",
"if",
"isinstance",
"(",
"walker",
",",
"six",
".",
"string_types",
")",
"else",
"walker",
"(",
")",
"for",
"walker",
"in",
"current_app",
".",
"config",... | 34.714286 | 0.004016 |
def do_raw(self, subcmd, opts, message):
"""${cmd_name}: dump the complete raw message
${cmd_usage}
"""
client = MdClient(self.maildir)
client.getraw(message, self.stdout) | [
"def",
"do_raw",
"(",
"self",
",",
"subcmd",
",",
"opts",
",",
"message",
")",
":",
"client",
"=",
"MdClient",
"(",
"self",
".",
"maildir",
")",
"client",
".",
"getraw",
"(",
"message",
",",
"self",
".",
"stdout",
")"
] | 29.428571 | 0.009434 |
def adjacent(self, other):
"""
Returns True if ranges are directly next to each other but does not
overlap.
>>> intrange(1, 5).adjacent(intrange(5, 10))
True
>>> intrange(1, 5).adjacent(intrange(10, 15))
False
The empty set is not adjacen... | [
"def",
"adjacent",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"self",
".",
"is_valid_range",
"(",
"other",
")",
":",
"raise",
"TypeError",
"(",
"\"Unsupported type to test for inclusion '{0.__class__.__name__}'\"",
".",
"format",
"(",
"other",
")",
")",
"... | 36.433333 | 0.003565 |
def get_queryset(self, request):
''' Restrict the listed assignments for the current user.'''
qs = super(AssignmentAdmin, self).get_queryset(request)
if not request.user.is_superuser:
qs = qs.filter(course__active=True).filter(Q(course__tutors__pk=request.user.pk) | Q(course__owner=r... | [
"def",
"get_queryset",
"(",
"self",
",",
"request",
")",
":",
"qs",
"=",
"super",
"(",
"AssignmentAdmin",
",",
"self",
")",
".",
"get_queryset",
"(",
"request",
")",
"if",
"not",
"request",
".",
"user",
".",
"is_superuser",
":",
"qs",
"=",
"qs",
".",
... | 62.5 | 0.007895 |
def convert_units(self, desired, guess=False):
"""
Convert the units of the mesh into a specified unit.
Parameters
----------
desired : string
Units to convert to (eg 'inches')
guess : boolean
If self.units are not defined should we
guess th... | [
"def",
"convert_units",
"(",
"self",
",",
"desired",
",",
"guess",
"=",
"False",
")",
":",
"units",
".",
"_convert_units",
"(",
"self",
",",
"desired",
",",
"guess",
")",
"return",
"self"
] | 31.357143 | 0.004425 |
def organize_models(self, outdir, force_rerun=False):
"""Organize and rename SWISS-MODEL models to a single folder with a name containing template information.
Args:
outdir (str): New directory to copy renamed models to
force_rerun (bool): If models should be copied again even i... | [
"def",
"organize_models",
"(",
"self",
",",
"outdir",
",",
"force_rerun",
"=",
"False",
")",
":",
"uniprot_to_swissmodel",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"u",
",",
"models",
"in",
"self",
".",
"all_models",
".",
"items",
"(",
")",
":",
"for... | 50.461538 | 0.005984 |
def editfile(fpath):
""" Runs gvim. Can also accept a module / class / function """
if not isinstance(fpath, six.string_types):
from six import types
print('Rectify to module fpath = %r' % (fpath,))
if isinstance(fpath, types.ModuleType):
fpath = fpath.__file__
else:
... | [
"def",
"editfile",
"(",
"fpath",
")",
":",
"if",
"not",
"isinstance",
"(",
"fpath",
",",
"six",
".",
"string_types",
")",
":",
"from",
"six",
"import",
"types",
"print",
"(",
"'Rectify to module fpath = %r'",
"%",
"(",
"fpath",
",",
")",
")",
"if",
"isin... | 35.466667 | 0.002745 |
def register(linter):
"""required method to auto register this checker"""
linter.register_checker(EncodingChecker(linter))
linter.register_checker(ByIdManagedMessagesChecker(linter)) | [
"def",
"register",
"(",
"linter",
")",
":",
"linter",
".",
"register_checker",
"(",
"EncodingChecker",
"(",
"linter",
")",
")",
"linter",
".",
"register_checker",
"(",
"ByIdManagedMessagesChecker",
"(",
"linter",
")",
")"
] | 47.75 | 0.005155 |
def get_service_by_name(self, name):
"""
Implementation of :meth:`twitcher.api.IRegistry.get_service_by_name`.
"""
try:
service = self.store.fetch_by_name(name=name)
except Exception:
LOGGER.error('Could not get service with name %s', name)
ret... | [
"def",
"get_service_by_name",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"service",
"=",
"self",
".",
"store",
".",
"fetch_by_name",
"(",
"name",
"=",
"name",
")",
"except",
"Exception",
":",
"LOGGER",
".",
"error",
"(",
"'Could not get service with nam... | 33.090909 | 0.005348 |
def neg(self):
"""
Unary operation: neg
:return: 0 - self
"""
si = StridedInterval(bits=self.bits, stride=0, lower_bound=0, upper_bound=0).sub(self)
si.uninitialized = self.uninitialized
return si | [
"def",
"neg",
"(",
"self",
")",
":",
"si",
"=",
"StridedInterval",
"(",
"bits",
"=",
"self",
".",
"bits",
",",
"stride",
"=",
"0",
",",
"lower_bound",
"=",
"0",
",",
"upper_bound",
"=",
"0",
")",
".",
"sub",
"(",
"self",
")",
"si",
".",
"uninitia... | 24.5 | 0.011811 |
def loadMsbwt(self, dirName, logger):
'''
This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory
@param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail
'''
#open the file ... | [
"def",
"loadMsbwt",
"(",
"self",
",",
"dirName",
",",
"logger",
")",
":",
"#open the file with our BWT in it",
"self",
".",
"dirName",
"=",
"dirName",
"self",
".",
"bwt",
"=",
"np",
".",
"load",
"(",
"self",
".",
"dirName",
"+",
"'/comp_msbwt.npy'",
",",
"... | 44.538462 | 0.011844 |
def blobs(shape: List[int], porosity: float = 0.5, blobiness: int = 1):
"""
Generates an image containing amorphous blobs
Parameters
----------
shape : list
The size of the image to generate in [Nx, Ny, Nz] where N is the
number of voxels
porosity : float
If specified, ... | [
"def",
"blobs",
"(",
"shape",
":",
"List",
"[",
"int",
"]",
",",
"porosity",
":",
"float",
"=",
"0.5",
",",
"blobiness",
":",
"int",
"=",
"1",
")",
":",
"blobiness",
"=",
"sp",
".",
"array",
"(",
"blobiness",
")",
"shape",
"=",
"sp",
".",
"array"... | 30 | 0.000769 |
def auto_slug_after_insert(mapper, connection, target):
"""Generate a slug from entity_type and id, unless slug is already set."""
if target.slug is None:
target.slug = "{name}{sep}{id}".format(
name=target.entity_class.lower(), sep=target.SLUG_SEPARATOR, id=target.id
) | [
"def",
"auto_slug_after_insert",
"(",
"mapper",
",",
"connection",
",",
"target",
")",
":",
"if",
"target",
".",
"slug",
"is",
"None",
":",
"target",
".",
"slug",
"=",
"\"{name}{sep}{id}\"",
".",
"format",
"(",
"name",
"=",
"target",
".",
"entity_class",
"... | 50.166667 | 0.006536 |
def append(self, obj):
"""Append an object to end. If the object is a string, appends a
:class:`Word <Word>` object.
"""
if isinstance(obj, basestring):
return self._collection.append(Word(obj))
else:
return self._collection.append(obj) | [
"def",
"append",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
":",
"return",
"self",
".",
"_collection",
".",
"append",
"(",
"Word",
"(",
"obj",
")",
")",
"else",
":",
"return",
"self",
".",
"_collection"... | 33.125 | 0.003676 |
def _prt_line_detail(self, prt, values, lnum=""):
"""Print header and field values in a readable format."""
#### data = zip(self.req_str, self.ntgafobj._fields, values)
data = zip(self.req_str, self.flds, values)
txt = ["{:2}) {:3} {:20} {}".format(i, req, hdr, val) for i, (req, hdr, val... | [
"def",
"_prt_line_detail",
"(",
"self",
",",
"prt",
",",
"values",
",",
"lnum",
"=",
"\"\"",
")",
":",
"#### data = zip(self.req_str, self.ntgafobj._fields, values)",
"data",
"=",
"zip",
"(",
"self",
".",
"req_str",
",",
"self",
".",
"flds",
",",
"values",
")"... | 68.5 | 0.009615 |
def first(self) -> Signature:
""" Retrieve the first Signature ordered by mangling descendant """
k = sorted(self._hsig.keys())
return self._hsig[k[0]] | [
"def",
"first",
"(",
"self",
")",
"->",
"Signature",
":",
"k",
"=",
"sorted",
"(",
"self",
".",
"_hsig",
".",
"keys",
"(",
")",
")",
"return",
"self",
".",
"_hsig",
"[",
"k",
"[",
"0",
"]",
"]"
] | 43 | 0.011429 |
def main():
"""Program entry point"""
parser = argparse.ArgumentParser()
parser.add_argument("path", help="Path to the CAPTCHA image file")
parser.add_argument("--prefix", help="Checkpoint prefix [Default 'ocr']", default='ocr')
parser.add_argument("--epoch", help="Checkpoint epoch [Default 100]", t... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"path\"",
",",
"help",
"=",
"\"Path to the CAPTCHA image file\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--prefix\"",
",",
"hel... | 40.791667 | 0.00499 |
async def read(self):
"""
Read from the box in a blocking manner.
:returns: An item from the box.
"""
result = await self._queue.get()
self._can_write.set()
if self._queue.empty():
self._can_read.clear()
return result | [
"async",
"def",
"read",
"(",
"self",
")",
":",
"result",
"=",
"await",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"self",
".",
"_can_write",
".",
"set",
"(",
")",
"if",
"self",
".",
"_queue",
".",
"empty",
"(",
")",
":",
"self",
".",
"_can_read... | 20.285714 | 0.006734 |
def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
... | [
"def",
"run_wfunc",
"(",
"self",
")",
":",
"# Ensure that opts/grains are up to date",
"# Execute routine",
"data_cache",
"=",
"False",
"data",
"=",
"None",
"cdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"opts",
"[",
"'cachedir'",
"]",
",",
"... | 41.282723 | 0.001486 |
def process_kwargs(self, kwargs, prefix='default_', delete=True):
"""
set self attributes based on kwargs, optionally deleting kwargs that are processed
"""
processed = []
for k in kwargs:
if hasattr(self, prefix + k):
processed += [k]
... | [
"def",
"process_kwargs",
"(",
"self",
",",
"kwargs",
",",
"prefix",
"=",
"'default_'",
",",
"delete",
"=",
"True",
")",
":",
"processed",
"=",
"[",
"]",
"for",
"k",
"in",
"kwargs",
":",
"if",
"hasattr",
"(",
"self",
",",
"prefix",
"+",
"k",
")",
":... | 35.166667 | 0.006928 |
def _make_names_unique(animations):
"""
Given a list of animations, some of which might have duplicate names, rename
the first one to be <duplicate>_0, the second <duplicate>_1,
<duplicate>_2, etc."""
counts = {}
for a in animations:
c = counts.get(a['name'], 0) + 1
counts[a['nam... | [
"def",
"_make_names_unique",
"(",
"animations",
")",
":",
"counts",
"=",
"{",
"}",
"for",
"a",
"in",
"animations",
":",
"c",
"=",
"counts",
".",
"get",
"(",
"a",
"[",
"'name'",
"]",
",",
"0",
")",
"+",
"1",
"counts",
"[",
"a",
"[",
"'name'",
"]",... | 32.1875 | 0.003774 |
def _create_intermediate_target(self, address, suffix):
"""
:param string address: A target address.
:param string suffix: A string used as a suffix of the intermediate target name.
:returns: The address of a synthetic intermediary target.
"""
if not isinstance(address, string_types):
rais... | [
"def",
"_create_intermediate_target",
"(",
"self",
",",
"address",
",",
"suffix",
")",
":",
"if",
"not",
"isinstance",
"(",
"address",
",",
"string_types",
")",
":",
"raise",
"self",
".",
"ExpectedAddressError",
"(",
"\"Expected string address argument, got type {type... | 40.166667 | 0.005673 |
def mdprint(*values, plain=None, **options):
""" Convert HTML to VTML and then print it.
Follows same semantics as vtmlprint. """
print(*[mdrender(x, plain=plain) for x in values], **options) | [
"def",
"mdprint",
"(",
"*",
"values",
",",
"plain",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"print",
"(",
"*",
"[",
"mdrender",
"(",
"x",
",",
"plain",
"=",
"plain",
")",
"for",
"x",
"in",
"values",
"]",
",",
"*",
"*",
"options",
")"
] | 50 | 0.004926 |
def update_assembly(data):
"""
Create a new Assembly() and convert as many of our old params to the new
version as we can. Also report out any parameters that are removed
and what their values are.
"""
print("##############################################################")
print("Updating... | [
"def",
"update_assembly",
"(",
"data",
")",
":",
"print",
"(",
"\"##############################################################\"",
")",
"print",
"(",
"\"Updating assembly to current version\"",
")",
"## New assembly object to update pdate from.",
"new_assembly",
"=",
"ip",
".",... | 42.395833 | 0.009606 |
def _set_params(self, p):
"""
change parameters in OrderedDict to list with or without uncertainties
:param p: parameters in OrderedDict
:return: parameters in list
:note: internal function
"""
if self.force_norm:
params = [value.n for key, value in p... | [
"def",
"_set_params",
"(",
"self",
",",
"p",
")",
":",
"if",
"self",
".",
"force_norm",
":",
"params",
"=",
"[",
"value",
".",
"n",
"for",
"key",
",",
"value",
"in",
"p",
".",
"items",
"(",
")",
"]",
"else",
":",
"params",
"=",
"[",
"value",
"f... | 31.538462 | 0.004739 |
def tas53(msg):
"""Aircraft true airspeed, BDS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: true airspeed in knots
"""
d = hex2bin(data(msg))
if d[33] == '0':
return None
tas = bin2int(d[34:46]) * 0.5 # kts
return round(tas, 1... | [
"def",
"tas53",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"33",
"]",
"==",
"'0'",
":",
"return",
"None",
"tas",
"=",
"bin2int",
"(",
"d",
"[",
"34",
":",
"46",
"]",
")",
"*",
"0.5",
"# kts... | 19.125 | 0.003115 |
def codec_desc(self):
"""string or None"""
info = self.decSpecificInfo
desc = None
if info is not None:
desc = info.description
return desc | [
"def",
"codec_desc",
"(",
"self",
")",
":",
"info",
"=",
"self",
".",
"decSpecificInfo",
"desc",
"=",
"None",
"if",
"info",
"is",
"not",
"None",
":",
"desc",
"=",
"info",
".",
"description",
"return",
"desc"
] | 23.125 | 0.010417 |
def cal_frame_according_boundaries(left, right, top, bottom, parent_size, gaphas_editor=True, group=True):
""" Generate margin and relative position and size handed boundary parameter and parent size """
# print("parent_size ->", parent_size)
margin = cal_margin(parent_size)
# Add margin and ensure that... | [
"def",
"cal_frame_according_boundaries",
"(",
"left",
",",
"right",
",",
"top",
",",
"bottom",
",",
"parent_size",
",",
"gaphas_editor",
"=",
"True",
",",
"group",
"=",
"True",
")",
":",
"# print(\"parent_size ->\", parent_size)",
"margin",
"=",
"cal_margin",
"(",... | 49.166667 | 0.003326 |
def _chi_squared(self, proportions, margin, observed):
"""return ndarray of chi-squared measures for proportions' columns.
*proportions* (ndarray): The basis of chi-squared calcualations
*margin* (ndarray): Column margin for proportions (See `def _margin`)
*observed* (ndarray): Row marg... | [
"def",
"_chi_squared",
"(",
"self",
",",
"proportions",
",",
"margin",
",",
"observed",
")",
":",
"n",
"=",
"self",
".",
"_element_count",
"chi_squared",
"=",
"np",
".",
"zeros",
"(",
"[",
"n",
",",
"n",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"... | 45.764706 | 0.003778 |
def root_and_children_to_graph(self,root):
"""Take a root node and its children and make them into graphs"""
g = Graph()
g.add_node(root)
edges = []
edges += self.get_node_edges(root,"outgoing")
for c in self.get_children(root):
g.add_node(c)
edges += self.get_node_ed... | [
"def",
"root_and_children_to_graph",
"(",
"self",
",",
"root",
")",
":",
"g",
"=",
"Graph",
"(",
")",
"g",
".",
"add_node",
"(",
"root",
")",
"edges",
"=",
"[",
"]",
"edges",
"+=",
"self",
".",
"get_node_edges",
"(",
"root",
",",
"\"outgoing\"",
")",
... | 34.181818 | 0.044041 |
def sys_writev(self, fd, iov, count):
"""
Works just like C{sys_write} except that multiple buffers are written out.
:rtype: int
:param fd: the file descriptor of the file to write.
:param iov: the buffer where the the bytes to write are taken.
:param count: amount of C{... | [
"def",
"sys_writev",
"(",
"self",
",",
"fd",
",",
"iov",
",",
"count",
")",
":",
"cpu",
"=",
"self",
".",
"current",
"ptrsize",
"=",
"cpu",
".",
"address_bit_size",
"sizeof_iovec",
"=",
"2",
"*",
"(",
"ptrsize",
"//",
"8",
")",
"total",
"=",
"0",
"... | 38.7 | 0.004202 |
def _set_service(self, v, load=False):
"""
Setter method for service, mapped from YANG variable /service (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_service is considered as a private
method. Backends looking to populate this variable should
do so... | [
"def",
"_set_service",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | 70.863636 | 0.005696 |
def cli(sequencepath, report, refseq_database):
"""
Pass command line arguments to, and run the feature extraction functions
"""
main(sequencepath, report, refseq_database, num_threads=multiprocessing.cpu_count()) | [
"def",
"cli",
"(",
"sequencepath",
",",
"report",
",",
"refseq_database",
")",
":",
"main",
"(",
"sequencepath",
",",
"report",
",",
"refseq_database",
",",
"num_threads",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
")"
] | 45 | 0.008734 |
def changes_since(self, domain, date_or_datetime):
"""
Gets the changes for a domain since the specified date/datetime.
The date can be one of:
- a Python datetime object
- a Python date object
- a string in the format 'YYYY-MM-YY HH:MM:SS'
- a str... | [
"def",
"changes_since",
"(",
"self",
",",
"domain",
",",
"date_or_datetime",
")",
":",
"domain_id",
"=",
"utils",
".",
"get_id",
"(",
"domain",
")",
"dt",
"=",
"utils",
".",
"iso_time_string",
"(",
"date_or_datetime",
",",
"show_tzinfo",
"=",
"True",
")",
... | 42.724138 | 0.001579 |
def pretty_dump(fn):
"""
Decorator used to output prettified JSON.
``response.content_type`` is set to ``application/json; charset=utf-8``.
Args:
fn (fn pointer): Function returning any basic python data structure.
Returns:
str: Data converted to prettified JSON.
"""
@wrap... | [
"def",
"pretty_dump",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"pretty_dump_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
".",
"content_type",
"=",
"\"application/json; charset=utf-8\"",
"return",
"json",
".",
... | 24.16 | 0.001592 |
def parse_conf(self, keys=[]):
"""Parse configuration values from the database.
The extension must have been previously initialized.
If a key is not found in the database, it will be created with the
default value specified.
Arguments:
keys (list[str]): list of key... | [
"def",
"parse_conf",
"(",
"self",
",",
"keys",
"=",
"[",
"]",
")",
":",
"confs",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'WAFFLE_CONFS'",
",",
"{",
"}",
")",
"if",
"not",
"keys",
":",
"keys",
"=",
"confs",
".",
"keys",
"(",
")... | 29.511111 | 0.001458 |
def to_file(file_):
"""Serializes file to id string
:param file_: object to serialize
:return: string id
"""
from sevenbridges.models.file import File
if not file_:
raise SbgError('File is required!')
elif isinstance(file_, File):
return fi... | [
"def",
"to_file",
"(",
"file_",
")",
":",
"from",
"sevenbridges",
".",
"models",
".",
"file",
"import",
"File",
"if",
"not",
"file_",
":",
"raise",
"SbgError",
"(",
"'File is required!'",
")",
"elif",
"isinstance",
"(",
"file_",
",",
"File",
")",
":",
"r... | 32.571429 | 0.004264 |
def inasafe_field_header(field, feature, parent):
"""Retrieve a header name of the field name from definitions.
For instance:
inasafe_field_header('minimum_needs__clean_water') -> 'Clean water'
"""
_ = feature, parent # NOQA
age_fields = [under_5_displaced_count_field, over_60_displaced_count_... | [
"def",
"inasafe_field_header",
"(",
"field",
",",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"age_fields",
"=",
"[",
"under_5_displaced_count_field",
",",
"over_60_displaced_count_field",
"]",
"symbol_mapping",
"=",
"{",
"'ov... | 35.294118 | 0.000811 |
def create_customer_request(self, fields=None, prefetch=True, **fieldargs):
"""Create a new customer request and return an issue Resource for it.
Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value
is treated as the intended value for that ... | [
"def",
"create_customer_request",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"prefetch",
"=",
"True",
",",
"*",
"*",
"fieldargs",
")",
":",
"data",
"=",
"fields",
"p",
"=",
"data",
"[",
"'serviceDeskId'",
"]",
"service_desk",
"=",
"None",
"if",
"isins... | 46.442308 | 0.004461 |
def info(self, **kwargs):
"""
Get the primary information about a TV season by its season number.
Args:
language: (optional) ISO 639 code.
append_to_response: (optional) Comma separated, any TV series
method.
Returns:
... | [
"def",
"info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_series_id_season_number_path",
"(",
"'info'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
... | 32.176471 | 0.003552 |
def section_end_info(template, tag_key, state, index):
"""
Given the tag key of an opening section tag, find the corresponding closing
tag (if it exists) and return information about that match.
"""
state.section.push(tag_key)
match = None
matchinfo = None
search_index = index
whil... | [
"def",
"section_end_info",
"(",
"template",
",",
"tag_key",
",",
"state",
",",
"index",
")",
":",
"state",
".",
"section",
".",
"push",
"(",
"tag_key",
")",
"match",
"=",
"None",
"matchinfo",
"=",
"None",
"search_index",
"=",
"index",
"while",
"state",
"... | 35.848485 | 0.000823 |
def _on_stream_disconnect(self, stream):
"""
Respond to disconnection of a local stream by propagating DEL_ROUTE for
any contexts we know were attached to it.
"""
# During a stream crash it is possible for disconnect signal to fire
# twice, in which case ignore the second... | [
"def",
"_on_stream_disconnect",
"(",
"self",
",",
"stream",
")",
":",
"# During a stream crash it is possible for disconnect signal to fire",
"# twice, in which case ignore the second instance.",
"routes",
"=",
"self",
".",
"_routes_by_stream",
".",
"pop",
"(",
"stream",
",",
... | 42.285714 | 0.002203 |
def axes(self, axes):
'''Set the angular axis of rotation for this joint.
Parameters
----------
axes : list containing one 3-tuple of floats
A list of the axes for this joint. For a hinge joint, which has one
degree of freedom, this must contain one 3-tuple speci... | [
"def",
"axes",
"(",
"self",
",",
"axes",
")",
":",
"self",
".",
"amotor",
".",
"axes",
"=",
"[",
"axes",
"[",
"0",
"]",
"]",
"self",
".",
"ode_obj",
".",
"setAxis",
"(",
"tuple",
"(",
"axes",
"[",
"0",
"]",
")",
")"
] | 38 | 0.004283 |
def cancel(self, mark_completed_as_cancelled=False):
"""
Cancel the future. If the future has not been started yet, it will never
start running. If the future is already running, it will run until the
worker function exists. The worker function can check if the future has
been cancelled using the :m... | [
"def",
"cancel",
"(",
"self",
",",
"mark_completed_as_cancelled",
"=",
"False",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"not",
"self",
".",
"_completed",
"or",
"mark_completed_as_cancelled",
":",
"self",
".",
"_cancelled",
"=",
"True",
"callbacks",
... | 42.631579 | 0.003623 |
def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by... | [
"def",
"folderitem",
"(",
"self",
",",
"obj",
",",
"item",
",",
"index",
")",
":",
"item",
"=",
"super",
"(",
"ReferenceSamplesView",
",",
"self",
")",
".",
"folderitem",
"(",
"obj",
",",
"item",
",",
"index",
")",
"# ensure we have an object and not a brain... | 35.8 | 0.001813 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.