text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def main(args=sys.argv):
"""
main entry point for the manifest CLI
"""
if len(args) < 2:
return usage("Command expected")
command = args[1]
rest = args[2:]
if "create".startswith(command):
return cli_create(rest)
elif "query".startswith(command):
return cli_que... | [
"def",
"main",
"(",
"args",
"=",
"sys",
".",
"argv",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"return",
"usage",
"(",
"\"Command expected\"",
")",
"command",
"=",
"args",
"[",
"1",
"]",
"rest",
"=",
"args",
"[",
"2",
":",
"]",
"i... | 23.421053 | 14.578947 |
def _unmarshal_parts(pkg_reader, package, part_factory):
"""
Return a dictionary of |Part| instances unmarshalled from
*pkg_reader*, keyed by partname. Side-effect is that each part in
*pkg_reader* is constructed using *part_factory*.
"""
parts = {}
for partname, ... | [
"def",
"_unmarshal_parts",
"(",
"pkg_reader",
",",
"package",
",",
"part_factory",
")",
":",
"parts",
"=",
"{",
"}",
"for",
"partname",
",",
"content_type",
",",
"reltype",
",",
"blob",
"in",
"pkg_reader",
".",
"iter_sparts",
"(",
")",
":",
"parts",
"[",
... | 42.25 | 18.583333 |
def _scan(
self,
fs, # type: FS
dir_path, # type: Text
namespaces=None, # type: Optional[Collection[Text]]
):
# type: (...) -> Iterator[Info]
"""Get an iterator of `Info` objects for a directory path.
Arguments:
fs (FS): A filesystem instance.
... | [
"def",
"_scan",
"(",
"self",
",",
"fs",
",",
"# type: FS",
"dir_path",
",",
"# type: Text",
"namespaces",
"=",
"None",
",",
"# type: Optional[Collection[Text]]",
")",
":",
"# type: (...) -> Iterator[Info]",
"try",
":",
"for",
"info",
"in",
"fs",
".",
"scandir",
... | 33.038462 | 18.846154 |
def update_subnetpool(self, subnetpool, body=None):
"""Updates a subnetpool."""
return self.put(self.subnetpool_path % (subnetpool), body=body) | [
"def",
"update_subnetpool",
"(",
"self",
",",
"subnetpool",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"subnetpool_path",
"%",
"(",
"subnetpool",
")",
",",
"body",
"=",
"body",
")"
] | 52.333333 | 14 |
def dataframe(self):
"""
Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string URI that is used to
instantiate the class, such as '201806070VEG'.
"""
if self._away_goals is None and self._home_goals is None:... | [
"def",
"dataframe",
"(",
"self",
")",
":",
"if",
"self",
".",
"_away_goals",
"is",
"None",
"and",
"self",
".",
"_home_goals",
"is",
"None",
":",
"return",
"None",
"fields_to_include",
"=",
"{",
"'arena'",
":",
"self",
".",
"arena",
",",
"'attendance'",
"... | 52.056604 | 17.490566 |
def common_values_dict():
"""Build a basic values object used in every create method.
All our resources contain a same subset of value. Instead of
redoing this code everytime, this method ensures it is done only at
one place.
"""
now = datetime.datetime.utcnow().isoformat()
etag = ... | [
"def",
"common_values_dict",
"(",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"etag",
"=",
"utils",
".",
"gen_etag",
"(",
")",
"values",
"=",
"{",
"'id'",
":",
"utils",
".",
"gen_uuid",
"(",... | 27.470588 | 20.058824 |
def printed_out(self, name):
"""
Create a string describing the APIObject and its children
"""
out = ''
out += '|\n'
if self._id_variable:
subs = '[{}]'.format(self._id_variable)
else:
subs = ''
out += '|---{}{}\n'.format(name, subs... | [
"def",
"printed_out",
"(",
"self",
",",
"name",
")",
":",
"out",
"=",
"''",
"out",
"+=",
"'|\\n'",
"if",
"self",
".",
"_id_variable",
":",
"subs",
"=",
"'[{}]'",
".",
"format",
"(",
"self",
".",
"_id_variable",
")",
"else",
":",
"subs",
"=",
"''",
... | 31.875 | 13.75 |
def uniq_to_level_ipix(uniq):
"""
Convert a HEALPix cell uniq number to its (level, ipix) equivalent.
A uniq number is a 64 bits integer equaling to : ipix + 4*(4**level). Please read
this `paper <http://ivoa.net/documents/MOC/20140602/REC-MOC-1.0-20140602.pdf>`_
for more details about uniq numbers... | [
"def",
"uniq_to_level_ipix",
"(",
"uniq",
")",
":",
"uniq",
"=",
"np",
".",
"asarray",
"(",
"uniq",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"level",
"=",
"(",
"np",
".",
"log2",
"(",
"uniq",
"//",
"4",
")",
")",
"//",
"2",
"level",
"=",
"le... | 26.892857 | 21.821429 |
def describe_volumes(self, xml_bytes):
"""Parse the XML returned by the C{DescribeVolumes} function.
@param xml_bytes: XML bytes with a C{DescribeVolumesResponse} root
element.
@return: A list of L{Volume} instances.
TODO: attachementSetItemResponseType#deleteOnTermination
... | [
"def",
"describe_volumes",
"(",
"self",
",",
"xml_bytes",
")",
":",
"root",
"=",
"XML",
"(",
"xml_bytes",
")",
"result",
"=",
"[",
"]",
"for",
"volume_data",
"in",
"root",
".",
"find",
"(",
"\"volumeSet\"",
")",
":",
"volume_id",
"=",
"volume_data",
".",... | 47.057143 | 17.228571 |
def buildconfig_update(orig, new, remove_nonexistent_keys=False):
"""Performs update of given `orig` BuildConfig with values from `new` BuildConfig.
Both BuildConfigs have to be represented as `dict`s.
This function:
- adds all key/value pairs to `orig` from `new` that are missing
- replaces values... | [
"def",
"buildconfig_update",
"(",
"orig",
",",
"new",
",",
"remove_nonexistent_keys",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"orig",
",",
"dict",
")",
"and",
"isinstance",
"(",
"new",
",",
"dict",
")",
":",
"clean_triggers",
"(",
"orig",
",",
"... | 45.791667 | 17.833333 |
def OnTextColorDialog(self, event):
"""Event handler for launching text color dialog"""
dlg = wx.ColourDialog(self.main_window)
# Ensure the full colour dialog is displayed,
# not the abbreviated version.
dlg.GetColourData().SetChooseFull(True)
if dlg.ShowModal() == wx... | [
"def",
"OnTextColorDialog",
"(",
"self",
",",
"event",
")",
":",
"dlg",
"=",
"wx",
".",
"ColourDialog",
"(",
"self",
".",
"main_window",
")",
"# Ensure the full colour dialog is displayed,",
"# not the abbreviated version.",
"dlg",
".",
"GetColourData",
"(",
")",
".... | 30.210526 | 18.578947 |
def isBridgeFiltered (self):
"""
Checks if address is an IEEE 802.1D MAC Bridge Filtered MAC Group Address
This range is 01-80-C2-00-00-00 to 01-80-C2-00-00-0F. MAC frames that
have a destination MAC address within this range are not relayed by
bridges conforming to IEEE 802.1D
... | [
"def",
"isBridgeFiltered",
"(",
"self",
")",
":",
"return",
"(",
"(",
"self",
".",
"__value",
"[",
"0",
"]",
"==",
"0x01",
")",
"and",
"(",
"self",
".",
"__value",
"[",
"1",
"]",
"==",
"0x80",
")",
"and",
"(",
"self",
".",
"__value",
"[",
"2",
... | 39.785714 | 12.642857 |
def watts2pascal(watts, cfm, fan_tot_eff):
"""convert and return inputs for E+ in pascal and m3/s"""
bhp = watts2bhp(watts)
return bhp2pascal(bhp, cfm, fan_tot_eff) | [
"def",
"watts2pascal",
"(",
"watts",
",",
"cfm",
",",
"fan_tot_eff",
")",
":",
"bhp",
"=",
"watts2bhp",
"(",
"watts",
")",
"return",
"bhp2pascal",
"(",
"bhp",
",",
"cfm",
",",
"fan_tot_eff",
")"
] | 43.25 | 5 |
def process_document(self, doc):
"""
Add your code for processing the document
"""
segment = doc.select_segments("target_text")[0]
for e in self.e_list:
res = doc.extract(e, segment)
doc.store(res, e.name)
return list() | [
"def",
"process_document",
"(",
"self",
",",
"doc",
")",
":",
"segment",
"=",
"doc",
".",
"select_segments",
"(",
"\"target_text\"",
")",
"[",
"0",
"]",
"for",
"e",
"in",
"self",
".",
"e_list",
":",
"res",
"=",
"doc",
".",
"extract",
"(",
"e",
",",
... | 25.727273 | 13.545455 |
def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
if not self.upstream:
raise Exception("CompressionCache must have an upstream")
# Must always propagate, since this is really just a filter.
self.upstream.remove(self._r... | [
"def",
"remove",
"(",
"self",
",",
"rel_path",
",",
"propagate",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"upstream",
":",
"raise",
"Exception",
"(",
"\"CompressionCache must have an upstream\"",
")",
"# Must always propagate, since this is really just a filter... | 36.846154 | 23.461538 |
def disk(x, y, height, gaussian_width):
"""
Circular disk with Gaussian fall-off after the solid central region.
"""
disk_radius = height/2.0
distance_from_origin = np.sqrt(x**2+y**2)
distance_outside_disk = distance_from_origin - disk_radius
sigmasq = gaussian_width*gaussian_width
if ... | [
"def",
"disk",
"(",
"x",
",",
"y",
",",
"height",
",",
"gaussian_width",
")",
":",
"disk_radius",
"=",
"height",
"/",
"2.0",
"distance_from_origin",
"=",
"np",
".",
"sqrt",
"(",
"x",
"**",
"2",
"+",
"y",
"**",
"2",
")",
"distance_outside_disk",
"=",
... | 31.944444 | 18.611111 |
def dict_merge(dct, merge_dct):
""" Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
updating only top-level keys, dict_merge recurses down into dicts nested
to an arbitrary depth, updating keys. The ``merge_dct`` is merged into
``dct``.
:param dct: dict onto which the merge is ... | [
"def",
"dict_merge",
"(",
"dct",
",",
"merge_dct",
")",
":",
"for",
"k",
",",
"v",
"in",
"merge_dct",
".",
"items",
"(",
")",
":",
"if",
"(",
"k",
"in",
"dct",
"and",
"isinstance",
"(",
"dct",
"[",
"k",
"]",
",",
"dict",
")",
"and",
"isinstance",... | 40.357143 | 16.928571 |
def pre_save(self, instance, add):
"""
Auto-generate the slug if needed.
"""
# get currently entered slug
value = self.value_from_object(instance)
slug = None
# auto populate (if the form didn't do that already).
# If you want unique_with logic, use djang... | [
"def",
"pre_save",
"(",
"self",
",",
"instance",
",",
"add",
")",
":",
"# get currently entered slug",
"value",
"=",
"self",
".",
"value_from_object",
"(",
"instance",
")",
"slug",
"=",
"None",
"# auto populate (if the form didn't do that already).",
"# If you want uniq... | 37.68 | 16 |
def sliding_tensor(mv_time_series, width, step, order='F'):
'''
segments multivariate time series with sliding window
Parameters
----------
mv_time_series : array like shape [n_samples, n_variables]
multivariate time series or sequence
width : int > 0
segment width in samples
... | [
"def",
"sliding_tensor",
"(",
"mv_time_series",
",",
"width",
",",
"step",
",",
"order",
"=",
"'F'",
")",
":",
"D",
"=",
"mv_time_series",
".",
"shape",
"[",
"1",
"]",
"data",
"=",
"[",
"sliding_window",
"(",
"mv_time_series",
"[",
":",
",",
"j",
"]",
... | 31.047619 | 21.904762 |
def add_link(app, pagename, templatename, context, doctree):
"""Add the slides link to the HTML context."""
# we can only show the slidelink if we can resolve the filename
context['show_slidelink'] = (
app.config.slide_link_html_to_slides and
hasattr(app.builder, 'get_outfilename')
)
... | [
"def",
"add_link",
"(",
"app",
",",
"pagename",
",",
"templatename",
",",
"context",
",",
"doctree",
")",
":",
"# we can only show the slidelink if we can resolve the filename",
"context",
"[",
"'show_slidelink'",
"]",
"=",
"(",
"app",
".",
"config",
".",
"slide_lin... | 37.090909 | 19.636364 |
def show(close=None):
"""Show all figures as SVG/PNG payloads sent to the IPython clients.
Parameters
----------
close : bool, optional
If true, a ``plt.close('all')`` call is automatically issued after
sending all the figures. If this is set, the figures will entirely
removed from th... | [
"def",
"show",
"(",
"close",
"=",
"None",
")",
":",
"if",
"close",
"is",
"None",
":",
"close",
"=",
"InlineBackend",
".",
"instance",
"(",
")",
".",
"close_figures",
"try",
":",
"for",
"figure_manager",
"in",
"Gcf",
".",
"get_all_fig_managers",
"(",
")",... | 33.473684 | 18.894737 |
def _multihop_xml(self, **kwargs):
"""Build BGP multihop XML.
Do not use this method directly. You probably want ``multihop``.
Args:
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
neighbor (ipaddress.ip_i... | [
"def",
"_multihop_xml",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"ip_addr",
"=",
"kwargs",
".",
"pop",
"(",
"'neighbor'",
")",
"ip",
"=",
"str",
"(",
"ip_addr",
".",
"ip",
")",
"rbr_ns",
"=",
"'urn:brocade.com:mgmt:brocade-rbridge'",
"bgp_ns",
"=",
... | 43.566038 | 19.283019 |
def srcmaps(self, **kwargs):
""" return the name of a source map file
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))
kwargs_copy['component'] = kwargs.get(
'component'... | [
"def",
"srcmaps",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs_copy",
"=",
"self",
".",
"base_dict",
".",
"copy",
"(",
")",
"kwargs_copy",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"kwargs_copy",
"[",
"'dataset'",
"]",
"=",
"kwargs",
".... | 44.076923 | 10.615385 |
def on_for_degrees(self, speed, degrees, brake=True, block=True):
"""
Rotate the motor at ``speed`` for ``degrees``
``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue`
object, enabling use of other units.
"""
speed_sp = self._speed_native_units(speed)
... | [
"def",
"on_for_degrees",
"(",
"self",
",",
"speed",
",",
"degrees",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"speed_sp",
"=",
"self",
".",
"_speed_native_units",
"(",
"speed",
")",
"self",
".",
"_set_rel_position_degrees_and_speed_sp",
... | 37.6 | 18 |
def applyColorMap(gray, cmap='flame'):
'''
like cv2.applyColorMap(im_gray, cv2.COLORMAP_*) but with different color maps
'''
# TODO:implement more cmaps
if cmap != 'flame':
raise NotImplemented
# TODO: make better
mx = 256 # if gray.dtype==np.uint8 else 65535
lut = np.e... | [
"def",
"applyColorMap",
"(",
"gray",
",",
"cmap",
"=",
"'flame'",
")",
":",
"# TODO:implement more cmaps\r",
"if",
"cmap",
"!=",
"'flame'",
":",
"raise",
"NotImplemented",
"# TODO: make better\r",
"mx",
"=",
"256",
"# if gray.dtype==np.uint8 else 65535\r",
"lut",
"=",... | 28.428571 | 17.4 |
def ParseOptions(cls, options, configuration_object):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is o... | [
"def",
"ParseOptions",
"(",
"cls",
",",
"options",
",",
"configuration_object",
")",
":",
"if",
"not",
"isinstance",
"(",
"configuration_object",
",",
"tools",
".",
"CLITool",
")",
":",
"raise",
"errors",
".",
"BadConfigObject",
"(",
"'Configuration object is not ... | 39.579545 | 25.204545 |
def _set_cell_attr(self, selection, table, attr):
"""Sets cell attr for key cell and mark grid content as changed
Parameters
----------
attr: dict
\tContains cell attribute keys
\tkeys in ["borderwidth_bottom", "borderwidth_right",
\t"bordercolor_bottom", "borde... | [
"def",
"_set_cell_attr",
"(",
"self",
",",
"selection",
",",
"table",
",",
"attr",
")",
":",
"# Mark content as changed",
"post_command_event",
"(",
"self",
".",
"main_window",
",",
"self",
".",
"ContentChangedMsg",
")",
"if",
"selection",
"is",
"not",
"None",
... | 35.727273 | 22 |
def pass_bucket(f):
"""Decorate to retrieve a bucket."""
@wraps(f)
def decorate(*args, **kwargs):
bucket_id = kwargs.pop('bucket_id')
bucket = Bucket.get(as_uuid(bucket_id))
if not bucket:
abort(404, 'Bucket does not exist.')
return f(bucket=bucket, *args, **kwarg... | [
"def",
"pass_bucket",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bucket_id",
"=",
"kwargs",
".",
"pop",
"(",
"'bucket_id'",
")",
"bucket",
"=",
"Bucket",
".",
"get",
"... | 33.3 | 11.9 |
def add(self, logical_id, property, value):
"""
Add the information that resource with given `logical_id` supports the given `property`, and that a reference
to `logical_id.property` resolves to given `value.
Example:
"MyApi.Deployment" -> "MyApiDeployment1234567890"
... | [
"def",
"add",
"(",
"self",
",",
"logical_id",
",",
"property",
",",
"value",
")",
":",
"if",
"not",
"logical_id",
"or",
"not",
"property",
":",
"raise",
"ValueError",
"(",
"\"LogicalId and property must be a non-empty string\"",
")",
"if",
"not",
"value",
"or",
... | 39.392857 | 27.25 |
def is_iterable(obj,
forbid_literals = (str, bytes),
minimum_length = None,
maximum_length = None,
**kwargs):
"""Indicate whether ``obj`` is iterable.
:param forbid_literals: A collection of literals that will be considered invalid
even if t... | [
"def",
"is_iterable",
"(",
"obj",
",",
"forbid_literals",
"=",
"(",
"str",
",",
"bytes",
")",
",",
"minimum_length",
"=",
"None",
",",
"maximum_length",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"False",
... | 35.021739 | 23.130435 |
def offsets(self):
"""A generator producing a (path, offset) tuple for all tailed files."""
for path, tailedfile in self._tailedfiles.iteritems():
yield path, tailedfile._offset | [
"def",
"offsets",
"(",
"self",
")",
":",
"for",
"path",
",",
"tailedfile",
"in",
"self",
".",
"_tailedfiles",
".",
"iteritems",
"(",
")",
":",
"yield",
"path",
",",
"tailedfile",
".",
"_offset"
] | 48.75 | 10.75 |
def derivatives_ctrlpts(**kwargs):
""" Computes the control points of all derivative surfaces up to and including the {degree}-th derivative.
Output is PKL[k][l][i][j], i,j-th control point of the surface differentiated k times w.r.t to u and
l times w.r.t v.
"""
r1 = kwargs.get... | [
"def",
"derivatives_ctrlpts",
"(",
"*",
"*",
"kwargs",
")",
":",
"r1",
"=",
"kwargs",
".",
"get",
"(",
"'r1'",
")",
"# minimum span on the u-direction",
"r2",
"=",
"kwargs",
".",
"get",
"(",
"'r2'",
")",
"# maximum span on the u-direction",
"s1",
"=",
"kwargs"... | 46.316667 | 24 |
def get_best_auth(self, family, address, dispno,
types = ( b"MIT-MAGIC-COOKIE-1", )):
"""Find an authentication entry matching FAMILY, ADDRESS and
DISPNO.
The name of the auth scheme must match one of the names in
TYPES. If several entries match, the first scheme... | [
"def",
"get_best_auth",
"(",
"self",
",",
"family",
",",
"address",
",",
"dispno",
",",
"types",
"=",
"(",
"b\"MIT-MAGIC-COOKIE-1\"",
",",
")",
")",
":",
"num",
"=",
"str",
"(",
"dispno",
")",
".",
"encode",
"(",
")",
"matches",
"=",
"{",
"}",
"for",... | 29.862069 | 21.896552 |
def dataReceived(self, data):
"""
Do not overwrite this method. Instead implement `on_...` methods for the
registered typenames to handle incomming packets.
"""
self._unprocessed_data.enqueue(data)
while True:
if len(self._unprocesse... | [
"def",
"dataReceived",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_unprocessed_data",
".",
"enqueue",
"(",
"data",
")",
"while",
"True",
":",
"if",
"len",
"(",
"self",
".",
"_unprocessed_data",
")",
"<",
"self",
".",
"_header",
".",
"size",
":",... | 37.433333 | 19.433333 |
def reboot(self, comment=None):
"""
Send reboot command to this node.
:param str comment: comment to audit
:raises NodeCommandFailed: reboot failed with reason
:return: None
"""
self.make_request(
NodeCommandFailed,
method='update',
... | [
"def",
"reboot",
"(",
"self",
",",
"comment",
"=",
"None",
")",
":",
"self",
".",
"make_request",
"(",
"NodeCommandFailed",
",",
"method",
"=",
"'update'",
",",
"resource",
"=",
"'reboot'",
",",
"params",
"=",
"{",
"'comment'",
":",
"comment",
"}",
")"
] | 28.692308 | 10.692308 |
def getWifiInfo(self, wifiInterfaceId=1, timeout=1):
"""Execute GetInfo action to get Wifi basic information's.
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
:return: the basic informations
:rtype... | [
"def",
"getWifiInfo",
"(",
"self",
",",
"wifiInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wifi",
".",
"getServiceType",
"(",
"\"getWifiInfo\"",
")",
"+",
"str",
"(",
"wifiInterfaceId",
")",
"uri",
"=",
"self",
".",
"getC... | 40.785714 | 20.285714 |
def to_protobuf(self) -> LinkItemProto:
"""
Create protobuf item.
:return: protobuf structure
:rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto
"""
result = LinkItemProto()
result.name = self._name
result.time.CopyFrom(datetime_to_timestamp(sel... | [
"def",
"to_protobuf",
"(",
"self",
")",
"->",
"LinkItemProto",
":",
"result",
"=",
"LinkItemProto",
"(",
")",
"result",
".",
"name",
"=",
"self",
".",
"_name",
"result",
".",
"time",
".",
"CopyFrom",
"(",
"datetime_to_timestamp",
"(",
"self",
".",
"_time",... | 31 | 13 |
def atype_view_asset(self, ):
"""View the project of the current assettype
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_atype:
return
i = self.atype_asset_treev.currentIndex()
item = i.internalPointer()
if item:
... | [
"def",
"atype_view_asset",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_atype",
":",
"return",
"i",
"=",
"self",
".",
"atype_asset_treev",
".",
"currentIndex",
"(",
")",
"item",
"=",
"i",
".",
"internalPointer",
"(",
")",
"if",
"item",
":... | 27.3125 | 14.875 |
def RetrievePluginAsset(self, plugin_name, asset_name):
"""Return the contents of a given plugin asset.
Args:
plugin_name: The string name of a plugin.
asset_name: The string name of an asset.
Returns:
The string contents of the plugin asset.
Raises:
KeyError: If the asset is ... | [
"def",
"RetrievePluginAsset",
"(",
"self",
",",
"plugin_name",
",",
"asset_name",
")",
":",
"return",
"plugin_asset_util",
".",
"RetrieveAsset",
"(",
"self",
".",
"path",
",",
"plugin_name",
",",
"asset_name",
")"
] | 29.142857 | 20.428571 |
def letter2num(letters, zbase=False):
"""A = 1, C = 3 and so on. Convert spreadsheet style column
enumeration to a number.
Answers:
A = 1, Z = 26, AA = 27, AZ = 52, ZZ = 702, AMJ = 1024
>>> from channelpack.pullxl import letter2num
>>> letter2num('A') == 1
True
>>> letter2num('Z') == ... | [
"def",
"letter2num",
"(",
"letters",
",",
"zbase",
"=",
"False",
")",
":",
"letters",
"=",
"letters",
".",
"upper",
"(",
")",
"res",
"=",
"0",
"weight",
"=",
"len",
"(",
"letters",
")",
"-",
"1",
"assert",
"weight",
">=",
"0",
",",
"letters",
"for"... | 22.861111 | 19.138889 |
def submit_reading(basename, pmid_list_filename, readers, start_ix=None,
end_ix=None, pmids_per_job=3000, num_tries=2,
force_read=False, force_fulltext=False, project_name=None):
"""Submit an old-style pmid-centered no-database s3 only reading job.
This function is provide... | [
"def",
"submit_reading",
"(",
"basename",
",",
"pmid_list_filename",
",",
"readers",
",",
"start_ix",
"=",
"None",
",",
"end_ix",
"=",
"None",
",",
"pmids_per_job",
"=",
"3000",
",",
"num_tries",
"=",
"2",
",",
"force_read",
"=",
"False",
",",
"force_fulltex... | 50.571429 | 20.142857 |
def find_executable(executable, path=None):
'''Try to find 'executable' in the directories listed in 'path' (a
string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']).'''
if path is None:
path = os.environ['PATH']
paths = path.split(os.pathsep)
extlist = [''... | [
"def",
"find_executable",
"(",
"executable",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
"paths",
"=",
"path",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"extlist",
... | 35.870968 | 14.967742 |
def index(self):
'''
Index funtion.
'''
self.render('ext_excel/index.html',
userinfo=self.userinfo,
cfg=CMS_CFG,
kwd={}, ) | [
"def",
"index",
"(",
"self",
")",
":",
"self",
".",
"render",
"(",
"'ext_excel/index.html'",
",",
"userinfo",
"=",
"self",
".",
"userinfo",
",",
"cfg",
"=",
"CMS_CFG",
",",
"kwd",
"=",
"{",
"}",
",",
")"
] | 20.7 | 20.5 |
def notebook_merge(local, base, remote, check_modified=False):
"""Unify three notebooks into a single notebook with merge metadata.
The result of this function is a valid notebook that can be loaded
by the IPython Notebook front-end. This function adds additional
cell metadata that the front-end Javasc... | [
"def",
"notebook_merge",
"(",
"local",
",",
"base",
",",
"remote",
",",
"check_modified",
"=",
"False",
")",
":",
"local_cells",
"=",
"get_cells",
"(",
"local",
")",
"base_cells",
"=",
"get_cells",
"(",
"base",
")",
"remote_cells",
"=",
"get_cells",
"(",
"... | 37.727273 | 18.719697 |
def getWaveletData(eda):
'''
This function computes the wavelet coefficients
INPUT:
data: DataFrame, index is a list of timestamps at 8Hz, columns include EDA, filtered_eda
OUTPUT:
wave1Second: DateFrame, index is a list of timestamps at 1Hz, columns include OneSecond_featur... | [
"def",
"getWaveletData",
"(",
"eda",
")",
":",
"# Create wavelet dataframes",
"oneSecond",
"=",
"halfSecond",
"=",
"# Compute wavelets",
"cA_n",
",",
"cD_3",
",",
"cD_2",
",",
"cD_1",
"=",
"pywt",
".",
"wavedec",
"(",
"eda",
",",
"'Haar'",
",",
"level",
"=",... | 42.454545 | 30.939394 |
def _is_valid_index(self, index):
"""
Return ``True`` if and only if the given ``index``
is valid.
"""
if isinstance(index, int):
return (index >= 0) and (index < len(self))
if isinstance(index, list):
valid = True
for i in index:
... | [
"def",
"_is_valid_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"return",
"(",
"index",
">=",
"0",
")",
"and",
"(",
"index",
"<",
"len",
"(",
"self",
")",
")",
"if",
"isinstance",
"(",
"index",... | 31.153846 | 11.923077 |
def _mainthread_accept_clients(self):
"""Accepts new clients and sends them to the to _handle_accepted within a subthread
"""
try:
if self._accept_selector.select(timeout=self.block_time):
client = self._server_socket.accept()
logging.info('Client conn... | [
"def",
"_mainthread_accept_clients",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_accept_selector",
".",
"select",
"(",
"timeout",
"=",
"self",
".",
"block_time",
")",
":",
"client",
"=",
"self",
".",
"_server_socket",
".",
"accept",
"(",
")",
... | 45.25 | 21.25 |
def authenticate(self, req_data, identifier: Optional[str]=None,
signature: Optional[str]=None, threshold: Optional[int] = None,
verifier: Verifier=DidVerifier):
"""
Prepares the data to be serialised for signing and then verifies the
signature
:... | [
"def",
"authenticate",
"(",
"self",
",",
"req_data",
",",
"identifier",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"signature",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"threshold",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
"... | 43.756757 | 20.513514 |
def _max_weight_state(states: Iterable[TensorProductState]) -> Union[None, TensorProductState]:
"""Construct a TensorProductState by taking the single-qubit state at each
qubit position.
This function will return ``None`` if the input states are not compatible
For example, the max_weight_state of ["(+... | [
"def",
"_max_weight_state",
"(",
"states",
":",
"Iterable",
"[",
"TensorProductState",
"]",
")",
"->",
"Union",
"[",
"None",
",",
"TensorProductState",
"]",
":",
"mapping",
"=",
"dict",
"(",
")",
"# type: Dict[int, _OneQState]",
"for",
"state",
"in",
"states",
... | 46.111111 | 22.5 |
def create_project(args):
"""
Create a new django project using the longclaw template
"""
# Make sure given name is not already in use by another python package/module.
try:
__import__(args.project_name)
except ImportError:
pass
else:
sys.exit("'{}' conflicts with th... | [
"def",
"create_project",
"(",
"args",
")",
":",
"# Make sure given name is not already in use by another python package/module.",
"try",
":",
"__import__",
"(",
"args",
".",
"project_name",
")",
"except",
"ImportError",
":",
"pass",
"else",
":",
"sys",
".",
"exit",
"(... | 32.259259 | 21.074074 |
def create_autoscale_rule(subscription_id, resource_group, vmss_name, metric_name, operator,
threshold, direction, change_count, time_grain='PT1M',
time_window='PT5M', cool_down='PT1M'):
'''Create a new autoscale rule - pass the output in a list to create_autoscal... | [
"def",
"create_autoscale_rule",
"(",
"subscription_id",
",",
"resource_group",
",",
"vmss_name",
",",
"metric_name",
",",
"operator",
",",
"threshold",
",",
"direction",
",",
"change_count",
",",
"time_grain",
"=",
"'PT1M'",
",",
"time_window",
"=",
"'PT5M'",
",",... | 51.435897 | 19.948718 |
def string(self) -> bytes:
"""The capabilities string without the enclosing square brackets."""
if self._raw is not None:
return self._raw
self._raw = raw = BytesFormat(b' ').join(
[b'CAPABILITY', b'IMAP4rev1'] + self.capabilities)
return raw | [
"def",
"string",
"(",
"self",
")",
"->",
"bytes",
":",
"if",
"self",
".",
"_raw",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_raw",
"self",
".",
"_raw",
"=",
"raw",
"=",
"BytesFormat",
"(",
"b' '",
")",
".",
"join",
"(",
"[",
"b'CAPABILITY'"... | 41.714286 | 12.285714 |
def parse_docs(docs, marks):
"""
Parse YAML syntax content from docs
If docs is None, return {}
If docs has no YAML content, return {"$desc": docs}
Else, parse YAML content, return {"$desc": docs, YAML}
Args:
docs (str): docs to be parsed
marks (list): list of which indicate YA... | [
"def",
"parse_docs",
"(",
"docs",
",",
"marks",
")",
":",
"if",
"docs",
"is",
"None",
":",
"return",
"{",
"}",
"indexs",
"=",
"[",
"]",
"for",
"mark",
"in",
"marks",
":",
"i",
"=",
"docs",
".",
"find",
"(",
"mark",
")",
"if",
"i",
">=",
"0",
... | 28.275862 | 16.344828 |
def prepare_special_info_about_entry(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
dict - dict with info
... | [
"def",
"prepare_special_info_about_entry",
"(",
"i",
")",
":",
"# Add control info",
"d",
"=",
"{",
"'engine'",
":",
"'CK'",
",",
"'version'",
":",
"cfg",
"[",
"'version'",
"]",
"}",
"if",
"cfg",
".",
"get",
"(",
"'default_developer'",
",",
"''",
")",
"!="... | 26.162162 | 18.702703 |
def getMessage(self):
"""Returns a colorized log message based on the log level.
If the platform is windows the original message will be returned
without colorization windows escape codes are crazy.
:returns: ``str``
"""
msg = str(self.msg)
if self.args:
... | [
"def",
"getMessage",
"(",
"self",
")",
":",
"msg",
"=",
"str",
"(",
"self",
".",
"msg",
")",
"if",
"self",
".",
"args",
":",
"msg",
"=",
"msg",
"%",
"self",
".",
"args",
"if",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"==",
... | 35.25 | 17.875 |
def typed_fields(cls):
"""Return a tuple of this entity's TypedFields."""
# Checking cls._typed_fields could return a superclass _typed_fields
# value. So we check our class __dict__ which does not include
# inherited attributes.
klassdict = cls.__dict__
try:
... | [
"def",
"typed_fields",
"(",
"cls",
")",
":",
"# Checking cls._typed_fields could return a superclass _typed_fields",
"# value. So we check our class __dict__ which does not include",
"# inherited attributes.",
"klassdict",
"=",
"cls",
".",
"__dict__",
"try",
":",
"return",
"klassdi... | 37.357143 | 19.928571 |
def service_group(self, service_name):
"""
Args:
service_name: the name of the service in the service registry
Returns:
the name of the group the service is in, or None of the service was not found
"""
for group in EFConfig.SERVICE_GROUPS:
if self.services(group).has_key(service_na... | [
"def",
"service_group",
"(",
"self",
",",
"service_name",
")",
":",
"for",
"group",
"in",
"EFConfig",
".",
"SERVICE_GROUPS",
":",
"if",
"self",
".",
"services",
"(",
"group",
")",
".",
"has_key",
"(",
"service_name",
")",
":",
"return",
"group",
"return",
... | 31.909091 | 17.181818 |
def raise_enter_downtime_log_entry(self):
"""Raise CONTACT DOWNTIME ALERT entry (info level)
Format is : "CONTACT DOWNTIME ALERT: *get_name()*;STARTED;
Contact has entered a period of scheduled downtime"
Example : "CONTACT DOWNTIME ALERT: test_contact;STARTED;
... | [
"def",
"raise_enter_downtime_log_entry",
"(",
"self",
")",
":",
"brok",
"=",
"make_monitoring_log",
"(",
"'info'",
",",
"\"CONTACT DOWNTIME ALERT: %s;STARTED; \"",
"\"Contact has entered a period of scheduled downtime\"",
"%",
"self",
".",
"get_name",
"(",
")",
")",
"self",... | 44.857143 | 20.5 |
def dfa_word_acceptance(dfa: dict, word: list) -> bool:
""" Checks if a given **word** is accepted by a DFA,
returning True/false.
The word w is accepted by a DFA if DFA has an accepting run
on w. Since A is deterministic,
:math:`w ∈ L(A)` if and only if :math:`ρ(s_0 , w) ∈ F` .
:param dict df... | [
"def",
"dfa_word_acceptance",
"(",
"dfa",
":",
"dict",
",",
"word",
":",
"list",
")",
"->",
"bool",
":",
"current_state",
"=",
"dfa",
"[",
"'initial_state'",
"]",
"for",
"action",
"in",
"word",
":",
"if",
"(",
"current_state",
",",
"action",
")",
"in",
... | 33.291667 | 18.75 |
def configure(level=logging.WARNING, handler=None, formatter=None):
"""Configure Logr
@param handler: Logger message handler
@type handler: logging.Handler or None
@param formatter: Logger message Formatter
@type formatter: logging.Formatter or None
"""
if forma... | [
"def",
"configure",
"(",
"level",
"=",
"logging",
".",
"WARNING",
",",
"handler",
"=",
"None",
",",
"formatter",
"=",
"None",
")",
":",
"if",
"formatter",
"is",
"None",
":",
"formatter",
"=",
"LogrFormatter",
"(",
")",
"if",
"handler",
"is",
"None",
":... | 29.722222 | 14.944444 |
def prune_non_existent_outputs(compound_match_query):
"""Remove non-existent outputs from each MatchQuery in the given CompoundMatchQuery.
Each of the 2^n MatchQuery objects (except one) has been pruned to exclude some Traverse blocks,
For each of these, remove the outputs (that have been implicitly pruned... | [
"def",
"prune_non_existent_outputs",
"(",
"compound_match_query",
")",
":",
"if",
"len",
"(",
"compound_match_query",
".",
"match_queries",
")",
"==",
"1",
":",
"return",
"compound_match_query",
"elif",
"len",
"(",
"compound_match_query",
".",
"match_queries",
")",
... | 58.256757 | 31.432432 |
def predict(self, features):
"""Use the optimized pipeline to predict the target for a feature set.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
Returns
----------
array-like: {n_samples}
Predicted tar... | [
"def",
"predict",
"(",
"self",
",",
"features",
")",
":",
"if",
"not",
"self",
".",
"fitted_pipeline_",
":",
"raise",
"RuntimeError",
"(",
"'A pipeline has not yet been optimized. Please call fit() first.'",
")",
"features",
"=",
"self",
".",
"_check_dataset",
"(",
... | 31.5 | 23.95 |
def get_opt(key, config, section, booleans, repeatable):
"""Get one value from config file.
:raise DocoptcfgFileError: If an option is the wrong type.
:param str key: Option long name (e.g. --config).
:param ConfigParser config: ConfigParser instance with config file data already loaded.
:param st... | [
"def",
"get_opt",
"(",
"key",
",",
"config",
",",
"section",
",",
"booleans",
",",
"repeatable",
")",
":",
"# Handle repeatable non-boolean options (e.g. --file=file1.txt --file=file2.txt).",
"if",
"key",
"in",
"repeatable",
"and",
"key",
"not",
"in",
"booleans",
":",... | 40.848485 | 23.424242 |
def start(self, port):
"""
启动服务器
:param port: 端口号
:return:
"""
self.application = tornado.web.Application(self.views,
template_path=self.templatePath,
static_path=self.staticPath)
self.application.listen(port)
self.ioloop.... | [
"def",
"start",
"(",
"self",
",",
"port",
")",
":",
"self",
".",
"application",
"=",
"tornado",
".",
"web",
".",
"Application",
"(",
"self",
".",
"views",
",",
"template_path",
"=",
"self",
".",
"templatePath",
",",
"static_path",
"=",
"self",
".",
"st... | 28.818182 | 12.454545 |
def strategyKLogN(kls, n, k=4):
"""Return the directory names to preserve under the KLogN purge strategy."""
assert(k>1)
s = set([n])
i = 0
while k**i <= n:
s.update(range(n, n-k*k**i, -k**i))
i += 1
n -= n % k**i
return set(map(str, filter(lambda x:x>=0, s))) | [
"def",
"strategyKLogN",
"(",
"kls",
",",
"n",
",",
"k",
"=",
"4",
")",
":",
"assert",
"(",
"k",
">",
"1",
")",
"s",
"=",
"set",
"(",
"[",
"n",
"]",
")",
"i",
"=",
"0",
"while",
"k",
"**",
"i",
"<=",
"n",
":",
"s",
".",
"update",
"(",
"r... | 23 | 21.5 |
def to_gds(self, multiplier, timestamp=None):
"""
Convert this cell to a GDSII structure.
Parameters
----------
multiplier : number
A number that multiplies all dimensions written in the GDSII
structure.
timestamp : datetime object
Set... | [
"def",
"to_gds",
"(",
"self",
",",
"multiplier",
",",
"timestamp",
"=",
"None",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"today",
"(",
")",
"if",
"timestamp",
"is",
"None",
"else",
"timestamp",
"name",
"=",
"self",
".",
"name",
"if",
"... | 37.483871 | 18.83871 |
def to_result(self):
"""Convert to the Linter.run return value"""
text = [self.text]
if self.note:
text.append(self.note)
return {
'lnum': self.line_num,
'col': self.column,
'text': ' - '.join(text),
'type': self.types.get(self... | [
"def",
"to_result",
"(",
"self",
")",
":",
"text",
"=",
"[",
"self",
".",
"text",
"]",
"if",
"self",
".",
"note",
":",
"text",
".",
"append",
"(",
"self",
".",
"note",
")",
"return",
"{",
"'lnum'",
":",
"self",
".",
"line_num",
",",
"'col'",
":",... | 28.083333 | 15.75 |
def power_law(target, X, A1='', A2='', A3=''):
r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of *X*:
.. math::
r = A_{1} x^{A_{2}} + A_{3}
Parameters
----------
A1 -> A3 : string
The dictionary keys on the ... | [
"def",
"power_law",
"(",
"target",
",",
"X",
",",
"A1",
"=",
"''",
",",
"A2",
"=",
"''",
",",
"A3",
"=",
"''",
")",
":",
"A",
"=",
"_parse_args",
"(",
"target",
"=",
"target",
",",
"key",
"=",
"A1",
",",
"default",
"=",
"1.0",
")",
"B",
"=",
... | 29.066667 | 24.022222 |
def has_data(d, fullname):
"""Test if any of the `keys` of the `d` dictionary starts with `fullname`.
"""
fullname = r'%s-' % (fullname, )
for k in d:
if not k.startswith(fullname):
continue
return True
return False | [
"def",
"has_data",
"(",
"d",
",",
"fullname",
")",
":",
"fullname",
"=",
"r'%s-'",
"%",
"(",
"fullname",
",",
")",
"for",
"k",
"in",
"d",
":",
"if",
"not",
"k",
".",
"startswith",
"(",
"fullname",
")",
":",
"continue",
"return",
"True",
"return",
"... | 28.333333 | 12.222222 |
def get_query_param(request, key):
"""Get query parameter uniformly for GET and POST requests."""
value = request.query_params.get(key) or request.data.get(key)
if value is None:
raise KeyError()
return value | [
"def",
"get_query_param",
"(",
"request",
",",
"key",
")",
":",
"value",
"=",
"request",
".",
"query_params",
".",
"get",
"(",
"key",
")",
"or",
"request",
".",
"data",
".",
"get",
"(",
"key",
")",
"if",
"value",
"is",
"None",
":",
"raise",
"KeyError... | 37.833333 | 15.166667 |
def _get_oauth_session(self):
"""Creates a new OAuth session
:return:
- OAuth2Session object
"""
return self._get_session(
OAuth2Session(
client_id=self.client_id,
token=self.token,
token_updater=self.token_updater... | [
"def",
"_get_oauth_session",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_session",
"(",
"OAuth2Session",
"(",
"client_id",
"=",
"self",
".",
"client_id",
",",
"token",
"=",
"self",
".",
"token",
",",
"token_updater",
"=",
"self",
".",
"token_updater"... | 28.263158 | 14.421053 |
def as_dict(self):
"""
Json-serializable dict representation.
"""
structure = self.final_structure
d = {"has_gaussian_completed": self.properly_terminated,
"nsites": len(structure)}
comp = structure.composition
d["unit_cell_formula"] = comp.as_dict()
... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"structure",
"=",
"self",
".",
"final_structure",
"d",
"=",
"{",
"\"has_gaussian_completed\"",
":",
"self",
".",
"properly_terminated",
",",
"\"nsites\"",
":",
"len",
"(",
"structure",
")",
"}",
"comp",
"=",
"structur... | 34.681818 | 16.090909 |
def remove_action(self, action_name, action_id):
"""
Remove an existing action.
action_name -- name of the action
action_id -- ID of the action
Returns a boolean indicating the presence of the action.
"""
action = self.get_action(action_name, action_id)
... | [
"def",
"remove_action",
"(",
"self",
",",
"action_name",
",",
"action_id",
")",
":",
"action",
"=",
"self",
".",
"get_action",
"(",
"action_name",
",",
"action_id",
")",
"if",
"action",
"is",
"None",
":",
"return",
"False",
"action",
".",
"cancel",
"(",
... | 27.625 | 15.875 |
def reportTimes(self):
"""
Print out a formatted summary of the elapsed times for all the
performed steps.
"""
self.end = _ptime()
total_time = 0
print(ProcSteps.__report_header)
for step in self.order:
if 'elapsed' in self.steps[step]:
... | [
"def",
"reportTimes",
"(",
"self",
")",
":",
"self",
".",
"end",
"=",
"_ptime",
"(",
")",
"total_time",
"=",
"0",
"print",
"(",
"ProcSteps",
".",
"__report_header",
")",
"for",
"step",
"in",
"self",
".",
"order",
":",
"if",
"'elapsed'",
"in",
"self",
... | 32.631579 | 16.631579 |
def get_config():
"""
Prepare and return alembic config
These configurations used to live in alembic config initialiser, but that
just tight coupling. Ideally we should move that to userspace and find a
way to pass these into alembic commands.
@todo: think about it
"""
from boiler.migra... | [
"def",
"get_config",
"(",
")",
":",
"from",
"boiler",
".",
"migrations",
".",
"config",
"import",
"MigrationsConfig",
"# used for errors",
"map",
"=",
"dict",
"(",
"path",
"=",
"'MIGRATIONS_PATH'",
",",
"db_url",
"=",
"'SQLALCHEMY_DATABASE_URI'",
",",
"metadata",
... | 29.709677 | 18.354839 |
def choose_directory(message='Choose a directory', path="", parent=None):
"Show a dialog to choose a directory"
result = dialogs.directoryDialog(parent, message, path)
return result.path | [
"def",
"choose_directory",
"(",
"message",
"=",
"'Choose a directory'",
",",
"path",
"=",
"\"\"",
",",
"parent",
"=",
"None",
")",
":",
"result",
"=",
"dialogs",
".",
"directoryDialog",
"(",
"parent",
",",
"message",
",",
"path",
")",
"return",
"result",
"... | 49.5 | 18.5 |
def get_drug(drug_name: str,
name_is_generic: bool = False,
include_categories: bool = False) -> Optional[Drug]:
"""
Converts a drug name to a :class:`.Drug` class.
If you already have the generic name, you can get the Drug more
efficiently by setting ``name_is_generic=True``.... | [
"def",
"get_drug",
"(",
"drug_name",
":",
"str",
",",
"name_is_generic",
":",
"bool",
"=",
"False",
",",
"include_categories",
":",
"bool",
"=",
"False",
")",
"->",
"Optional",
"[",
"Drug",
"]",
":",
"drug_name",
"=",
"drug_name",
".",
"strip",
"(",
")",... | 35.73913 | 18.782609 |
def _download_py2(link, path, __hdr__):
"""Download a file from a link in Python 2."""
try:
req = urllib2.Request(link, headers=__hdr__)
u = urllib2.urlopen(req)
except Exception as e:
raise Exception(' Download failed with the error:\n{}'.format(e))
with open(path, 'wb') as out... | [
"def",
"_download_py2",
"(",
"link",
",",
"path",
",",
"__hdr__",
")",
":",
"try",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"link",
",",
"headers",
"=",
"__hdr__",
")",
"u",
"=",
"urllib2",
".",
"urlopen",
"(",
"req",
")",
"except",
"Exceptio... | 30.916667 | 17.416667 |
def chunked(iterable, n):
"""Break an iterable into lists of a given length::
>>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7]]
If the length of ``iterable`` is not evenly divisible by ``n``, the last
returned list will be shorter.
This is useful for splitting up... | [
"def",
"chunked",
"(",
"iterable",
",",
"n",
")",
":",
"return",
"iter",
"(",
"functools",
".",
"partial",
"(",
"take",
",",
"n",
",",
"iter",
"(",
"iterable",
")",
")",
",",
"[",
"]",
")"
] | 36.526316 | 24.631579 |
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' ... | [
"def",
"file_list",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"output",
"=",
"file_dict",
"(",
"*",
"packages",
")",
"files",
"=",
"[",
"]",
"for",
"package",
"in",
"list",
"(",
"output",
"[",
"'packages'... | 31.263158 | 22.421053 |
def _draw_multiclass(self):
"""
Draw the precision-recall curves in the multiclass case
"""
# TODO: handle colors better with a mapping and user input
if self.per_class:
for cls in self.classes_:
precision = self.precision_[cls]
recall ... | [
"def",
"_draw_multiclass",
"(",
"self",
")",
":",
"# TODO: handle colors better with a mapping and user input",
"if",
"self",
".",
"per_class",
":",
"for",
"cls",
"in",
"self",
".",
"classes_",
":",
"precision",
"=",
"self",
".",
"precision_",
"[",
"cls",
"]",
"... | 36.263158 | 17 |
def commitVersion(self):
''' return a GithubComponentVersion object for a specific commit if valid
'''
import re
commit_match = re.match('^[a-f0-9]{7,40}$', self.tagOrBranchSpec(), re.I)
if commit_match:
return GithubComponentVersion(
'', '', _getComm... | [
"def",
"commitVersion",
"(",
"self",
")",
":",
"import",
"re",
"commit_match",
"=",
"re",
".",
"match",
"(",
"'^[a-f0-9]{7,40}$'",
",",
"self",
".",
"tagOrBranchSpec",
"(",
")",
",",
"re",
".",
"I",
")",
"if",
"commit_match",
":",
"return",
"GithubComponen... | 34.833333 | 30.166667 |
def get_errors(self):
"""Verify that this MAR file is well formed.
Returns:
A list of strings describing errors in the MAR file
None if this MAR file appears well formed.
"""
errors = []
errors.extend(self._get_signature_errors())
errors.extend(s... | [
"def",
"get_errors",
"(",
"self",
")",
":",
"errors",
"=",
"[",
"]",
"errors",
".",
"extend",
"(",
"self",
".",
"_get_signature_errors",
"(",
")",
")",
"errors",
".",
"extend",
"(",
"self",
".",
"_get_additional_errors",
"(",
")",
")",
"errors",
".",
"... | 30.5 | 18 |
def create(self, name, *args, **kwargs):
"""
Standard task creation, but first check for the existence of the
containers, and raise an exception if they don't exist.
"""
cont = kwargs.get("cont")
if cont:
# Verify that it exists. If it doesn't, a NoSuchContain... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cont",
"=",
"kwargs",
".",
"get",
"(",
"\"cont\"",
")",
"if",
"cont",
":",
"# Verify that it exists. If it doesn't, a NoSuchContainer exception",
"# will be raised."... | 41.142857 | 15.142857 |
def _init_transformer(cls, data):
"""Convert input into a QuantumChannel subclass object or Operator object"""
# This handles common conversion for all QuantumChannel subclasses.
# If the input is already a QuantumChannel subclass it will return
# the original object
if isinstanc... | [
"def",
"_init_transformer",
"(",
"cls",
",",
"data",
")",
":",
"# This handles common conversion for all QuantumChannel subclasses.",
"# If the input is already a QuantumChannel subclass it will return",
"# the original object",
"if",
"isinstance",
"(",
"data",
",",
"QuantumChannel",... | 55.26087 | 18.391304 |
def indent(indent_str=None):
"""
A complete, standalone indent ruleset.
Arguments:
indent_str
The string used for indentation. Defaults to None, which will
defer the value used to the one provided by the Dispatcher.
"""
def indentation_rule():
inst = Indentator(indent... | [
"def",
"indent",
"(",
"indent_str",
"=",
"None",
")",
":",
"def",
"indentation_rule",
"(",
")",
":",
"inst",
"=",
"Indentator",
"(",
"indent_str",
")",
"return",
"{",
"'layout_handlers'",
":",
"{",
"OpenBlock",
":",
"layout_handler_openbrace",
",",
"CloseBlock... | 38 | 16.666667 |
def apply_weight_drop(block, local_param_regex, rate, axes=(),
weight_dropout_mode='training'):
"""Apply weight drop to the parameter of a block.
Parameters
----------
block : Block or HybridBlock
The block whose parameter is to be applied weight-drop.
local_param_rege... | [
"def",
"apply_weight_drop",
"(",
"block",
",",
"local_param_regex",
",",
"rate",
",",
"axes",
"=",
"(",
")",
",",
"weight_dropout_mode",
"=",
"'training'",
")",
":",
"if",
"not",
"rate",
":",
"return",
"existing_params",
"=",
"_find_params",
"(",
"block",
",... | 49.886076 | 24.594937 |
def _get_corresponding_parsers(self, func):
"""Get the parser that has been set up by the given `function`"""
if func in self._used_functions:
yield self
if self._subparsers_action is not None:
for parser in self._subparsers_action.choices.values():
for sp... | [
"def",
"_get_corresponding_parsers",
"(",
"self",
",",
"func",
")",
":",
"if",
"func",
"in",
"self",
".",
"_used_functions",
":",
"yield",
"self",
"if",
"self",
".",
"_subparsers_action",
"is",
"not",
"None",
":",
"for",
"parser",
"in",
"self",
".",
"_subp... | 48.25 | 11.625 |
def _split_stock_code(self, code):
stock_str = str(code)
split_loc = stock_str.find(".")
'''do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original cod... | [
"def",
"_split_stock_code",
"(",
"self",
",",
"code",
")",
":",
"stock_str",
"=",
"str",
"(",
"code",
")",
"split_loc",
"=",
"stock_str",
".",
"find",
"(",
"\".\"",
")",
"if",
"0",
"<=",
"split_loc",
"<",
"len",
"(",
"stock_str",
")",
"-",
"1",
"and"... | 46.4375 | 23.1875 |
def get_event_stream(self):
"""Get the event stream associated with this WVA
Note that this event stream is shared across all users of this WVA device
as the WVA only supports a single event stream.
:return: a new :class:`WVAEventStream` instance
"""
if self._event_stre... | [
"def",
"get_event_stream",
"(",
"self",
")",
":",
"if",
"self",
".",
"_event_stream",
"is",
"None",
":",
"self",
".",
"_event_stream",
"=",
"WVAEventStream",
"(",
"self",
".",
"_http_client",
")",
"return",
"self",
".",
"_event_stream"
] | 38.363636 | 18.090909 |
def remove(self, pools):
"""
Remove Pools Running Script And Update to Not Created
:param ids: List of ids
:return: None on success
:raise ScriptRemovePoolException
:raise InvalidIdPoolException
:raise NetworkAPIException
"""
... | [
"def",
"remove",
"(",
"self",
",",
"pools",
")",
":",
"data",
"=",
"dict",
"(",
")",
"data",
"[",
"\"pools\"",
"]",
"=",
"pools",
"uri",
"=",
"\"api/pools/v2/\"",
"return",
"self",
".",
"delete",
"(",
"uri",
",",
"data",
")"
] | 22.157895 | 17.947368 |
def main(ctx, debug, base_config, env_file): # pragma: no cover
"""
\b
_____ _ _
| |___| |___ ___ _ _| |___
| | | | . | | -_| _| | | | -_|
|_|_|_|___|_|___|___|___|_|___|
Molecule aids in the development and testing of Ansible roles.
Enable autocomplete issue:
... | [
"def",
"main",
"(",
"ctx",
",",
"debug",
",",
"base_config",
",",
"env_file",
")",
":",
"# pragma: no cover",
"ctx",
".",
"obj",
"=",
"{",
"}",
"ctx",
".",
"obj",
"[",
"'args'",
"]",
"=",
"{",
"}",
"ctx",
".",
"obj",
"[",
"'args'",
"]",
"[",
"'de... | 27.894737 | 16 |
def make_server(host, port, app=None,
server_class=AsyncWsgiServer,
handler_class=AsyncWsgiHandler,
ws_handler_class=None,
ws_path='/ws'):
"""Create server instance with an optional WebSocket handler
For pure WebSocket server ``app`` may be ``None... | [
"def",
"make_server",
"(",
"host",
",",
"port",
",",
"app",
"=",
"None",
",",
"server_class",
"=",
"AsyncWsgiServer",
",",
"handler_class",
"=",
"AsyncWsgiHandler",
",",
"ws_handler_class",
"=",
"None",
",",
"ws_path",
"=",
"'/ws'",
")",
":",
"handler_class",
... | 40.62963 | 16.962963 |
def uncompress(payload):
"""
Given a compressed ec key in bytes, uncompress it using math and return (x, y)
"""
payload = hexlify(payload)
even = payload[:2] == b"02"
x = int(payload[2:], 16)
beta = pow(int(x ** 3 + A * x + B), int((P + 1) // 4), int(P))
y = (P-beta) if even else beta
... | [
"def",
"uncompress",
"(",
"payload",
")",
":",
"payload",
"=",
"hexlify",
"(",
"payload",
")",
"even",
"=",
"payload",
"[",
":",
"2",
"]",
"==",
"b\"02\"",
"x",
"=",
"int",
"(",
"payload",
"[",
"2",
":",
"]",
",",
"16",
")",
"beta",
"=",
"pow",
... | 32.4 | 14.6 |
def multiplication_circuit(nbit, vartype=dimod.BINARY):
"""Multiplication circuit constraint satisfaction problem.
A constraint satisfaction problem that represents the binary multiplication :math:`ab=p`,
where the multiplicands are binary variables of length `nbit`; for example,
:math:`a_0 + 2a_1 + 4a... | [
"def",
"multiplication_circuit",
"(",
"nbit",
",",
"vartype",
"=",
"dimod",
".",
"BINARY",
")",
":",
"if",
"nbit",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"num_multiplier_bits, num_multiplicand_bits must be positive integers\"",
")",
"num_multiplier_bits",
"=",
"... | 43.395349 | 28.680233 |
def _insertFont(self, fontname, bfname, fontfile, fontbuffer, set_simple, idx, wmode, serif, encoding, ordering):
"""_insertFont(self, fontname, bfname, fontfile, fontbuffer, set_simple, idx, wmode, serif, encoding, ordering) -> PyObject *"""
return _fitz.Page__insertFont(self, fontname, bfname, fontfil... | [
"def",
"_insertFont",
"(",
"self",
",",
"fontname",
",",
"bfname",
",",
"fontfile",
",",
"fontbuffer",
",",
"set_simple",
",",
"idx",
",",
"wmode",
",",
"serif",
",",
"encoding",
",",
"ordering",
")",
":",
"return",
"_fitz",
".",
"Page__insertFont",
"(",
... | 127.666667 | 55.666667 |
def get_price(self):
""" Shortcut to self.get_ticks(lookback=1, as_dict=True)['last'] """
tick = self.get_ticks(lookback=1, as_dict=True)
return None if tick is None else tick['last'] | [
"def",
"get_price",
"(",
"self",
")",
":",
"tick",
"=",
"self",
".",
"get_ticks",
"(",
"lookback",
"=",
"1",
",",
"as_dict",
"=",
"True",
")",
"return",
"None",
"if",
"tick",
"is",
"None",
"else",
"tick",
"[",
"'last'",
"]"
] | 51 | 12 |
def get_structure_by_material_id(self, material_id, final=True,
conventional_unit_cell=False):
"""
Get a Structure corresponding to a material_id.
Args:
material_id (str): Materials Project material_id (a string,
e.g., mp-1234).
... | [
"def",
"get_structure_by_material_id",
"(",
"self",
",",
"material_id",
",",
"final",
"=",
"True",
",",
"conventional_unit_cell",
"=",
"False",
")",
":",
"prop",
"=",
"\"final_structure\"",
"if",
"final",
"else",
"\"initial_structure\"",
"data",
"=",
"self",
".",
... | 41.318182 | 19.5 |
def function_arguments(func):
"""
This returns a list of all arguments
:param func: callable object
:return: list of str of the arguments for the function
"""
if getattr(inspect, 'signature', None) is None:
return list(inspect.getargspec(func).args)
else:
return list(inspect.... | [
"def",
"function_arguments",
"(",
"func",
")",
":",
"if",
"getattr",
"(",
"inspect",
",",
"'signature'",
",",
"None",
")",
"is",
"None",
":",
"return",
"list",
"(",
"inspect",
".",
"getargspec",
"(",
"func",
")",
".",
"args",
")",
"else",
":",
"return"... | 34.5 | 11.1 |
def _maybe_coerce_values(self, values):
"""Input validation for values passed to __init__. Ensure that
we have datetime64TZ, coercing if necessary.
Parametetrs
-----------
values : array-like
Must be convertible to datetime64
Returns
-------
... | [
"def",
"_maybe_coerce_values",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"self",
".",
"_holder",
")",
":",
"values",
"=",
"self",
".",
"_holder",
"(",
"values",
")",
"if",
"values",
".",
"tz",
"is",
"None",
... | 27.85 | 18.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.