text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def sep1(parser, separator):
"""Like sep but must consume at least one of parser.
"""
first = [parser()]
def inner():
separator()
return parser()
return first + many(tri(inner)) | [
"def",
"sep1",
"(",
"parser",
",",
"separator",
")",
":",
"first",
"=",
"[",
"parser",
"(",
")",
"]",
"def",
"inner",
"(",
")",
":",
"separator",
"(",
")",
"return",
"parser",
"(",
")",
"return",
"first",
"+",
"many",
"(",
"tri",
"(",
"inner",
")... | 25.75 | 12.125 |
def louvain_clustering(self, X=None, res=1, method='modularity'):
"""Runs Louvain clustering using the vtraag implementation. Assumes
that 'louvain' optional dependency is installed.
Parameters
----------
res - float, optional, default 1
The resolution parameter whic... | [
"def",
"louvain_clustering",
"(",
"self",
",",
"X",
"=",
"None",
",",
"res",
"=",
"1",
",",
"method",
"=",
"'modularity'",
")",
":",
"if",
"X",
"is",
"None",
":",
"X",
"=",
"self",
".",
"adata",
".",
"uns",
"[",
"'neighbors'",
"]",
"[",
"'connectiv... | 33.115385 | 19.307692 |
def _R2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
... | [
"def",
"_R2deriv",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"return",
"self",
".",
"_denom",
"(",
"R",
",",
"z",
")",
"**",
"-",
"1.5",
"-",
"3.",
"*",
"R",
"**",
"2",
"*",
"self",
".",
"_deno... | 29.411765 | 15.882353 |
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
... | [
"def",
"_valid_deleted_file",
"(",
"path",
")",
":",
"ret",
"=",
"False",
"if",
"path",
".",
"endswith",
"(",
"' (deleted)'",
")",
":",
"ret",
"=",
"True",
"if",
"re",
".",
"compile",
"(",
"r\"\\(path inode=[0-9]+\\)$\"",
")",
".",
"search",
"(",
"path",
... | 25.05 | 24.45 |
def map_aliases_to_device_objects(self):
"""
A device object knows its rid, but not its alias.
A portal object knows its device rids and aliases.
This function adds an 'portals_aliases' key to all of the
device objects so they can be sorted by alias.
"""... | [
"def",
"map_aliases_to_device_objects",
"(",
"self",
")",
":",
"all_devices",
"=",
"self",
".",
"get_all_devices_in_portal",
"(",
")",
"for",
"dev_o",
"in",
"all_devices",
":",
"dev_o",
"[",
"'portals_aliases'",
"]",
"=",
"self",
".",
"get_portal_by_name",
"(",
... | 46.642857 | 19.5 |
def get_index_list(nside, nest, region):
""" Returns the list of pixels indices for all the pixels in a region
nside : HEALPix nside parameter
nest : True for 'NESTED', False = 'RING'
region : HEALPix region string
"""
tokens = parse_hpxregion(region)
i... | [
"def",
"get_index_list",
"(",
"nside",
",",
"nest",
",",
"region",
")",
":",
"tokens",
"=",
"parse_hpxregion",
"(",
"region",
")",
"if",
"tokens",
"[",
"0",
"]",
"==",
"'DISK'",
":",
"vec",
"=",
"coords_to_vec",
"(",
"float",
"(",
"tokens",
"[",
"1",
... | 44.59375 | 16.34375 |
def unregister(self, provider_class):
"""
Unregisters a provider from the site.
"""
if not issubclass(provider_class, BaseProvider):
raise TypeError('%s must be a subclass of BaseProvider' % provider_class.__name__)
if provider_class not in self._registered_p... | [
"def",
"unregister",
"(",
"self",
",",
"provider_class",
")",
":",
"if",
"not",
"issubclass",
"(",
"provider_class",
",",
"BaseProvider",
")",
":",
"raise",
"TypeError",
"(",
"'%s must be a subclass of BaseProvider'",
"%",
"provider_class",
".",
"__name__",
")",
"... | 38.714286 | 19 |
def get_assign_annotation(node):
"""Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None... | [
"def",
"get_assign_annotation",
"(",
"node",
")",
":",
"annotation",
"=",
"None",
"annotation_node",
"=",
"None",
"try",
":",
"annotation_node",
"=",
"node",
".",
"annotation",
"except",
"AttributeError",
":",
"# Python 2 has no support for type annotations, so use getatt... | 31.2 | 21.28 |
def _call_when_changed(self, ticks, state):
"""
Called to fire the :attr:`when_changed` event handler; override this
in descendents if additional (currently redundant) parameters need
to be passed.
"""
method = self._when_changed()
if method is None:
s... | [
"def",
"_call_when_changed",
"(",
"self",
",",
"ticks",
",",
"state",
")",
":",
"method",
"=",
"self",
".",
"_when_changed",
"(",
")",
"if",
"method",
"is",
"None",
":",
"self",
".",
"when_changed",
"=",
"None",
"else",
":",
"method",
"(",
"ticks",
","... | 34.545455 | 13.454545 |
def set_default_property_values(self, dev_class, class_prop, dev_prop):
"""
set_default_property_values(self, dev_class, class_prop, dev_prop) -> None
Sets the default property values
Parameters :
- dev_class : (DeviceClass) device class object
... | [
"def",
"set_default_property_values",
"(",
"self",
",",
"dev_class",
",",
"class_prop",
",",
"dev_prop",
")",
":",
"for",
"name",
"in",
"class_prop",
":",
"type",
"=",
"self",
".",
"get_property_type",
"(",
"name",
",",
"class_prop",
")",
"val",
"=",
"self",... | 42 | 20.153846 |
def write_data(self, variable_id, value):
"""
write values to the device
"""
i = 0
j = 0
while i < 10:
try:
self.inst.query('*IDN?')
logger.info("Visa-MDO3014-Write- variable_id : %s et value : %s" %(variable_id, value))
... | [
"def",
"write_data",
"(",
"self",
",",
"variable_id",
",",
"value",
")",
":",
"i",
"=",
"0",
"j",
"=",
"0",
"while",
"i",
"<",
"10",
":",
"try",
":",
"self",
".",
"inst",
".",
"query",
"(",
"'*IDN?'",
")",
"logger",
".",
"info",
"(",
"\"Visa-MDO3... | 46.131944 | 22.1875 |
def from_excel_to_ymd(excel_int):
"""
converts date in Microsoft Excel representation style and returns `(year, month, day)` tuple
:param int excel_int: date as int (days since 1899-12-31)
:return tuple(int, int, int):
"""
int_date = int(floor(excel_int))
int_date -= 1 if excel_int > 60 e... | [
"def",
"from_excel_to_ymd",
"(",
"excel_int",
")",
":",
"int_date",
"=",
"int",
"(",
"floor",
"(",
"excel_int",
")",
")",
"int_date",
"-=",
"1",
"if",
"excel_int",
">",
"60",
"else",
"0",
"# jan dingerkus: There are two errors in excels own date <> int conversion.",
... | 32.971429 | 24.514286 |
def constrain_opts(self, constraint_dict, options):
""" Return result of constraints and options against a template """
constraints = {}
for constraint in constraint_dict:
if constraint != 'self':
if (constraint_dict[constraint] or
constraint_d... | [
"def",
"constrain_opts",
"(",
"self",
",",
"constraint_dict",
",",
"options",
")",
":",
"constraints",
"=",
"{",
"}",
"for",
"constraint",
"in",
"constraint_dict",
":",
"if",
"constraint",
"!=",
"'self'",
":",
"if",
"(",
"constraint_dict",
"[",
"constraint",
... | 52.272727 | 13.272727 |
def _split(self, string):
"""Iterates over the ngrams of a string (no padding).
>>> from ngram import NGram
>>> n = NGram()
>>> list(n._split("hamegg"))
['ham', 'ame', 'meg', 'egg']
"""
for i in range(len(string) - self.N + 1):
yield string[i:i + self... | [
"def",
"_split",
"(",
"self",
",",
"string",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"string",
")",
"-",
"self",
".",
"N",
"+",
"1",
")",
":",
"yield",
"string",
"[",
"i",
":",
"i",
"+",
"self",
".",
"N",
"]"
] | 31.4 | 9.6 |
def undo(self):
''' Undo the last action. '''
if self.canundo():
undoable = self._undos.pop()
with self._pausereceiver():
try:
undoable.undo()
except:
self.clear()
raise
... | [
"def",
"undo",
"(",
"self",
")",
":",
"if",
"self",
".",
"canundo",
"(",
")",
":",
"undoable",
"=",
"self",
".",
"_undos",
".",
"pop",
"(",
")",
"with",
"self",
".",
"_pausereceiver",
"(",
")",
":",
"try",
":",
"undoable",
".",
"undo",
"(",
")",
... | 31.076923 | 10.461538 |
def create_background(bg_type, fafile, outfile, genome="hg18", width=200, nr_times=10, custom_background=None):
"""Create background of a specific type.
Parameters
----------
bg_type : str
Name of background type.
fafile : str
Name of input FASTA file.
outfile : str
Na... | [
"def",
"create_background",
"(",
"bg_type",
",",
"fafile",
",",
"outfile",
",",
"genome",
"=",
"\"hg18\"",
",",
"width",
"=",
"200",
",",
"nr_times",
"=",
"10",
",",
"custom_background",
"=",
"None",
")",
":",
"width",
"=",
"int",
"(",
"width",
")",
"c... | 35.662921 | 21.696629 |
def confusion_matrix(y_true, y_pred, target_names=None, normalize=False,
cmap=None, ax=None):
"""
Plot confustion matrix.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_pred : array-like, shape = [n_samples]
... | [
"def",
"confusion_matrix",
"(",
"y_true",
",",
"y_pred",
",",
"target_names",
"=",
"None",
",",
"normalize",
"=",
"False",
",",
"cmap",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"if",
"any",
"(",
"(",
"val",
"is",
"None",
"for",
"val",
"in",
"... | 33.096774 | 20.666667 |
def prev_sibling(self):
"""
The node immediately preceding the invocant in their parent's children
list. If the invocant does not have a previous sibling, it is None.
"""
if self.parent is None:
return None
# Can't use index(); we need to test by identity
... | [
"def",
"prev_sibling",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"None",
"# Can't use index(); we need to test by identity",
"for",
"i",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"parent",
".",
"children",
")",
... | 35.571429 | 16.428571 |
def _init_metadata(self):
"""stub"""
self._min_string_length = None
self._max_string_length = None
self._texts_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'te... | [
"def",
"_init_metadata",
"(",
"self",
")",
":",
"self",
".",
"_min_string_length",
"=",
"None",
"self",
".",
"_max_string_length",
"=",
"None",
"self",
".",
"_texts_metadata",
"=",
"{",
"'element_id'",
":",
"Id",
"(",
"self",
".",
"my_osid_object_form",
".",
... | 38 | 12.545455 |
def set_result(self, values, visible_columns={}):
"""Set the result of this run.
Use this method instead of manually setting the run attributes and calling after_execution(),
this method handles all this by itself.
@param values: a dictionary with result values as returned by RunExecutor... | [
"def",
"set_result",
"(",
"self",
",",
"values",
",",
"visible_columns",
"=",
"{",
"}",
")",
":",
"exitcode",
"=",
"values",
".",
"pop",
"(",
"'exitcode'",
",",
"None",
")",
"if",
"exitcode",
"is",
"not",
"None",
":",
"self",
".",
"values",
"[",
"'@e... | 48.179487 | 17.897436 |
def show_vcs_output_vcs_cluster_type_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
vcs_cluster_type_info = ET.SubElement(output, "vcs-cl... | [
"def",
"show_vcs_output_vcs_cluster_type_info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_vcs",
"=",
"ET",
".",
"Element",
"(",
"\"show_vcs\"",
")",
"config",
"=",
"show_vcs",
"output",... | 40.833333 | 15.25 |
def from_status(status, message=None, extra=None):
""" Try to create an error from status code
:param int status: HTTP status
:param str message: Body content
:param dict extra: Additional info
:return: An error
:rtype: cdumay_rest_client.errors.Error
"""
if status in HTTP_STATUS_CODES:... | [
"def",
"from_status",
"(",
"status",
",",
"message",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"if",
"status",
"in",
"HTTP_STATUS_CODES",
":",
"return",
"HTTP_STATUS_CODES",
"[",
"status",
"]",
"(",
"message",
"=",
"message",
",",
"extra",
"=",
"... | 32.25 | 15.625 |
def image_name(self):
"""
The image_name of a container is the concatenation of the ``image_index``,
``image_name_prefix``, and ``name`` of the image.
Also, if $EXTRA_IMAGE_NAME is defined, that is appended
"""
if getattr(self, "_image_name", NotSpecified) is NotSpecifie... | [
"def",
"image_name",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"\"_image_name\"",
",",
"NotSpecified",
")",
"is",
"NotSpecified",
":",
"self",
".",
"_image_name",
"=",
"self",
".",
"prefixed_image_name",
"if",
"self",
".",
"image_index",
":",... | 41.6875 | 24.8125 |
def is_unit_paused_set():
"""Return the state of the kv().get('unit-paused').
This does NOT verify that the unit really is paused.
To help with units that don't have HookData() (testing)
if it excepts, return False
"""
try:
with unitdata.HookData()() as t:
kv = t[0]
... | [
"def",
"is_unit_paused_set",
"(",
")",
":",
"try",
":",
"with",
"unitdata",
".",
"HookData",
"(",
")",
"(",
")",
"as",
"t",
":",
"kv",
"=",
"t",
"[",
"0",
"]",
"# transform something truth-y into a Boolean.",
"return",
"not",
"(",
"not",
"(",
"kv",
".",
... | 32.142857 | 15.428571 |
def index_queryset(self, using=None):
"""
Used when the entire index for model is updated.
"""
return self.get_model().objects.filter(date_creation__lte=datetime.datetime.now()) | [
"def",
"index_queryset",
"(",
"self",
",",
"using",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_model",
"(",
")",
".",
"objects",
".",
"filter",
"(",
"date_creation__lte",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")"
] | 41 | 13.8 |
def threshold_monitor_hidden_threshold_monitor_sfp_policy_area_threshold_high_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-mon... | [
"def",
"threshold_monitor_hidden_threshold_monitor_sfp_policy_area_threshold_high_threshold",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"threshold_monitor_hidden",
"=",
"ET",
".",
"SubElement",
"(",
"c... | 54.047619 | 20.857143 |
def get_key(self, section, key):
"""
Gets key value from settings file.
:param section: Current section to retrieve key from.
:type section: unicode
:param key: Current key to retrieve.
:type key: unicode
:return: Current key value.
:rtype: object
... | [
"def",
"get_key",
"(",
"self",
",",
"section",
",",
"key",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Retrieving '{0}' in '{1}' section.\"",
".",
"format",
"(",
"key",
",",
"section",
")",
")",
"self",
".",
"__settings",
".",
"beginGroup",
"(",
"section",
... | 29.55 | 16.55 |
def main(arg1=55, arg2='test', arg3=None):
"""
This is a sample program to show how a learning agent can
be logged using AIKIF.
The idea is that this main function is your algorithm, which
will run until it finds a successful result. The result is
returned and the time taken is logged.
... | [
"def",
"main",
"(",
"arg1",
"=",
"55",
",",
"arg2",
"=",
"'test'",
",",
"arg3",
"=",
"None",
")",
":",
"print",
"(",
"'Starting dummy AI algorithm with :'",
",",
"arg1",
",",
"arg2",
",",
"arg3",
")",
"if",
"arg3",
"is",
"None",
":",
"arg3",
"=",
"["... | 33.789474 | 16.315789 |
def register_entry_points(self, exclude=()):
"""Allow Gears plugins to inject themselves to the environment. For
example, if your plugin's package contains such ``entry_points``
definition in ``setup.py``, ``gears_plugin.register`` function will be
called with current environment during ... | [
"def",
"register_entry_points",
"(",
"self",
",",
"exclude",
"=",
"(",
")",
")",
":",
"for",
"entry_point",
"in",
"iter_entry_points",
"(",
"'gears'",
",",
"'register'",
")",
":",
"if",
"entry_point",
".",
"module_name",
"not",
"in",
"exclude",
":",
"registe... | 41.714286 | 22 |
def pending():
"""Show the number of pending signals by signal type."""
signalbus = current_app.extensions['signalbus']
pending = []
total_pending = 0
for signal_model in signalbus.get_signal_models():
count = signal_model.query.count()
if count > 0:
pending.append((coun... | [
"def",
"pending",
"(",
")",
":",
"signalbus",
"=",
"current_app",
".",
"extensions",
"[",
"'signalbus'",
"]",
"pending",
"=",
"[",
"]",
"total_pending",
"=",
"0",
"for",
"signal_model",
"in",
"signalbus",
".",
"get_signal_models",
"(",
")",
":",
"count",
"... | 36.333333 | 17.333333 |
def wrapup(self):
"""
Finishes up after execution finishes, does not remove any graphical output.
"""
self._loader = None
self._iterator = None
super(LoadDataset, self).wrapup() | [
"def",
"wrapup",
"(",
"self",
")",
":",
"self",
".",
"_loader",
"=",
"None",
"self",
".",
"_iterator",
"=",
"None",
"super",
"(",
"LoadDataset",
",",
"self",
")",
".",
"wrapup",
"(",
")"
] | 31.285714 | 13 |
def read_msh(path):
"""
Reads a GMSH MSH file and returns a :class:`Mesh` instance.
:arg path: path to MSH file.
:type path: str
"""
elementMap = { 15:"point1",
1:"line2",
2:"tri3",
3:"quad4",
4:"tetra4",
5:"hexa8",
... | [
"def",
"read_msh",
"(",
"path",
")",
":",
"elementMap",
"=",
"{",
"15",
":",
"\"point1\"",
",",
"1",
":",
"\"line2\"",
",",
"2",
":",
"\"tri3\"",
",",
"3",
":",
"\"quad4\"",
",",
"4",
":",
"\"tetra4\"",
",",
"5",
":",
"\"hexa8\"",
",",
"6",
":",
... | 31.52381 | 14.920635 |
def read_certificate(self, certificate_name):
'''
a method to retrieve the details about a server certificate
:param certificate_name: string with name of server certificate
:return: dictionary with certificate details
'''
title = '%s.read_certificate' % self.__cla... | [
"def",
"read_certificate",
"(",
"self",
",",
"certificate_name",
")",
":",
"title",
"=",
"'%s.read_certificate'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs",
"input_fields",
"=",
"{",
"'certificate_name'",
":",
"certificate_name",
"}",
"for"... | 39.042553 | 21.382979 |
def rtl_all(*vectorlist):
""" Hardware equivalent of python native "all".
:param WireVector vectorlist: all arguments are WireVectors of length 1
:return: WireVector of length 1
Returns a 1-bit WireVector which will hold a '1' only if all of the
inputs are '1' (i.e. it is a big ol' AND gate)
"... | [
"def",
"rtl_all",
"(",
"*",
"vectorlist",
")",
":",
"if",
"len",
"(",
"vectorlist",
")",
"<=",
"0",
":",
"raise",
"PyrtlError",
"(",
"'rtl_all requires at least 1 argument'",
")",
"converted_vectorlist",
"=",
"[",
"as_wires",
"(",
"v",
")",
"for",
"v",
"in",... | 43.733333 | 20.133333 |
def __grabHotkey(self, key, modifiers, window):
"""
Grab a specific hotkey in the given window
"""
logger.debug("Grabbing hotkey: %r %r", modifiers, key)
try:
keycode = self.__lookupKeyCode(key)
mask = 0
for mod in modifiers:
ma... | [
"def",
"__grabHotkey",
"(",
"self",
",",
"key",
",",
"modifiers",
",",
"window",
")",
":",
"logger",
".",
"debug",
"(",
"\"Grabbing hotkey: %r %r\"",
",",
"modifiers",
",",
"key",
")",
"try",
":",
"keycode",
"=",
"self",
".",
"__lookupKeyCode",
"(",
"key",... | 44.458333 | 28.958333 |
def extract_body(mail, types=None, field_key='copiousoutput'):
"""Returns a string view of a Message.
If the `types` argument is set then any encoding types there will be used
as the prefered encoding to extract. If `types` is None then
:ref:`prefer_plaintext <prefer-plaintext>` will be consulted; if i... | [
"def",
"extract_body",
"(",
"mail",
",",
"types",
"=",
"None",
",",
"field_key",
"=",
"'copiousoutput'",
")",
":",
"preferred",
"=",
"'text/plain'",
"if",
"settings",
".",
"get",
"(",
"'prefer_plaintext'",
")",
"else",
"'text/html'",
"has_preferred",
"=",
"Fal... | 37.017544 | 19.666667 |
def _get_coordinator_for_group(self, group):
"""
Returns the coordinator broker for a consumer group.
GroupCoordinatorNotAvailableError will be raised if the coordinator
does not currently exist for the group.
GroupLoadInProgressError is raised if the coordinator is available
... | [
"def",
"_get_coordinator_for_group",
"(",
"self",
",",
"group",
")",
":",
"resp",
"=",
"self",
".",
"send_consumer_metadata_request",
"(",
"group",
")",
"# If there's a problem with finding the coordinator, raise the",
"# provided error",
"kafka",
".",
"errors",
".",
"che... | 36.105263 | 22.105263 |
def _get_voltage_magnitude_var(self, buses, generators):
""" Returns the voltage magnitude variable set.
"""
Vm = array([b.v_magnitude for b in buses])
# For buses with generators initialise Vm from gen data.
for g in generators:
Vm[g.bus._i] = g.v_magnitude
... | [
"def",
"_get_voltage_magnitude_var",
"(",
"self",
",",
"buses",
",",
"generators",
")",
":",
"Vm",
"=",
"array",
"(",
"[",
"b",
".",
"v_magnitude",
"for",
"b",
"in",
"buses",
"]",
")",
"# For buses with generators initialise Vm from gen data.",
"for",
"g",
"in",... | 34.846154 | 16.230769 |
def generate_description(dataset_name, local_cache_dir=None):
"""Generates desription for a given dataset in its README.md file in a dataset local_cache_dir file.
:param dataset_name: str
The name of the data set to load from PMLB.
:param local_cache_dir: str (required)
The directory on... | [
"def",
"generate_description",
"(",
"dataset_name",
",",
"local_cache_dir",
"=",
"None",
")",
":",
"assert",
"(",
"local_cache_dir",
"!=",
"None",
")",
"readme_file",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"local_cache_dir",
",",
"'datasets'",
... | 48.789474 | 21.394737 |
def regex_search(self, regex: str) -> List[HistoryItem]:
"""Find history items which match a given regular expression
:param regex: the regular expression to search for.
:return: a list of history items, or an empty list if the string was not found
"""
regex = regex.strip()
... | [
"def",
"regex_search",
"(",
"self",
",",
"regex",
":",
"str",
")",
"->",
"List",
"[",
"HistoryItem",
"]",
":",
"regex",
"=",
"regex",
".",
"strip",
"(",
")",
"if",
"regex",
".",
"startswith",
"(",
"r'/'",
")",
"and",
"regex",
".",
"endswith",
"(",
... | 45.133333 | 18.266667 |
def broadcast(self, response):
'''Broadcast ``message`` to all :attr:`clients`.'''
remove = set()
channel = to_string(response[0])
message = response[1]
if self.protocol:
try:
message = self.protocol.decode(message)
except ProtocolError:
... | [
"def",
"broadcast",
"(",
"self",
",",
"response",
")",
":",
"remove",
"=",
"set",
"(",
")",
"channel",
"=",
"to_string",
"(",
"response",
"[",
"0",
"]",
")",
"message",
"=",
"response",
"[",
"1",
"]",
"if",
"self",
".",
"protocol",
":",
"try",
":",... | 37.190476 | 13.095238 |
def create_admin_by_sis_id(self, sis_account_id, user_id, role):
"""
Flag an existing user as an admin within the account sis id.
"""
return self.create_admin(self._sis_id(sis_account_id), user_id, role) | [
"def",
"create_admin_by_sis_id",
"(",
"self",
",",
"sis_account_id",
",",
"user_id",
",",
"role",
")",
":",
"return",
"self",
".",
"create_admin",
"(",
"self",
".",
"_sis_id",
"(",
"sis_account_id",
")",
",",
"user_id",
",",
"role",
")"
] | 46.2 | 17.8 |
def install_virtualenv_p2(root, python_version):
""" Install virtual environment for Python 2.7+; removing the old one if it exists """
try:
import virtualenv
except ImportError:
sys.stdout.write('Installing virtualenv into global interpreter \n')
ret_code = subprocess.call([VE_GLOBA... | [
"def",
"install_virtualenv_p2",
"(",
"root",
",",
"python_version",
")",
":",
"try",
":",
"import",
"virtualenv",
"except",
"ImportError",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'Installing virtualenv into global interpreter \\n'",
")",
"ret_code",
"=",
"sub... | 46.4375 | 23.8125 |
def filter(self, s, method='chebyshev', order=30):
r"""Filter signals (analysis or synthesis).
A signal is defined as a rank-3 tensor of shape ``(N_NODES, N_SIGNALS,
N_FEATURES)``, where ``N_NODES`` is the number of nodes in the graph,
``N_SIGNALS`` is the number of independent signals,... | [
"def",
"filter",
"(",
"self",
",",
"s",
",",
"method",
"=",
"'chebyshev'",
",",
"order",
"=",
"30",
")",
":",
"s",
"=",
"self",
".",
"G",
".",
"_check_signal",
"(",
"s",
")",
"# TODO: not in self.Nin (Nf = Nin x Nout).",
"if",
"s",
".",
"ndim",
"==",
"... | 39.405405 | 23.102703 |
def GCT(gct_obj):
"""
Create a Dataframe with the contents of the GCT file
"""
# Handle all the various initialization types and get an IO object
gct_io = _obtain_io(gct_obj)
# Load the GCT file into a DataFrame
df = pd.read_csv(gct_io, sep='\t', header=2, index_col=[0, 1], skip_blank_lines... | [
"def",
"GCT",
"(",
"gct_obj",
")",
":",
"# Handle all the various initialization types and get an IO object",
"gct_io",
"=",
"_obtain_io",
"(",
"gct_obj",
")",
"# Load the GCT file into a DataFrame",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"gct_io",
",",
"sep",
"=",
"'... | 29 | 19.266667 |
def post_install_postgresql():
"""
example default hook for installing postgresql
"""
from django.conf import settings as s
with settings(warn_only=True):
sudo('/etc/init.d/postgresql-8.4 restart')
sudo("""psql template1 -c "ALTER USER postgres with encrypted password '%s';" """% env... | [
"def",
"post_install_postgresql",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"as",
"s",
"with",
"settings",
"(",
"warn_only",
"=",
"True",
")",
":",
"sudo",
"(",
"'/etc/init.d/postgresql-8.4 restart'",
")",
"sudo",
"(",
"\"\"\"psql templ... | 62.8125 | 20.0625 |
def system_info(query):
"""system_info(query) -- print system specific information like OS, kernel,
architecture etc.
"""
proc = subprocess.Popen(["uname -o"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "operating system : "+str(out),
proc = subprocess.Popen(["uname"], stdout=subp... | [
"def",
"system_info",
"(",
"query",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"uname -o\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"shell",
"=",
"True",
")",
"(",
"out",
",",
"err",
")",
"=",
"proc",
".",
"com... | 35.782609 | 18.73913 |
def remove_dependent_cols(M, tol=1e-6, display=False):
"""
Returns a matrix where dependent columsn have been removed
"""
R = la.qr(M, mode='r')[0][:M.shape[1], :]
I = (abs(R.diagonal())>tol)
if sp.any(~I) and display:
print(('cols ' + str(sp.where(~I)[0]) +
' have been r... | [
"def",
"remove_dependent_cols",
"(",
"M",
",",
"tol",
"=",
"1e-6",
",",
"display",
"=",
"False",
")",
":",
"R",
"=",
"la",
".",
"qr",
"(",
"M",
",",
"mode",
"=",
"'r'",
")",
"[",
"0",
"]",
"[",
":",
"M",
".",
"shape",
"[",
"1",
"]",
",",
":... | 32.384615 | 15.923077 |
def process_pc_pathsbetween(gene_names, neighbor_limit=1,
database_filter=None, block_size=None):
"""Returns a BiopaxProcessor for a PathwayCommons paths-between query.
The paths-between query finds the paths between a set of genes. Here
source gene names are given in a single l... | [
"def",
"process_pc_pathsbetween",
"(",
"gene_names",
",",
"neighbor_limit",
"=",
"1",
",",
"database_filter",
"=",
"None",
",",
"block_size",
"=",
"None",
")",
":",
"if",
"not",
"block_size",
":",
"model",
"=",
"pcc",
".",
"graph_query",
"(",
"'pathsbetween'",... | 44.844828 | 22.241379 |
def RunPlaybookOnHosts(playbook_path, hosts, private_key, extra_vars=None):
""" Runs the playbook and returns True if it completes successfully on all
hosts. """
inventory = ansible_inventory.Inventory(hosts)
if not inventory.list_hosts():
raise RuntimeError("Host list is empty.")
stats = callbacks.Aggreg... | [
"def",
"RunPlaybookOnHosts",
"(",
"playbook_path",
",",
"hosts",
",",
"private_key",
",",
"extra_vars",
"=",
"None",
")",
":",
"inventory",
"=",
"ansible_inventory",
".",
"Inventory",
"(",
"hosts",
")",
"if",
"not",
"inventory",
".",
"list_hosts",
"(",
")",
... | 41.444444 | 14.777778 |
def _api_get(self):
"""
A helper method to GET this object from the server
"""
json = self._client.get(type(self).api_endpoint, model=self)
self._populate(json) | [
"def",
"_api_get",
"(",
"self",
")",
":",
"json",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"type",
"(",
"self",
")",
".",
"api_endpoint",
",",
"model",
"=",
"self",
")",
"self",
".",
"_populate",
"(",
"json",
")"
] | 32.5 | 13.166667 |
def time_replacer(match, timestamp):
"""
Transforms the timestamp to the format the regex match determines.
:param str match: the regex match
:param time timestamp: the timestamp to format with match.group(1)
:return str: the timestamp formated with strftime the way the
... | [
"def",
"time_replacer",
"(",
"match",
",",
"timestamp",
")",
":",
"# match.group(0) = entire match",
"# match.group(1) = match in braces #1",
"return",
"time",
".",
"strftime",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"time",
".",
"gmtime",
"(",
"timestamp"... | 44.916667 | 17.25 |
def get_type(self):
"""
Return the type of the field
:rtype: string
"""
if self.type_idx_value == None:
self.type_idx_value = self.CM.get_type(self.type_idx)
return self.type_idx_value | [
"def",
"get_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"type_idx_value",
"==",
"None",
":",
"self",
".",
"type_idx_value",
"=",
"self",
".",
"CM",
".",
"get_type",
"(",
"self",
".",
"type_idx",
")",
"return",
"self",
".",
"type_idx_value"
] | 24.5 | 14.7 |
def _validate_singletons(self, boxes):
"""Several boxes can only occur once."""
count = self._collect_box_count(boxes)
# Which boxes occur more than once?
multiples = [box_id for box_id, bcount in count.items() if bcount > 1]
if 'dtbl' in multiples:
raise IOError('The... | [
"def",
"_validate_singletons",
"(",
"self",
",",
"boxes",
")",
":",
"count",
"=",
"self",
".",
"_collect_box_count",
"(",
"boxes",
")",
"# Which boxes occur more than once?",
"multiples",
"=",
"[",
"box_id",
"for",
"box_id",
",",
"bcount",
"in",
"count",
".",
... | 50.571429 | 12.571429 |
def load_app(target):
""" Load a bottle application based on a target string and return the
application object.
If the target is an import path (e.g. package.module), the application
stack is used to isolate the routes defined in that module.
If the target contains a colon (e.g. pac... | [
"def",
"load_app",
"(",
"target",
")",
":",
"tmp",
"=",
"app",
".",
"push",
"(",
")",
"# Create a new \"default application\"",
"rv",
"=",
"_load",
"(",
"target",
")",
"# Import the target module",
"app",
".",
"remove",
"(",
"tmp",
")",
"# Remove the temporary a... | 48.846154 | 19.923077 |
def en_last(self):
""" Report the energies from the last SCF present in the output.
Returns a |dict| providing the various energy values from the
last SCF cycle performed in the output. Keys are those of
:attr:`~opan.output.OrcaOutput.p_en`.
Any energy value not relevant to the ... | [
"def",
"en_last",
"(",
"self",
")",
":",
"# Initialize the return dict",
"last_ens",
"=",
"dict",
"(",
")",
"# Iterate and store",
"for",
"(",
"k",
",",
"l",
")",
"in",
"self",
".",
"en",
".",
"items",
"(",
")",
":",
"last_ens",
".",
"update",
"(",
"{"... | 28.740741 | 19.814815 |
def _get_args(cls, args):
# type: (tuple) -> Tuple[type, slice, Callable]
"""Return the parameters necessary to check type boundaries.
Args:
args: A slice representing the minimum and maximum lengths allowed
for values of that string.
Returns:
A ... | [
"def",
"_get_args",
"(",
"cls",
",",
"args",
")",
":",
"# type: (tuple) -> Tuple[type, slice, Callable]",
"if",
"isinstance",
"(",
"args",
",",
"tuple",
")",
":",
"raise",
"TypeError",
"(",
"\"{}[...] takes exactly one argument.\"",
".",
"format",
"(",
"cls",
".",
... | 36.294118 | 20.941176 |
def get_radians(self):
""" Return the angle between this vector and the positive x-axis
measured in radians. Result will be between -pi and pi. """
if not self: raise NullVectorError()
return math.atan2(self.y, self.x) | [
"def",
"get_radians",
"(",
"self",
")",
":",
"if",
"not",
"self",
":",
"raise",
"NullVectorError",
"(",
")",
"return",
"math",
".",
"atan2",
"(",
"self",
".",
"y",
",",
"self",
".",
"x",
")"
] | 49.4 | 4.6 |
def get_shift_by_data(temp_hourly, lon, lat, time_zone):
'''function to get max temp shift (monthly) by hourly data
Parameters
----
hourly_data_obs : observed hourly data
lat : latitude in DezDeg
lon : longitude in DezDeg
time_zone: timezone
'''
d... | [
"def",
"get_shift_by_data",
"(",
"temp_hourly",
",",
"lon",
",",
"lat",
",",
"time_zone",
")",
":",
"daily_index",
"=",
"temp_hourly",
".",
"resample",
"(",
"'D'",
")",
".",
"mean",
"(",
")",
".",
"index",
"sun_times",
"=",
"melodist",
".",
"util",
".",
... | 38.47619 | 20.190476 |
def update(self, file_id, data):
"""
Update a file in the File Manager.
:param file_id: The unique id for the File Manager file.
:type file_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": stri... | [
"def",
"update",
"(",
"self",
",",
"file_id",
",",
"data",
")",
":",
"self",
".",
"file_id",
"=",
"file_id",
"if",
"'name'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",
"'The file must have a name'",
")",
"if",
"'file_data'",
"not",
"in",
"data",
... | 34.421053 | 13.684211 |
def repository_get(name, local=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Get existing repository details.
name
Repository name
local
Retrieve only local information, default is false
CLI example::
salt myminion elasticsearch.repository_get testr... | [
"def",
"repository_get",
"(",
"name",
",",
"local",
"=",
"False",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"es",
"=",
"_get_instance",
"(",
"hosts",
",",
"profile",
")",
"try",
":",
"return",
"es",
".",
"snapshot",
".",
"get_... | 29.73913 | 27.913043 |
def generate_vectored_io_stripe_metadata(local_path, metadata):
# type: (blobxfer.models.upload.LocalPath, dict) -> dict
"""Generate vectored io stripe metadata dict
:param blobxfer.models.upload.LocalPath local_path: local path
:param dict metadata: existing metadata dict
:rtype: dict
:return: ... | [
"def",
"generate_vectored_io_stripe_metadata",
"(",
"local_path",
",",
"metadata",
")",
":",
"# type: (blobxfer.models.upload.LocalPath, dict) -> dict",
"md",
"=",
"{",
"_JSON_KEY_VECTORED_IO",
":",
"{",
"_JSON_KEY_VECTORED_IO_MODE",
":",
"_JSON_KEY_VECTORED_IO_STRIPE",
",",
"_... | 42.75 | 16.791667 |
def get_undecorated_callback(self):
""" Return the callback. If the callback is a decorated function, try to
recover the original function. """
func = self.callback
func = getattr(func, '__func__' if py3k else 'im_func', func)
closure_attr = '__closure__' if py3k else 'func_c... | [
"def",
"get_undecorated_callback",
"(",
"self",
")",
":",
"func",
"=",
"self",
".",
"callback",
"func",
"=",
"getattr",
"(",
"func",
",",
"'__func__'",
"if",
"py3k",
"else",
"'im_func'",
",",
"func",
")",
"closure_attr",
"=",
"'__closure__'",
"if",
"py3k",
... | 52.235294 | 18.705882 |
def get_logs(self, project, release_id, **kwargs):
"""GetLogs.
[Preview API] Get logs for a release Id.
:param str project: Project ID or project name
:param int release_id: Id of the release.
:rtype: object
"""
route_values = {}
if project is not None:
... | [
"def",
"get_logs",
"(",
"self",
",",
"project",
",",
"release_id",
",",
"*",
"*",
"kwargs",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
... | 45.863636 | 16.863636 |
def load(filename):
"""Retrieve a pickled object
Parameter
---------
filename : path
Return
------
object
Unpickled object
"""
filename = os.path.normcase(filename)
try:
with open(filename, 'rb') as f:
u = pickle.Unpickler(f)
return u.loa... | [
"def",
"load",
"(",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"filename",
")",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"u",
"=",
"pickle",
".",
"Unpickler",
"(",
"f",
")... | 21.052632 | 20.473684 |
def query_associations(self, subjects=None, infer_subjects=True, include_xrefs=True):
"""
Query for a set of associations.
Note: only a minimal association model is stored, so all results are returned as (subject_id,class_id) tuples
Arguments:
subjects: list
list o... | [
"def",
"query_associations",
"(",
"self",
",",
"subjects",
"=",
"None",
",",
"infer_subjects",
"=",
"True",
",",
"include_xrefs",
"=",
"True",
")",
":",
"if",
"subjects",
"is",
"None",
":",
"subjects",
"=",
"[",
"]",
"mset",
"=",
"set",
"(",
")",
"if",... | 37.26 | 25.54 |
def _update_font(self, textfont):
"""Updates text font widget
Parameters
----------
textfont: String
\tFont name
"""
try:
fontface_id = self.fonts.index(textfont)
except ValueError:
fontface_id = 0
self.font_choice_comb... | [
"def",
"_update_font",
"(",
"self",
",",
"textfont",
")",
":",
"try",
":",
"fontface_id",
"=",
"self",
".",
"fonts",
".",
"index",
"(",
"textfont",
")",
"except",
"ValueError",
":",
"fontface_id",
"=",
"0",
"self",
".",
"font_choice_combo",
".",
"Select",
... | 19.117647 | 21.470588 |
def magic(self, arg_s):
"""DEPRECATED. Use run_line_magic() instead.
Call a magic function by name.
Input: a string containing the name of the magic function to call and
any additional arguments to be passed to the magic.
magic('name -opt foo bar') is equivalent to typing at t... | [
"def",
"magic",
"(",
"self",
",",
"arg_s",
")",
":",
"# TODO: should we issue a loud deprecation warning here?",
"magic_name",
",",
"_",
",",
"magic_arg_s",
"=",
"arg_s",
".",
"partition",
"(",
"' '",
")",
"magic_name",
"=",
"magic_name",
".",
"lstrip",
"(",
"pr... | 37.913043 | 25 |
def get_group_permissions(self, user_obj, obj=None):
"""
Returns a set of permission strings that this user has through his/her
groups.
"""
if user_obj.is_anonymous() or obj is not None:
return set()
if not hasattr(user_obj, '_group_perm_cache'):
i... | [
"def",
"get_group_permissions",
"(",
"self",
",",
"user_obj",
",",
"obj",
"=",
"None",
")",
":",
"if",
"user_obj",
".",
"is_anonymous",
"(",
")",
"or",
"obj",
"is",
"not",
"None",
":",
"return",
"set",
"(",
")",
"if",
"not",
"hasattr",
"(",
"user_obj",... | 53.941176 | 25.235294 |
def extended_arg_patterns(self):
"""Iterator over patterns for positional arguments to be matched
This yields the elements of :attr:`args`, extended by their `mode`
value
"""
for arg in self._arg_iterator(self.args):
if isinstance(arg, Pattern):
if ar... | [
"def",
"extended_arg_patterns",
"(",
"self",
")",
":",
"for",
"arg",
"in",
"self",
".",
"_arg_iterator",
"(",
"self",
".",
"args",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Pattern",
")",
":",
"if",
"arg",
".",
"mode",
">",
"self",
".",
"single... | 32.6 | 13.6 |
def parse_supybot_log(filepath):
"""Parse a Supybot IRC log file.
The method parses the Supybot IRC log file and returns an iterator of
dictionaries. Each one of this, contains a message from the file.
:param filepath: path to the IRC log file
:returns: a generator of parsed m... | [
"def",
"parse_supybot_log",
"(",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"'r'",
",",
"errors",
"=",
"'surrogateescape'",
",",
"newline",
"=",
"os",
".",
"linesep",
")",
"as",
"f",
":",
"parser",
"=",
"SupybotParser",
"(",
"f",
")",
... | 35.68 | 19.48 |
def load(source, **kwargs) -> JsonObj:
""" Deserialize a JSON source.
:param source: a URI, File name or a .read()-supporting file-like object containing a JSON document
:param kwargs: arguments. see: json.load for details
:return: JsonObj representing fp
"""
if isinstance(source, str):
... | [
"def",
"load",
"(",
"source",
",",
"*",
"*",
"kwargs",
")",
"->",
"JsonObj",
":",
"if",
"isinstance",
"(",
"source",
",",
"str",
")",
":",
"if",
"'://'",
"in",
"source",
":",
"req",
"=",
"Request",
"(",
"source",
")",
"req",
".",
"add_header",
"(",... | 35.954545 | 17 |
def split(self):
"""Split the phase.
When a phase is exhausted, it gets split into a pair of phases to be
further solved. The split happens like so:
1) Select the first unsolved package scope.
2) Find some common dependency in the first N variants of the scope.
3) Split ... | [
"def",
"split",
"(",
"self",
")",
":",
"assert",
"(",
"self",
".",
"status",
"==",
"SolverStatus",
".",
"exhausted",
")",
"scopes",
"=",
"[",
"]",
"next_scopes",
"=",
"[",
"]",
"split_i",
"=",
"None",
"for",
"i",
",",
"scope",
"in",
"enumerate",
"(",... | 34.072727 | 18.727273 |
def convert_to_human_readable(sdp):
"""Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the mo... | [
"def",
"convert_to_human_readable",
"(",
"sdp",
")",
":",
"objective",
"=",
"\"\"",
"indices_in_objective",
"=",
"[",
"]",
"for",
"i",
",",
"tmp",
"in",
"enumerate",
"(",
"sdp",
".",
"obj_facvar",
")",
":",
"candidates",
"=",
"[",
"key",
"for",
"key",
",... | 37.530303 | 15.318182 |
def _supported_baremetal_transaction(self, context):
"""Verify transaction is complete and for us."""
port = context.current
if self.trunk.is_trunk_subport_baremetal(port):
return self._baremetal_set_binding(context)
if not nexus_help.is_baremetal(port):
return... | [
"def",
"_supported_baremetal_transaction",
"(",
"self",
",",
"context",
")",
":",
"port",
"=",
"context",
".",
"current",
"if",
"self",
".",
"trunk",
".",
"is_trunk_subport_baremetal",
"(",
"port",
")",
":",
"return",
"self",
".",
"_baremetal_set_binding",
"(",
... | 29.192308 | 20.538462 |
def _IncrementNestLevel():
"""Increments the per thread nest level of imports."""
# This is the top call to import (no nesting), init the per-thread nest level
# and names set.
if getattr(_import_local, 'nest_level', None) is None:
_import_local.nest_level = 0
if _import_local.nest_level == 0:
# Re-i... | [
"def",
"_IncrementNestLevel",
"(",
")",
":",
"# This is the top call to import (no nesting), init the per-thread nest level",
"# and names set.",
"if",
"getattr",
"(",
"_import_local",
",",
"'nest_level'",
",",
"None",
")",
"is",
"None",
":",
"_import_local",
".",
"nest_lev... | 36.384615 | 17.769231 |
def update_cdh_version(self, new_cdh_version):
"""
Manually set the CDH version.
@param new_cdh_version: New CDH version, e.g. 4.5.1
@return: An ApiCluster object
@since: API v6
"""
dic = self.to_json_dict()
dic['fullVersion'] = new_cdh_version
return self._put_cluster(dic) | [
"def",
"update_cdh_version",
"(",
"self",
",",
"new_cdh_version",
")",
":",
"dic",
"=",
"self",
".",
"to_json_dict",
"(",
")",
"dic",
"[",
"'fullVersion'",
"]",
"=",
"new_cdh_version",
"return",
"self",
".",
"_put_cluster",
"(",
"dic",
")"
] | 27.363636 | 10.454545 |
def to_satoshis(input_quantity, input_type):
''' convert to satoshis, no rounding '''
assert input_type in UNIT_CHOICES, input_type
# convert to satoshis
if input_type in ('btc', 'mbtc', 'bit'):
satoshis = float(input_quantity) * float(UNIT_MAPPINGS[input_type]['satoshis_per'])
elif input_t... | [
"def",
"to_satoshis",
"(",
"input_quantity",
",",
"input_type",
")",
":",
"assert",
"input_type",
"in",
"UNIT_CHOICES",
",",
"input_type",
"# convert to satoshis",
"if",
"input_type",
"in",
"(",
"'btc'",
",",
"'mbtc'",
",",
"'bit'",
")",
":",
"satoshis",
"=",
... | 35.307692 | 19.307692 |
def report_errors(audit, url):
"""
Args:
audit: results of `AxeCoreAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError`
"""
errors = AxeCoreAudit.get_errors(audit)
if errors["total"] > 0:
msg = u"URL... | [
"def",
"report_errors",
"(",
"audit",
",",
"url",
")",
":",
"errors",
"=",
"AxeCoreAudit",
".",
"get_errors",
"(",
"audit",
")",
"if",
"errors",
"[",
"\"total\"",
"]",
">",
"0",
":",
"msg",
"=",
"u\"URL '{}' has {} errors:\\n\\n{}\"",
".",
"format",
"(",
"... | 30 | 15.176471 |
def ndef(self):
"""An :class:`NDEF` object if found, otherwise :const:`None`."""
if self._ndef is None:
ndef = self.NDEF(self)
if ndef.has_changed:
self._ndef = ndef
return self._ndef | [
"def",
"ndef",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ndef",
"is",
"None",
":",
"ndef",
"=",
"self",
".",
"NDEF",
"(",
"self",
")",
"if",
"ndef",
".",
"has_changed",
":",
"self",
".",
"_ndef",
"=",
"ndef",
"return",
"self",
".",
"_ndef"
] | 34.428571 | 10.142857 |
def file_generator(self, sql, sql_args):
"""Generator for FileRecord
:param sql:
A SQL statement which must return rows describing files.
:param sql_args:
Any variables required to populate the query provided in 'sql'
:return:
A generator which produc... | [
"def",
"file_generator",
"(",
"self",
",",
"sql",
",",
"sql_args",
")",
":",
"self",
".",
"con",
".",
"execute",
"(",
"sql",
",",
"sql_args",
")",
"results",
"=",
"self",
".",
"con",
".",
"fetchall",
"(",
")",
"output",
"=",
"[",
"]",
"for",
"resul... | 45.081081 | 24.459459 |
def get_dependencies(self, version=None):
'''
Parameters
----------
version: str
string representing version number whose dependencies you are
looking up
'''
version = _process_version(self, version)
history = self.get_history()
f... | [
"def",
"get_dependencies",
"(",
"self",
",",
"version",
"=",
"None",
")",
":",
"version",
"=",
"_process_version",
"(",
"self",
",",
"version",
")",
"history",
"=",
"self",
".",
"get_history",
"(",
")",
"for",
"v",
"in",
"reversed",
"(",
"history",
")",
... | 29.058824 | 20.705882 |
def showConfig( self ):
"""
Show the config widget for the currently selected plugin.
"""
item = self.uiPluginTREE.currentItem()
if not isinstance(item, PluginItem):
return
plugin = item.plugin()
widget = self.findChild(QWidget, plugin.uniqueN... | [
"def",
"showConfig",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"uiPluginTREE",
".",
"currentItem",
"(",
")",
"if",
"not",
"isinstance",
"(",
"item",
",",
"PluginItem",
")",
":",
"return",
"plugin",
"=",
"item",
".",
"plugin",
"(",
")",
"widget",... | 33 | 14.647059 |
def _EStep(self, K, x, z_h1, pi_h, p_h):
"""
Description:
Internal function for computing the E-Step of the EMM algorithm.
"""
# E-Step:
for i in range(self.n):
for k in range(K):
denom_sum = 0
for k2 in range(K):
... | [
"def",
"_EStep",
"(",
"self",
",",
"K",
",",
"x",
",",
"z_h1",
",",
"pi_h",
",",
"p_h",
")",
":",
"# E-Step:",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n",
")",
":",
"for",
"k",
"in",
"range",
"(",
"K",
")",
":",
"denom_sum",
"=",
"0",
... | 38.833333 | 16.666667 |
def mock(self, slot, rpc_id, value):
"""Store a mock return value for an RPC
Args:
slot (SlotIdentifier): The slot we are mocking
rpc_id (int): The rpc we are mocking
value (int): The value that should be returned
when the RPC is called.
"""
... | [
"def",
"mock",
"(",
"self",
",",
"slot",
",",
"rpc_id",
",",
"value",
")",
":",
"address",
"=",
"slot",
".",
"address",
"if",
"address",
"not",
"in",
"self",
".",
"mock_rpcs",
":",
"self",
".",
"mock_rpcs",
"[",
"address",
"]",
"=",
"{",
"}",
"self... | 29.25 | 15.875 |
def run(self, data_service, project_file):
"""
Attach a remote file to activity with used relationship.
:param data_service: DataServiceApi: service used to attach relationship
:param project_file: ProjectFile: contains details about a file we will attach
"""
remote_path ... | [
"def",
"run",
"(",
"self",
",",
"data_service",
",",
"project_file",
")",
":",
"remote_path",
"=",
"project_file",
".",
"path",
"file_dict",
"=",
"data_service",
".",
"get_file",
"(",
"project_file",
".",
"id",
")",
".",
"json",
"(",
")",
"file_version_id",
... | 57.818182 | 23.272727 |
def dimension_values(self, dim, expanded=True, flat=True):
"""
The set of samples available along a particular dimension.
"""
dim_idx = self.get_dimension_index(dim)
if not expanded and dim_idx == 0:
return np.array(range(self.data.shape[1]))
elif not expanded... | [
"def",
"dimension_values",
"(",
"self",
",",
"dim",
",",
"expanded",
"=",
"True",
",",
"flat",
"=",
"True",
")",
":",
"dim_idx",
"=",
"self",
".",
"get_dimension_index",
"(",
"dim",
")",
"if",
"not",
"expanded",
"and",
"dim_idx",
"==",
"0",
":",
"retur... | 42.941176 | 13.529412 |
def _rm_units_from_var_name_single(var):
"""
NOTE: USE THIS FOR SINGLE CELLS ONLY
When parsing sheets, all variable names be exact matches when cross-referenceing the metadata and data sections
However, sometimes people like to put "age (years BP)" in one section, and "age" in the other. This causes pro... | [
"def",
"_rm_units_from_var_name_single",
"(",
"var",
")",
":",
"# Use the regex to match the cell",
"m",
"=",
"re",
".",
"match",
"(",
"re_var_w_units",
",",
"var",
")",
"# Should always get a match, but be careful anyways.",
"if",
"m",
":",
"# m.group(1): variableName",
... | 45.956522 | 22.130435 |
def user_stars(self, user_id, extra_query_params={}):
"""
client = BacklogClient("your_space_name", "your_api_key")
client.user_stars(5)
client.user_stars(5, {"count": 100, "order": "asc"})
"""
return self.do("GET", "users/{user_id}/stars",
url_para... | [
"def",
"user_stars",
"(",
"self",
",",
"user_id",
",",
"extra_query_params",
"=",
"{",
"}",
")",
":",
"return",
"self",
".",
"do",
"(",
"\"GET\"",
",",
"\"users/{user_id}/stars\"",
",",
"url_params",
"=",
"{",
"\"user_id\"",
":",
"user_id",
"}",
",",
"quer... | 43.555556 | 12.666667 |
def update_line(self, trace, xdata, ydata, side='left', draw=False,
update_limits=True):
""" update a single trace, for faster redraw """
x = self.conf.get_mpl_line(trace)
x.set_data(xdata, ydata)
datarange = [xdata.min(), xdata.max(), ydata.min(), ydata.max()]
... | [
"def",
"update_line",
"(",
"self",
",",
"trace",
",",
"xdata",
",",
"ydata",
",",
"side",
"=",
"'left'",
",",
"draw",
"=",
"False",
",",
"update_limits",
"=",
"True",
")",
":",
"x",
"=",
"self",
".",
"conf",
".",
"get_mpl_line",
"(",
"trace",
")",
... | 34.8125 | 16.3125 |
def location_from_dictionary(d):
"""
Builds a *Location* object out of a data dictionary. Only certain
properties of the dictionary are used: if these properties are not
found or cannot be read, an error is issued.
:param d: a data dictionary
:type d: dict
:returns: a *Location* instance
... | [
"def",
"location_from_dictionary",
"(",
"d",
")",
":",
"country",
"=",
"None",
"if",
"'sys'",
"in",
"d",
"and",
"'country'",
"in",
"d",
"[",
"'sys'",
"]",
":",
"country",
"=",
"d",
"[",
"'sys'",
"]",
"[",
"'country'",
"]",
"if",
"'city'",
"in",
"d",
... | 31.204545 | 17.022727 |
def run(self, N=100):
"""
Parameter
---------
N: int
number of particles
Returns
-------
wgts: Weights object
The importance weights (with attributes lw, W, and ESS)
X: ThetaParticles object
The N particles (wi... | [
"def",
"run",
"(",
"self",
",",
"N",
"=",
"100",
")",
":",
"th",
"=",
"self",
".",
"proposal",
".",
"rvs",
"(",
"size",
"=",
"N",
")",
"self",
".",
"X",
"=",
"ThetaParticles",
"(",
"theta",
"=",
"th",
",",
"lpost",
"=",
"None",
")",
"self",
"... | 30.434783 | 15.913043 |
def list_consumer_group(self, project, logstore):
""" List consumer group
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:return: ListConsumerGroupResponse
"""
resource = "/logstores... | [
"def",
"list_consumer_group",
"(",
"self",
",",
"project",
",",
"logstore",
")",
":",
"resource",
"=",
"\"/logstores/\"",
"+",
"logstore",
"+",
"\"/consumergroups\"",
"params",
"=",
"{",
"}",
"headers",
"=",
"{",
"}",
"(",
"resp",
",",
"header",
")",
"=",
... | 29.055556 | 19.611111 |
def push_0(self, build_record_id, **kwargs):
"""
Build record push results.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callb... | [
"def",
"push_0",
"(",
"self",
",",
"build_record_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"push_0_with_http_info",
"... | 40.769231 | 17.230769 |
def getRenderModelOriginalPath(self, pchRenderModelName, pchOriginalPath, unOriginalPathLen):
"""
Provides a render model path that will load the unskinned model if the model name provided has been replace by the user. If the model
hasn't been replaced the path value will still be a valid path t... | [
"def",
"getRenderModelOriginalPath",
"(",
"self",
",",
"pchRenderModelName",
",",
"pchOriginalPath",
",",
"unOriginalPathLen",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getRenderModelOriginalPath",
"peError",
"=",
"EVRRenderModelError",
"(",
")",
"resu... | 57.363636 | 36.636364 |
def GetRegion(region_name):
""" Converts region name string into boto Region object. """
regions = boto_ec2.regions()
region = None
valid_region_names = []
for r in regions:
valid_region_names.append(r.name)
if r.name == region_name:
region = r
break
if not region:
logging.info( ... | [
"def",
"GetRegion",
"(",
"region_name",
")",
":",
"regions",
"=",
"boto_ec2",
".",
"regions",
"(",
")",
"region",
"=",
"None",
"valid_region_names",
"=",
"[",
"]",
"for",
"r",
"in",
"regions",
":",
"valid_region_names",
".",
"append",
"(",
"r",
".",
"nam... | 30.8 | 18.4 |
def _do_save_as(self, filename):
"""Saves spectrum back to FITS file."""
if len(self.spectrum.x) < 2:
raise RuntimeError("Spectrum must have at least two points")
if os.path.isfile(filename):
os.unlink(filename) # PyFITS does not overwrite file
hdu = self.spect... | [
"def",
"_do_save_as",
"(",
"self",
",",
"filename",
")",
":",
"if",
"len",
"(",
"self",
".",
"spectrum",
".",
"x",
")",
"<",
"2",
":",
"raise",
"RuntimeError",
"(",
"\"Spectrum must have at least two points\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
... | 36.1 | 16 |
def file_md5(file_name):
'''
Generate an MD5 hash of the specified file.
@file_name - The file to hash.
Returns an MD5 hex digest string.
'''
md5 = hashlib.md5()
with open(file_name, 'rb') as f:
for chunk in iter(lambda: f.read(128 * md5.block_size), b''):
md5.update(c... | [
"def",
"file_md5",
"(",
"file_name",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"file_name",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"128",
"*",
... | 22.6 | 22.2 |
def _get_reference(self):
"""
Sets up references to important components. A reference is typically an
index or a list of indices that point to the corresponding elements
in a flattened array, which is how MuJoCo stores physical simulation data.
"""
super()._get_reference(... | [
"def",
"_get_reference",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_get_reference",
"(",
")",
"self",
".",
"hole_body_id",
"=",
"self",
".",
"sim",
".",
"model",
".",
"body_name2id",
"(",
"\"hole\"",
")",
"self",
".",
"cyl_body_id",
"=",
"self",
... | 49.333333 | 20.888889 |
def insert(self, iterable, data=None, weight=1.0):
"""Used to insert into he root node
Args
iterable(hashable): index or key used to identify
data(object): data to be paired with the key
"""
self.root.insert(iterable, index=0, data=data, weight=1.0) | [
"def",
"insert",
"(",
"self",
",",
"iterable",
",",
"data",
"=",
"None",
",",
"weight",
"=",
"1.0",
")",
":",
"self",
".",
"root",
".",
"insert",
"(",
"iterable",
",",
"index",
"=",
"0",
",",
"data",
"=",
"data",
",",
"weight",
"=",
"1.0",
")"
] | 37.375 | 17.625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.