text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def publishCommand(self, typeId, deviceId, commandId, msgFormat, data=None, qos=0, on_publish=None):
"""
Publish a command to a device
# Parameters
typeId (string) : The type of the device this command is to be published to
deviceId (string): The id of the device this command is... | [
"def",
"publishCommand",
"(",
"self",
",",
"typeId",
",",
"deviceId",
",",
"commandId",
",",
"msgFormat",
",",
"data",
"=",
"None",
",",
"qos",
"=",
"0",
",",
"on_publish",
"=",
"None",
")",
":",
"if",
"self",
".",
"_config",
".",
"isQuickstart",
"(",
... | 56.74 | 29.54 |
def iso_abundMulti(self, cyclist, stable=False, amass_range=None,
mass_range=None, ylim=[0,0], ref=-1,
decayed=False, include_title=False, title=None,
pdf=False, color_plot=True, grid=False,
point_set=1):
'''
Met... | [
"def",
"iso_abundMulti",
"(",
"self",
",",
"cyclist",
",",
"stable",
"=",
"False",
",",
"amass_range",
"=",
"None",
",",
"mass_range",
"=",
"None",
",",
"ylim",
"=",
"[",
"0",
",",
"0",
"]",
",",
"ref",
"=",
"-",
"1",
",",
"decayed",
"=",
"False",
... | 46.818182 | 20.090909 |
def QueryFields(r, what, fields=None):
"""
Retrieves available fields for a resource.
@type what: string
@param what: Resource name, one of L{constants.QR_VIA_RAPI}
@type fields: list of string
@param fields: Requested fields
@rtype: string
@return: job id
"""
query = {}
... | [
"def",
"QueryFields",
"(",
"r",
",",
"what",
",",
"fields",
"=",
"None",
")",
":",
"query",
"=",
"{",
"}",
"if",
"fields",
"is",
"not",
"None",
":",
"query",
"[",
"\"fields\"",
"]",
"=",
"\",\"",
".",
"join",
"(",
"fields",
")",
"return",
"r",
".... | 23.052632 | 19.789474 |
def _verified_frame_length(frame_length, content_type):
# type: (int, ContentType) -> int
"""Verify a frame length value for a message content type.
:param int frame_length: Frame length to verify
:param ContentType content_type: Message content type to verify against
:return: frame length
:rty... | [
"def",
"_verified_frame_length",
"(",
"frame_length",
",",
"content_type",
")",
":",
"# type: (int, ContentType) -> int",
"if",
"content_type",
"==",
"ContentType",
".",
"FRAMED_DATA",
"and",
"frame_length",
">",
"MAX_FRAME_SIZE",
":",
"raise",
"SerializationError",
"(",
... | 42.181818 | 24.954545 |
def label_for_lm(self, **kwargs):
"A special labelling method for language models."
self.__class__ = LMTextList
kwargs['label_cls'] = LMLabelList
return self.label_const(0, **kwargs) | [
"def",
"label_for_lm",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__class__",
"=",
"LMTextList",
"kwargs",
"[",
"'label_cls'",
"]",
"=",
"LMLabelList",
"return",
"self",
".",
"label_const",
"(",
"0",
",",
"*",
"*",
"kwargs",
")"
] | 42 | 6.8 |
def wtime_to_minutes(time_string):
''' wtime_to_minutes
Convert standard wallclock time string to minutes.
Args:
- Time_string in HH:MM:SS format
Returns:
(int) minutes
'''
hours, mins, seconds = time_string.split(':')
return int(hours) * 60 + int(mins) + 1 | [
"def",
"wtime_to_minutes",
"(",
"time_string",
")",
":",
"hours",
",",
"mins",
",",
"seconds",
"=",
"time_string",
".",
"split",
"(",
"':'",
")",
"return",
"int",
"(",
"hours",
")",
"*",
"60",
"+",
"int",
"(",
"mins",
")",
"+",
"1"
] | 20.857143 | 22.714286 |
def trade_signals_handler(self, signals):
'''
Process buy and sell signals from the simulation
'''
alloc = {}
if signals['buy'] or signals['sell']:
# Compute the optimal portfolio allocation,
# Using user defined function
try:
... | [
"def",
"trade_signals_handler",
"(",
"self",
",",
"signals",
")",
":",
"alloc",
"=",
"{",
"}",
"if",
"signals",
"[",
"'buy'",
"]",
"or",
"signals",
"[",
"'sell'",
"]",
":",
"# Compute the optimal portfolio allocation,",
"# Using user defined function",
"try",
":",... | 38.235294 | 15.647059 |
def p_delays_identifier(self, p):
'delays : DELAY identifier'
p[0] = DelayStatement(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_delays_identifier",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"DelayStatement",
"(",
"p",
"[",
"2",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"l... | 39.75 | 7.75 |
def _redundant_stack_variable_removal(self, function, data_graph):
"""
If an argument passed from the stack (i.e. dword ptr [ebp+4h]) is saved to a local variable on the stack at the
beginning of the function, and this local variable was never modified anywhere in this function, and no pointer
... | [
"def",
"_redundant_stack_variable_removal",
"(",
"self",
",",
"function",
",",
"data_graph",
")",
":",
"# check if there is any stack pointer being stored into any register other than esp",
"# basically check all consumers of stack pointers",
"stack_ptrs",
"=",
"[",
"]",
"sp_offset",... | 45.423423 | 27.495495 |
def create_signature(public_key, private_key, data, scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Return a (signature, scheme) tuple.
>>> requested_scheme = 'ecdsa-sha2-nistp256'
>>> public, private = generate_public_and_private(requested_scheme)
>>> data = b'The quick brown fox jumps over the lazy ... | [
"def",
"create_signature",
"(",
"public_key",
",",
"private_key",
",",
"data",
",",
"scheme",
"=",
"'ecdsa-sha2-nistp256'",
")",
":",
"# Do 'public_key' and 'private_key' have the correct format?",
"# This check will ensure that the arguments conform to",
"# 'securesystemslib.formats... | 35.1125 | 26.6375 |
def PlayerTypeEnum(ctx):
"""Player Type Enumeration."""
return Enum(
ctx,
absent=0,
closed=1,
human=2,
eliminated=3,
computer=4,
cyborg=5,
spectator=6
) | [
"def",
"PlayerTypeEnum",
"(",
"ctx",
")",
":",
"return",
"Enum",
"(",
"ctx",
",",
"absent",
"=",
"0",
",",
"closed",
"=",
"1",
",",
"human",
"=",
"2",
",",
"eliminated",
"=",
"3",
",",
"computer",
"=",
"4",
",",
"cyborg",
"=",
"5",
",",
"spectato... | 18.083333 | 21.416667 |
def AddCredentialOptions(self, argument_group):
"""Adds the credential options to the argument group.
The credential options are use to unlock encrypted volumes.
Args:
argument_group (argparse._ArgumentGroup): argparse argument group.
"""
argument_group.add_argument(
'--credential', ... | [
"def",
"AddCredentialOptions",
"(",
"self",
",",
"argument_group",
")",
":",
"argument_group",
".",
"add_argument",
"(",
"'--credential'",
",",
"action",
"=",
"'append'",
",",
"default",
"=",
"[",
"]",
",",
"type",
"=",
"str",
",",
"dest",
"=",
"'credentials... | 51.166667 | 25.277778 |
def read_md5(self, hex=False):
""" Calculate the md5 hash for this file.
hex - Return the digest as hex string.
This reads through the entire file.
"""
f = self.open('rb')
try:
m = hashlib.md5()
while True:
d = f.read(8192)
... | [
"def",
"read_md5",
"(",
"self",
",",
"hex",
"=",
"False",
")",
":",
"f",
"=",
"self",
".",
"open",
"(",
"'rb'",
")",
"try",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"while",
"True",
":",
"d",
"=",
"f",
".",
"read",
"(",
"8192",
")",
... | 24.047619 | 15.857143 |
def force_unicode(value):
"""
return an utf-8 unicode entry
"""
if not isinstance(value, (str, unicode)):
value = unicode(value)
if isinstance(value, str):
value = value.decode('utf-8')
return value | [
"def",
"force_unicode",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"value",
"=",
"unicode",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=... | 25.555556 | 8.222222 |
def update_dependent_files(self, prev_commands=[]):
""" Update the command's dependencies based on the evaluated input and
output of previous commands.
"""
for command in prev_commands:
for my_input in self.input_parts:
for their_output in command.output_parts... | [
"def",
"update_dependent_files",
"(",
"self",
",",
"prev_commands",
"=",
"[",
"]",
")",
":",
"for",
"command",
"in",
"prev_commands",
":",
"for",
"my_input",
"in",
"self",
".",
"input_parts",
":",
"for",
"their_output",
"in",
"command",
".",
"output_parts",
... | 47.333333 | 7.888889 |
def to_tuple(self):
"""Cast to tuple.
Returns
-------
tuple
The confusion table as a 4-tuple (tp, tn, fp, fn)
Example
-------
>>> ct = ConfusionTable(120, 60, 20, 30)
>>> ct.to_tuple()
(120, 60, 20, 30)
"""
return sel... | [
"def",
"to_tuple",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tp",
",",
"self",
".",
"_tn",
",",
"self",
".",
"_fp",
",",
"self",
".",
"_fn"
] | 21.25 | 21.25 |
def AdaBoost(L, K):
"""[Fig. 18.34]"""
def train(dataset):
examples, target = dataset.examples, dataset.target
N = len(examples)
epsilon = 1./(2*N)
w = [1./N] * N
h, z = [], []
for k in range(K):
h_k = L(dataset, w)
h.append(h_k)
... | [
"def",
"AdaBoost",
"(",
"L",
",",
"K",
")",
":",
"def",
"train",
"(",
"dataset",
")",
":",
"examples",
",",
"target",
"=",
"dataset",
".",
"examples",
",",
"dataset",
".",
"target",
"N",
"=",
"len",
"(",
"examples",
")",
"epsilon",
"=",
"1.",
"/",
... | 37.636364 | 14.909091 |
def arrays_overlap(a1, a2):
"""
Collection function: returns true if the arrays contain any common non-null element; if not,
returns null if both the arrays are non-empty and any of them contains a null element; returns
false otherwise.
>>> df = spark.createDataFrame([(["a", "b"], ["b", "c"]), (["a... | [
"def",
"arrays_overlap",
"(",
"a1",
",",
"a2",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"arrays_overlap",
"(",
"_to_java_column",
"(",
"a1",
")",
",",
"_to_java_colu... | 50.083333 | 27.75 |
def get_parameter_text(self, lower, maximum, upper, wrap=False):
""" Generates LaTeX appropriate text from marginalised parameter bounds.
Parameters
----------
lower : float
The lower bound on the parameter
maximum : float
The value of the parameter with ... | [
"def",
"get_parameter_text",
"(",
"self",
",",
"lower",
",",
"maximum",
",",
"upper",
",",
"wrap",
"=",
"False",
")",
":",
"if",
"lower",
"is",
"None",
"or",
"upper",
"is",
"None",
":",
"return",
"\"\"",
"upper_error",
"=",
"upper",
"-",
"maximum",
"lo... | 34.413333 | 15.76 |
def imread(path, grayscale=False, size=None, interpolate="bilinear",
channel_first=False, as_uint16=False, num_channels=-1):
"""
Read image by PIL module.
Notice that PIL only supports uint8 for RGB (not uint16).
So this imread function returns only uint8 array for both RGB and gray-scale.
... | [
"def",
"imread",
"(",
"path",
",",
"grayscale",
"=",
"False",
",",
"size",
"=",
"None",
",",
"interpolate",
"=",
"\"bilinear\"",
",",
"channel_first",
"=",
"False",
",",
"as_uint16",
"=",
"False",
",",
"num_channels",
"=",
"-",
"1",
")",
":",
"if",
"as... | 41.619048 | 26.142857 |
def css_load_time(self):
"""
Returns aggregate css load time for all pages.
"""
load_times = self.get_load_times('css')
return round(mean(load_times), self.decimal_precision) | [
"def",
"css_load_time",
"(",
"self",
")",
":",
"load_times",
"=",
"self",
".",
"get_load_times",
"(",
"'css'",
")",
"return",
"round",
"(",
"mean",
"(",
"load_times",
")",
",",
"self",
".",
"decimal_precision",
")"
] | 34.833333 | 9.833333 |
def update(self, auth_payload=values.unset):
"""
Update the ChallengeInstance
:param unicode auth_payload: Optional payload to verify the Challenge
:returns: Updated ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance
"""
... | [
"def",
"update",
"(",
"self",
",",
"auth_payload",
"=",
"values",
".",
"unset",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'AuthPayload'",
":",
"auth_payload",
",",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"update",
"(",
"'... | 30.24 | 18.72 |
def coerce_location(value, **options):
"""
Coerce a string to a :class:`Location` object.
:param value: The value to coerce (a string or :class:`Location` object).
:param options: Any keyword arguments are passed on to
:func:`~executor.contexts.create_context()`.
:returns: A :cl... | [
"def",
"coerce_location",
"(",
"value",
",",
"*",
"*",
"options",
")",
":",
"# Location objects pass through untouched.",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Location",
")",
":",
"# Other values are expected to be strings.",
"if",
"not",
"isinstance",
"(",
... | 39.259259 | 13.111111 |
def _initialize_parameters(state_machine, n_features):
""" Helper to create initial parameter vector with the correct shape. """
return np.zeros((state_machine.n_states
+ state_machine.n_transitions,
n_features)) | [
"def",
"_initialize_parameters",
"(",
"state_machine",
",",
"n_features",
")",
":",
"return",
"np",
".",
"zeros",
"(",
"(",
"state_machine",
".",
"n_states",
"+",
"state_machine",
".",
"n_transitions",
",",
"n_features",
")",
")"
] | 55 | 8 |
def cli(ctx, config, debug):
"""SnakTeX command line interface - write LaTeX faster through templating."""
ctx.obj['config'] = config
ctx.obj['engine'] = stex.SnakeTeX(config_file=config, debug=debug) | [
"def",
"cli",
"(",
"ctx",
",",
"config",
",",
"debug",
")",
":",
"ctx",
".",
"obj",
"[",
"'config'",
"]",
"=",
"config",
"ctx",
".",
"obj",
"[",
"'engine'",
"]",
"=",
"stex",
".",
"SnakeTeX",
"(",
"config_file",
"=",
"config",
",",
"debug",
"=",
... | 52.25 | 13 |
def clear_all(self):
""" clear all files that were to be injected """
self.injections.clear_all()
for config_file in CONFIG_FILES:
self.injections.clear(os.path.join("~", config_file)) | [
"def",
"clear_all",
"(",
"self",
")",
":",
"self",
".",
"injections",
".",
"clear_all",
"(",
")",
"for",
"config_file",
"in",
"CONFIG_FILES",
":",
"self",
".",
"injections",
".",
"clear",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"~\"",
",",
"config_... | 43.2 | 10 |
def roll(self):
""" Calculates the Roll of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z) | [
"def",
"roll",
"(",
"self",
")",
":",
"x",
",",
"y",
",",
"z",
",",
"w",
"=",
"self",
".",
"x",
",",
"self",
".",
"y",
",",
"self",
".",
"z",
",",
"self",
".",
"w",
"return",
"math",
".",
"atan2",
"(",
"2",
"*",
"y",
"*",
"w",
"-",
"2",... | 33.4 | 17.4 |
def _init_metadata(self):
"""stub"""
self._confused_learning_objectives_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'confusedLearningObjectiveIds'),
'element_labe... | [
"def",
"_init_metadata",
"(",
"self",
")",
":",
"self",
".",
"_confused_learning_objectives_metadata",
"=",
"{",
"'element_id'",
":",
"Id",
"(",
"self",
".",
"my_osid_object_form",
".",
"_authority",
",",
"self",
".",
"my_osid_object_form",
".",
"_namespace",
",",... | 39.137931 | 13.965517 |
def do_flip(dec=None, inc=None, di_block=None):
"""
This function returns the antipode (i.e. it flips) of directions.
The function can take dec and inc as seperate lists if they are of equal
length and explicitly specified or are the first two arguments. It will then
return a list of flipped decs a... | [
"def",
"do_flip",
"(",
"dec",
"=",
"None",
",",
"inc",
"=",
"None",
",",
"di_block",
"=",
"None",
")",
":",
"if",
"di_block",
"is",
"None",
":",
"dec_flip",
"=",
"[",
"]",
"inc_flip",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"le... | 32.267857 | 23.125 |
def get_credentials(scopes=None, secrets=None, storage=None, no_webserver=False):
"""Make OAuth 2.0 credentials for scopes from ``secrets`` and ``storage`` files.
Args:
scopes: scope URL(s) or ``'read'``, ``'write'`` (default: ``%r``)
secrets: location of secrets file (default: ``%r``)
... | [
"def",
"get_credentials",
"(",
"scopes",
"=",
"None",
",",
"secrets",
"=",
"None",
",",
"storage",
"=",
"None",
",",
"no_webserver",
"=",
"False",
")",
":",
"scopes",
"=",
"Scopes",
".",
"get",
"(",
"scopes",
")",
"if",
"secrets",
"is",
"None",
":",
... | 36.193548 | 23.83871 |
def get_location_metres(original_location, dNorth, dEast):
"""
Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the
specified `original_location`. The returned Location has the same `alt` value
as `original_location`.
The function is useful when yo... | [
"def",
"get_location_metres",
"(",
"original_location",
",",
"dNorth",
",",
"dEast",
")",
":",
"earth_radius",
"=",
"6378137.0",
"#Radius of \"spherical\" earth",
"#Coordinate offsets in radians",
"dLat",
"=",
"dNorth",
"/",
"earth_radius",
"dLon",
"=",
"dEast",
"/",
... | 51.428571 | 27.047619 |
def next(self):
''' Returns next image for same content_object and None if image is
the last. '''
try:
return self.__class__.objects.for_model(self.content_object,
self.content_type).\
filter(order__lt=se... | [
"def",
"next",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"__class__",
".",
"objects",
".",
"for_model",
"(",
"self",
".",
"content_object",
",",
"self",
".",
"content_type",
")",
".",
"filter",
"(",
"order__lt",
"=",
"self",
".",
"order... | 43.777778 | 26.666667 |
def visibleNodes(self):
"""
Returns a list of the visible nodes in the scene.
:return [<XNode>, ..]
"""
return filter(lambda x: isinstance(x, XNode) and x.isVisible(),
self.items()) | [
"def",
"visibleNodes",
"(",
"self",
")",
":",
"return",
"filter",
"(",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"XNode",
")",
"and",
"x",
".",
"isVisible",
"(",
")",
",",
"self",
".",
"items",
"(",
")",
")"
] | 31.125 | 13.625 |
def descend(self, remote, force=False):
""" Descend, possibly creating directories as needed """
remote_dirs = remote.split('/')
for directory in remote_dirs:
try:
self.conn.cwd(directory)
except Exception:
if force:
sel... | [
"def",
"descend",
"(",
"self",
",",
"remote",
",",
"force",
"=",
"False",
")",
":",
"remote_dirs",
"=",
"remote",
".",
"split",
"(",
"'/'",
")",
"for",
"directory",
"in",
"remote_dirs",
":",
"try",
":",
"self",
".",
"conn",
".",
"cwd",
"(",
"director... | 37 | 6.636364 |
def preview(df,preview_rows = 20):#,preview_max_cols = 0):
""" Returns a preview of a dataframe, which contains both header
rows and tail rows.
"""
if preview_rows < 4:
preview_rows = 4
preview_rows = min(preview_rows,df.shape[0])
outer = math.floor(preview_rows / 4)
return pd.concat... | [
"def",
"preview",
"(",
"df",
",",
"preview_rows",
"=",
"20",
")",
":",
"#,preview_max_cols = 0):",
"if",
"preview_rows",
"<",
"4",
":",
"preview_rows",
"=",
"4",
"preview_rows",
"=",
"min",
"(",
"preview_rows",
",",
"df",
".",
"shape",
"[",
"0",
"]",
")"... | 39.545455 | 9.818182 |
def _get_side1KerningGroups(self):
"""
Subclasses may override this method.
"""
found = {}
for name, contents in self.items():
if name.startswith("public.kern1."):
found[name] = contents
return found | [
"def",
"_get_side1KerningGroups",
"(",
"self",
")",
":",
"found",
"=",
"{",
"}",
"for",
"name",
",",
"contents",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"\"public.kern1.\"",
")",
":",
"found",
"[",
"name",
"]",
... | 29.666667 | 7.222222 |
def _insert_continuation_prompt(self, cursor):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_... | [
"def",
"_insert_continuation_prompt",
"(",
"self",
",",
"cursor",
")",
":",
"if",
"self",
".",
"_continuation_prompt_html",
"is",
"None",
":",
"self",
".",
"_insert_plain_text",
"(",
"cursor",
",",
"self",
".",
"_continuation_prompt",
")",
"else",
":",
"self",
... | 49.25 | 15.75 |
def desbloquear_sat(self):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
"""
resp = self._http_post('desbloquearsat')
conteudo = resp.json()
return RespostaSAT.desbloquear... | [
"def",
"desbloquear_sat",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_http_post",
"(",
"'desbloquearsat'",
")",
"conteudo",
"=",
"resp",
".",
"json",
"(",
")",
"return",
"RespostaSAT",
".",
"desbloquear_sat",
"(",
"conteudo",
".",
"get",
"(",
"'reto... | 37.888889 | 12.222222 |
def log(x, base=None):
"""
Calculate the log
Parameters
----------
x : float or array_like
Input values
base : int or float (Default: None)
Base of the log. If `None`, the natural logarithm
is computed (`base=np.e`).
Returns
-------
out : float or ndarray
... | [
"def",
"log",
"(",
"x",
",",
"base",
"=",
"None",
")",
":",
"if",
"base",
"==",
"10",
":",
"return",
"np",
".",
"log10",
"(",
"x",
")",
"elif",
"base",
"==",
"2",
":",
"return",
"np",
".",
"log2",
"(",
"x",
")",
"elif",
"base",
"is",
"None",
... | 21.24 | 17.48 |
def convert_separable_convolution(builder, layer, input_names, output_names, keras_layer):
"""
Convert separable convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.... | [
"def",
"convert_separable_convolution",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"_check_data_format",
"(",
"keras_layer",
")",
"# Get input and output names",
"input_name",
",",
"output_name",
"=",
"(",
"inp... | 32.556962 | 17.56962 |
def click_element(self, locator):
"""Click element identified by `locator`.
Key attributes for arbitrary elements are `index` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Clicking element '%s'." % locator)
self._element_find(... | [
"def",
"click_element",
"(",
"self",
",",
"locator",
")",
":",
"self",
".",
"_info",
"(",
"\"Clicking element '%s'.\"",
"%",
"locator",
")",
"self",
".",
"_element_find",
"(",
"locator",
",",
"True",
",",
"True",
")",
".",
"click",
"(",
")"
] | 42.625 | 16.125 |
def _is_dir(self, f):
'''Check if the given in-dap file is a directory'''
return self._tar.getmember(f).type == tarfile.DIRTYPE | [
"def",
"_is_dir",
"(",
"self",
",",
"f",
")",
":",
"return",
"self",
".",
"_tar",
".",
"getmember",
"(",
"f",
")",
".",
"type",
"==",
"tarfile",
".",
"DIRTYPE"
] | 47 | 19.666667 |
def remove_file(filepath):
''' Delete a file '''
try:
os.remove(os.path.abspath(os.path.expanduser(filepath)))
except OSError as e:
if e.errno != errno.ENOENT:
raise | [
"def",
"remove_file",
"(",
"filepath",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filepath",
")",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
"... | 31.857143 | 16.142857 |
def basic_range1(ranged_hparams):
"""A basic range of hyperparameters."""
rhp = ranged_hparams
rhp.set_discrete("batch_size", [1024, 2048, 4096])
rhp.set_discrete("num_hidden_layers", [1, 2, 3, 4, 5, 6])
rhp.set_discrete("hidden_size", [32, 64, 128, 256, 512], scale=rhp.LOG_SCALE)
rhp.set_discrete("kernel_h... | [
"def",
"basic_range1",
"(",
"ranged_hparams",
")",
":",
"rhp",
"=",
"ranged_hparams",
"rhp",
".",
"set_discrete",
"(",
"\"batch_size\"",
",",
"[",
"1024",
",",
"2048",
",",
"4096",
"]",
")",
"rhp",
".",
"set_discrete",
"(",
"\"num_hidden_layers\"",
",",
"[",... | 50 | 15.8 |
def geo(self):
"""
If the message media is geo, geo live or a venue,
this returns the :tl:`GeoPoint`.
"""
if isinstance(self.media, (types.MessageMediaGeo,
types.MessageMediaGeoLive,
types.MessageMediaVenue)):
... | [
"def",
"geo",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"media",
",",
"(",
"types",
".",
"MessageMediaGeo",
",",
"types",
".",
"MessageMediaGeoLive",
",",
"types",
".",
"MessageMediaVenue",
")",
")",
":",
"return",
"self",
".",
"media"... | 38.333333 | 12.111111 |
def remoteDataReceived(self, connection, data):
"""Some data was received from the remote end. Find the matching
protocol and replay it.
"""
proto = self.getLocalProtocol(connection)
proto.transport.write(data)
return {} | [
"def",
"remoteDataReceived",
"(",
"self",
",",
"connection",
",",
"data",
")",
":",
"proto",
"=",
"self",
".",
"getLocalProtocol",
"(",
"connection",
")",
"proto",
".",
"transport",
".",
"write",
"(",
"data",
")",
"return",
"{",
"}"
] | 32.75 | 11.625 |
def get_all_slots(cls):
"""Iterates through a class' (`cls`) mro to get all slots as a set."""
slots_iterator = (getattr(c, '__slots__', ()) for c in cls.__mro__)
# `__slots__` might only be a single string,
# so we need to put the strings into a tuple.
slots_converted = ((slots,) if isinstance(slot... | [
"def",
"get_all_slots",
"(",
"cls",
")",
":",
"slots_iterator",
"=",
"(",
"getattr",
"(",
"c",
",",
"'__slots__'",
",",
"(",
")",
")",
"for",
"c",
"in",
"cls",
".",
"__mro__",
")",
"# `__slots__` might only be a single string,",
"# so we need to put the strings in... | 47.2 | 15.4 |
def concat(invises, outvis, timesort=False):
"""Concatenate visibility measurement sets.
invises (list of str)
Paths to the input measurement sets
outvis (str)
Path to the output measurement set.
timesort (boolean)
If true, sort the output in time after concatenation.
Example::
... | [
"def",
"concat",
"(",
"invises",
",",
"outvis",
",",
"timesort",
"=",
"False",
")",
":",
"tb",
"=",
"util",
".",
"tools",
".",
"table",
"(",
")",
"ms",
"=",
"util",
".",
"tools",
".",
"ms",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",... | 29.068182 | 23.477273 |
def magic_file(filename):
""" Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first.
:param filename: path to file
:return: list of possible matches, highest confidence first
"""
head, foot = _file_details(filename)
if not head:
raise ValueError... | [
"def",
"magic_file",
"(",
"filename",
")",
":",
"head",
",",
"foot",
"=",
"_file_details",
"(",
"filename",
")",
"if",
"not",
"head",
":",
"raise",
"ValueError",
"(",
"\"Input was empty\"",
")",
"try",
":",
"info",
"=",
"_identify_all",
"(",
"head",
",",
... | 32.1875 | 16.1875 |
def get_vault_query_session(self, proxy):
"""Gets the OsidSession associated with the vault query service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.authorization.VaultQuerySession) - a
``VaultQuerySession``
raise: NullArgument - ``proxy`` is ``null``
... | [
"def",
"get_vault_query_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_vault_query",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"VaultQuerySession"... | 44.294118 | 14.470588 |
def COSTALD(T, Tc, Vc, omega):
r'''Calculate saturation liquid density using the COSTALD CSP method.
A popular and accurate estimation method. If possible, fit parameters are
used; alternatively critical properties work well.
The density of a liquid is given by:
.. math::
V_s=V^*V^{(0)}[1... | [
"def",
"COSTALD",
"(",
"T",
",",
"Tc",
",",
"Vc",
",",
"omega",
")",
":",
"Tr",
"=",
"T",
"/",
"Tc",
"V_delta",
"=",
"(",
"-",
"0.296123",
"+",
"0.386914",
"*",
"Tr",
"-",
"0.0427258",
"*",
"Tr",
"**",
"2",
"-",
"0.0480645",
"*",
"Tr",
"**",
... | 29.640625 | 24.765625 |
def version():
"""Get the version number without importing the mrcfile package."""
namespace = {}
with open(os.path.join('mrcfile', 'version.py')) as f:
exec(f.read(), namespace)
return namespace['__version__'] | [
"def",
"version",
"(",
")",
":",
"namespace",
"=",
"{",
"}",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'mrcfile'",
",",
"'version.py'",
")",
")",
"as",
"f",
":",
"exec",
"(",
"f",
".",
"read",
"(",
")",
",",
"namespace",
")",
"... | 38.166667 | 13 |
def list_to_pose(poselist, frame_id="", stamp=rospy.Time(0)):
"""
Convert a pose in the form of a list in PoseStamped
:param poselist: a pose on the form [[x, y, z], [x, y, z, w]]
:param frame_id: the frame_id on the outputed pose (facultative, empty otherwise)
:param stamp: the stamp of the outpute... | [
"def",
"list_to_pose",
"(",
"poselist",
",",
"frame_id",
"=",
"\"\"",
",",
"stamp",
"=",
"rospy",
".",
"Time",
"(",
"0",
")",
")",
":",
"p",
"=",
"PoseStamped",
"(",
")",
"p",
".",
"header",
".",
"frame_id",
"=",
"frame_id",
"p",
".",
"header",
"."... | 41.263158 | 12.631579 |
def nodePop(ctxt):
"""Pops the top element node from the node stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.nodePop(ctxt__o)
if ret is None:raise treeError('nodePop() failed')
return xmlNode(_obj=ret) | [
"def",
"nodePop",
"(",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"nodePop",
"(",
"ctxt__o",
")",
"if",
"ret",
"is",
"None",
":",
"raise"... | 36.428571 | 9.857143 |
def main(argv):
"""
Main function.
"""
if len(argv) != 2:
sys.stderr.write("\nYou can update a project in two steps.\n\n")
sys.stderr.write("Step 1: Update or create infrastructure files\n")
sys.stderr.write(" which will be needed to configure and build the project:\n")
... | [
"def",
"main",
"(",
"argv",
")",
":",
"if",
"len",
"(",
"argv",
")",
"!=",
"2",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\nYou can update a project in two steps.\\n\\n\"",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Step 1: Update or create infra... | 41.147541 | 17.868852 |
def p_definitions(self, p):
'definitions : definitions definition'
p[0] = p[1] + (p[2],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_definitions",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"2",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 34.5 | 8.5 |
def get_block_overview(block_representation, coin_symbol='btc', txn_limit=None,
txn_offset=None, api_key=None):
"""
Takes a block_representation, coin_symbol and txn_limit and gets an overview
of that block, including up to X transaction ids.
Note that block_representation may be the block numbe... | [
"def",
"get_block_overview",
"(",
"block_representation",
",",
"coin_symbol",
"=",
"'btc'",
",",
"txn_limit",
"=",
"None",
",",
"txn_offset",
"=",
"None",
",",
"api_key",
"=",
"None",
")",
":",
"assert",
"is_valid_coin_symbol",
"(",
"coin_symbol",
")",
"assert",... | 33.827586 | 19.344828 |
def get_view_menus(self, permission_name):
"""Returns the details of view_menus for a perm name"""
vm = set()
for perm_name, vm_name in self.get_all_permissions():
if perm_name == permission_name:
vm.add(vm_name)
return vm | [
"def",
"get_view_menus",
"(",
"self",
",",
"permission_name",
")",
":",
"vm",
"=",
"set",
"(",
")",
"for",
"perm_name",
",",
"vm_name",
"in",
"self",
".",
"get_all_permissions",
"(",
")",
":",
"if",
"perm_name",
"==",
"permission_name",
":",
"vm",
".",
"... | 39.428571 | 11.571429 |
def _mergeProteinEntries(proteinLists, protToPeps):
"""Returns a new "protToPeps" dictionary with entries merged that are
present in proteinLists.
NOTE:
The key of the merged entry is a tuple of the sorted protein keys. This
behaviour might change in the future; the tuple might be replaced ... | [
"def",
"_mergeProteinEntries",
"(",
"proteinLists",
",",
"protToPeps",
")",
":",
"mergedProtToPeps",
"=",
"dict",
"(",
"protToPeps",
")",
"for",
"proteins",
"in",
"proteinLists",
":",
"for",
"protein",
"in",
"proteins",
":",
"peptides",
"=",
"mergedProtToPeps",
... | 44.5 | 19.318182 |
def add_parameter(self, indicator_id, content, name='comment', ptype='string'):
"""
Add a a parameter to the IOC.
:param indicator_id: The unique Indicator/IndicatorItem id the parameter is associated with.
:param content: The value of the parameter.
:param name: The name of the... | [
"def",
"add_parameter",
"(",
"self",
",",
"indicator_id",
",",
"content",
",",
"name",
"=",
"'comment'",
",",
"ptype",
"=",
"'string'",
")",
":",
"parameters_node",
"=",
"self",
".",
"parameters",
"criteria_node",
"=",
"self",
".",
"top_level_indicator",
".",
... | 57.72 | 29.16 |
def accept(self, offer_ids, operations, filters=Filters()):
"""Accepts the given offers and performs a sequence of operations
on those accepted offers.
See Offer.Operation in mesos.proto for the set of available operations.
Available resources are aggregated when multiple offers are ... | [
"def",
"accept",
"(",
"self",
",",
"offer_ids",
",",
"operations",
",",
"filters",
"=",
"Filters",
"(",
")",
")",
":",
"logging",
".",
"info",
"(",
"'Accepts offers {}'",
".",
"format",
"(",
"offer_ids",
")",
")",
"return",
"self",
".",
"driver",
".",
... | 53.733333 | 24.666667 |
def _default_styles_xml(cls):
"""
Return a bytestream containing XML for a default styles part.
"""
path = os.path.join(
os.path.split(__file__)[0], '..', 'templates',
'default-styles.xml'
)
with open(path, 'rb') as f:
xml_bytes = f.rea... | [
"def",
"_default_styles_xml",
"(",
"cls",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"split",
"(",
"__file__",
")",
"[",
"0",
"]",
",",
"'..'",
",",
"'templates'",
",",
"'default-styles.xml'",
")",
"with",
"op... | 30.727273 | 12.545455 |
def get_genes_for_hgnc_id(self, hgnc_symbol):
""" obtain the ensembl gene IDs that correspond to a HGNC symbol
"""
headers = {"content-type": "application/json"}
# http://grch37.rest.ensembl.org/xrefs/symbol/homo_sapiens/KMT2A?content-type=application/json
... | [
"def",
"get_genes_for_hgnc_id",
"(",
"self",
",",
"hgnc_symbol",
")",
":",
"headers",
"=",
"{",
"\"content-type\"",
":",
"\"application/json\"",
"}",
"# http://grch37.rest.ensembl.org/xrefs/symbol/homo_sapiens/KMT2A?content-type=application/json",
"self",
".",
"attempt",
"=",
... | 33.833333 | 18.777778 |
def rtl_any(*vectorlist):
""" Hardware equivalent of python native "any".
: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' if any of the inputs
are '1' (i.e. it is a big ol' OR gate)
"""
... | [
"def",
"rtl_any",
"(",
"*",
"vectorlist",
")",
":",
"if",
"len",
"(",
"vectorlist",
")",
"<=",
"0",
":",
"raise",
"PyrtlError",
"(",
"'rtl_any requires at least 1 argument'",
")",
"converted_vectorlist",
"=",
"[",
"as_wires",
"(",
"v",
")",
"for",
"v",
"in",... | 43.266667 | 19.666667 |
def astype(array, y):
"""A functional form of the `astype` method.
Args:
array: The array or number to cast.
y: An array or number, as the input, whose type should be that of array.
Returns:
An array or number with the same dtype as `y`.
"""
if isinstance(y, autograd.core.Node):
return array... | [
"def",
"astype",
"(",
"array",
",",
"y",
")",
":",
"if",
"isinstance",
"(",
"y",
",",
"autograd",
".",
"core",
".",
"Node",
")",
":",
"return",
"array",
".",
"astype",
"(",
"numpy",
".",
"array",
"(",
"y",
".",
"value",
")",
".",
"dtype",
")",
... | 29.769231 | 17.230769 |
def _send_pub(self, load):
'''
Take a load and send it across the network to connected minions
'''
for transport, opts in iter_transport_opts(self.opts):
chan = salt.transport.server.PubServerChannel.factory(opts)
chan.publish(load) | [
"def",
"_send_pub",
"(",
"self",
",",
"load",
")",
":",
"for",
"transport",
",",
"opts",
"in",
"iter_transport_opts",
"(",
"self",
".",
"opts",
")",
":",
"chan",
"=",
"salt",
".",
"transport",
".",
"server",
".",
"PubServerChannel",
".",
"factory",
"(",
... | 40.285714 | 23.714286 |
def loadFullValue(self, seq, scope_attrs):
"""
Evaluate full value for async Console variables in a separate thread and send results to IDE side
:param seq: id of command
:param scope_attrs: a sequence of variables with their attributes separated by NEXT_VALUE_SEPARATOR
(i.e.: ob... | [
"def",
"loadFullValue",
"(",
"self",
",",
"seq",
",",
"scope_attrs",
")",
":",
"frame_variables",
"=",
"self",
".",
"get_namespace",
"(",
")",
"var_objects",
"=",
"[",
"]",
"vars",
"=",
"scope_attrs",
".",
"split",
"(",
"NEXT_VALUE_SEPARATOR",
")",
"for",
... | 43.821429 | 22.607143 |
def _cell_attribute_append(self, selection, tab, attributes):
"""Appends to cell_attributes with checks"""
cell_attributes = self.code_array.cell_attributes
thick_bottom_cells = []
thick_right_cells = []
# Does any cell in selection.cells have a larger bottom border?
... | [
"def",
"_cell_attribute_append",
"(",
"self",
",",
"selection",
",",
"tab",
",",
"attributes",
")",
":",
"cell_attributes",
"=",
"self",
".",
"code_array",
".",
"cell_attributes",
"thick_bottom_cells",
"=",
"[",
"]",
"thick_right_cells",
"=",
"[",
"]",
"# Does a... | 37.478261 | 18 |
def tcp_server(tcp_addr, settings):
"""Start up the tcp server, send the settings."""
family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET
sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
sock.bind(tcp_addr)
sock.listen(1)
logging.info("Waiting for connection on %s", tcp_ad... | [
"def",
"tcp_server",
"(",
"tcp_addr",
",",
"settings",
")",
":",
"family",
"=",
"socket",
".",
"AF_INET6",
"if",
"\":\"",
"in",
"tcp_addr",
".",
"ip",
"else",
"socket",
".",
"AF_INET",
"sock",
"=",
"socket",
".",
"socket",
"(",
"family",
",",
"socket",
... | 43.375 | 18.6875 |
def mxmt(m1, m2):
"""
Multiply a 3x3 matrix and the transpose of another 3x3 matrix.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmt_c.html
:param m1: 3x3 double precision matrix.
:type m1: 3x3-Element Array of floats
:param m2: 3x3 double precision matrix.
:type m2: 3x3-Eleme... | [
"def",
"mxmt",
"(",
"m1",
",",
"m2",
")",
":",
"m1",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"m1",
")",
"m2",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"m2",
")",
"mout",
"=",
"stypes",
".",
"emptyDoubleMatrix",
"(",
")",
"libspice",
".",
"mxmt_c... | 32 | 12.333333 |
def translate_js_with_compilation_plan(js, HEADER=DEFAULT_HEADER):
"""js has to be a javascript source code.
returns equivalent python code.
compile plans only work with the following restrictions:
- only enabled for oneliner expressions
- when there are comments in the js code string s... | [
"def",
"translate_js_with_compilation_plan",
"(",
"js",
",",
"HEADER",
"=",
"DEFAULT_HEADER",
")",
":",
"match_increaser_str",
",",
"match_increaser_num",
",",
"compilation_plan",
"=",
"get_compilation_plan",
"(",
"js",
")",
"cp_hash",
"=",
"hashlib",
".",
"md5",
"(... | 35.955556 | 23 |
def enrich(self, gmt):
"""use local mode
p = p-value computed using the Fisher exact test (Hypergeometric test)
Not implemented here:
combine score = log(p)·z
see here: http://amp.pharm.mssm.edu/Enrichr/help#background&q=4
columns contain:
... | [
"def",
"enrich",
"(",
"self",
",",
"gmt",
")",
":",
"if",
"isscalar",
"(",
"self",
".",
"background",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"background",
",",
"int",
")",
"or",
"self",
".",
"background",
".",
"isdigit",
"(",
")",
":",
"se... | 40.529412 | 20.372549 |
def __skeleton_base(graph, image, boundary_term, neighbourhood_function, spacing):
"""
Base of the skeleton for voxel based boundary term calculation.
This function holds the low level procedures shared by nearly all boundary terms.
@param graph An initialized graph.GCGraph object
@type gr... | [
"def",
"__skeleton_base",
"(",
"graph",
",",
"image",
",",
"boundary_term",
",",
"neighbourhood_function",
",",
"spacing",
")",
":",
"image",
"=",
"scipy",
".",
"asarray",
"(",
"image",
")",
"image",
"=",
"image",
".",
"astype",
"(",
"scipy",
".",
"float_"... | 54.470588 | 25.568627 |
def _best_match_syn(self, sx, sys, scope_map):
"""
The best match is determined by the highest magnitude weight
"""
SUBSTRING_WEIGHT = 0.2
WBEST = None
sbest = None
sxv = self._standardize_label(sx.val)
sxp = self._id_to_ontology(sx.class_id)
for s... | [
"def",
"_best_match_syn",
"(",
"self",
",",
"sx",
",",
"sys",
",",
"scope_map",
")",
":",
"SUBSTRING_WEIGHT",
"=",
"0.2",
"WBEST",
"=",
"None",
"sbest",
"=",
"None",
"sxv",
"=",
"self",
".",
"_standardize_label",
"(",
"sx",
".",
"val",
")",
"sxp",
"=",... | 44.965517 | 18.758621 |
def iter_extensions(extension):
""" Depth-first iterator over sub-extensions on `extension`.
"""
for _, ext in inspect.getmembers(extension, is_extension):
for item in iter_extensions(ext):
yield item
yield ext | [
"def",
"iter_extensions",
"(",
"extension",
")",
":",
"for",
"_",
",",
"ext",
"in",
"inspect",
".",
"getmembers",
"(",
"extension",
",",
"is_extension",
")",
":",
"for",
"item",
"in",
"iter_extensions",
"(",
"ext",
")",
":",
"yield",
"item",
"yield",
"ex... | 34.857143 | 10.428571 |
def get_function_url(self, function):
"""
Registers the given callable in the system (if it isn't already)
and returns the URL that can be used to invoke the given function from remote.
"""
assert self._opened, "RPC System is not opened"
logging.debug("get_function_url(%s... | [
"def",
"get_function_url",
"(",
"self",
",",
"function",
")",
":",
"assert",
"self",
".",
"_opened",
",",
"\"RPC System is not opened\"",
"logging",
".",
"debug",
"(",
"\"get_function_url(%s)\"",
"%",
"repr",
"(",
"function",
")",
")",
"if",
"function",
"in",
... | 47.230769 | 16.769231 |
def _resolve_dut_count(self):
"""
Calculates total amount of resources required and their types.
:return: Nothing, modifies _dut_count, _hardware_count and
_process_count
:raises: ValueError if total count does not match counts of types separately.
"""
self._dut_... | [
"def",
"_resolve_dut_count",
"(",
"self",
")",
":",
"self",
".",
"_dut_count",
"=",
"len",
"(",
"self",
".",
"_dut_requirements",
")",
"self",
".",
"_resolve_process_count",
"(",
")",
"self",
".",
"_resolve_hardware_count",
"(",
")",
"if",
"self",
".",
"_dut... | 44.538462 | 20.384615 |
def rows_from_csv(filename, predicate=None, encoding='utf-8'):
"""\
Returns an iterator over all rows in the provided CSV `filename`.
`filename`
Absolute path to a file to read the cables from.
The file must be a CSV file with the following columns:
<identifier>, <creation-date>, <r... | [
"def",
"rows_from_csv",
"(",
"filename",
",",
"predicate",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"pred",
"=",
"predicate",
"or",
"bool",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"row",
"in",
"_UnicodeR... | 55.625 | 29.5 |
def humanise_exception(exception):
"""Humanise a python exception by giving the class name and traceback.
The function will return a tuple with the exception name and the traceback.
:param exception: Exception object.
:type exception: Exception
:return: A tuple with the exception name and the tra... | [
"def",
"humanise_exception",
"(",
"exception",
")",
":",
"trace",
"=",
"''",
".",
"join",
"(",
"traceback",
".",
"format_tb",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
")",
"name",
"=",
"exception",
".",
"__class__",
".",
"__name__",
... | 33.428571 | 18.214286 |
def size(self):
""" -> #int number of keys in this instance """
return int(self._client.hget(self._bucket_key, self.key_prefix) or 0) | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"_client",
".",
"hget",
"(",
"self",
".",
"_bucket_key",
",",
"self",
".",
"key_prefix",
")",
"or",
"0",
")"
] | 49 | 20.666667 |
def update_assignment_override(self, id, course_id, assignment_id, assignment_override_due_at=None, assignment_override_lock_at=None, assignment_override_student_ids=None, assignment_override_title=None, assignment_override_unlock_at=None):
"""
Update an assignment override.
All current ove... | [
"def",
"update_assignment_override",
"(",
"self",
",",
"id",
",",
"course_id",
",",
"assignment_id",
",",
"assignment_override_due_at",
"=",
"None",
",",
"assignment_override_lock_at",
"=",
"None",
",",
"assignment_override_student_ids",
"=",
"None",
",",
"assignment_ov... | 51.685714 | 27.942857 |
def process_package(self, package_name):
"""
Build artifacts declared for the given package.
"""
metadata = super(ArtifactRegistry, self).process_package(package_name)
if metadata:
self.update_artifact_metadata(package_name, metadata) | [
"def",
"process_package",
"(",
"self",
",",
"package_name",
")",
":",
"metadata",
"=",
"super",
"(",
"ArtifactRegistry",
",",
"self",
")",
".",
"process_package",
"(",
"package_name",
")",
"if",
"metadata",
":",
"self",
".",
"update_artifact_metadata",
"(",
"p... | 35 | 17.25 |
def get_option_set_by_id(cls, option_set_id, **kwargs):
"""Find OptionSet
Return single instance of OptionSet by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_option_set_by_id(op... | [
"def",
"get_option_set_by_id",
"(",
"cls",
",",
"option_set_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_option_set_by_i... | 42.238095 | 20.428571 |
def __create_paleo_col(l, col_count):
"""
Receive split list from separate_data_vars, and turn it into a dictionary for that column
:param list l:
:param int col_count:
:return dict:
"""
# Format: what, material, error, units, seasonality, archive, detail, method,... | [
"def",
"__create_paleo_col",
"(",
"l",
",",
"col_count",
")",
":",
"# Format: what, material, error, units, seasonality, archive, detail, method,",
"# C or N for Character or Numeric data, direction of relation to climate (positive or negative)",
"d",
"=",
"OrderedDict",
"(",
")",
"d",... | 47.08 | 22.04 |
def WriteClientStartupInfo(self, client_id, new_si):
"""Handle a startup event."""
drift = rdfvalue.Duration("5m")
if data_store.RelationalDBEnabled():
current_si = data_store.REL_DB.ReadClientStartupInfo(client_id)
# We write the updated record if the client_info has any changes
# or th... | [
"def",
"WriteClientStartupInfo",
"(",
"self",
",",
"client_id",
",",
"new_si",
")",
":",
"drift",
"=",
"rdfvalue",
".",
"Duration",
"(",
"\"5m\"",
")",
"if",
"data_store",
".",
"RelationalDBEnabled",
"(",
")",
":",
"current_si",
"=",
"data_store",
".",
"REL_... | 39 | 21.155556 |
def rebind_string(self, keysym, newstring):
"""Change the translation of KEYSYM to NEWSTRING.
If NEWSTRING is None, remove old translation if any.
"""
if newstring is None:
try:
del self.keysym_translations[keysym]
except KeyError:
... | [
"def",
"rebind_string",
"(",
"self",
",",
"keysym",
",",
"newstring",
")",
":",
"if",
"newstring",
"is",
"None",
":",
"try",
":",
"del",
"self",
".",
"keysym_translations",
"[",
"keysym",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"self",
".",
... | 35 | 13.181818 |
def get_printable(iterable):
"""
Get printable characters from the specified string.
Note that str.isprintable() is not available in Python 2.
"""
if iterable:
return ''.join(i for i in iterable if i in string.printable)
return '' | [
"def",
"get_printable",
"(",
"iterable",
")",
":",
"if",
"iterable",
":",
"return",
"''",
".",
"join",
"(",
"i",
"for",
"i",
"in",
"iterable",
"if",
"i",
"in",
"string",
".",
"printable",
")",
"return",
"''"
] | 31.875 | 15.875 |
def create(self, data, **kwargs):
"""Create a new object.
Args:
data (dict): parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
RESTObject: a new instance of the... | [
"def",
"create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_missing_create_attrs",
"(",
"data",
")",
"files",
"=",
"{",
"}",
"# We get the attributes that need some special transformation",
"types",
"=",
"getattr",
"(",
"se... | 40.341463 | 21.463415 |
def whois_emails(self, emails):
"""Calls WHOIS Email end point
Args:
emails: An enumerable of string Emails
Returns:
A dict of {email: domain_result}
"""
api_name = 'opendns-whois-emails'
fmt_url_path = u'whois/emails/{0}'
return self._mul... | [
"def",
"whois_emails",
"(",
"self",
",",
"emails",
")",
":",
"api_name",
"=",
"'opendns-whois-emails'",
"fmt_url_path",
"=",
"u'whois/emails/{0}'",
"return",
"self",
".",
"_multi_get",
"(",
"api_name",
",",
"fmt_url_path",
",",
"emails",
")"
] | 31.636364 | 12.636364 |
def untlpy2highwirepy(untl_elements, **kwargs):
"""Convert a UNTL Python object to a highwire Python object."""
highwire_list = []
title = None
publisher = None
creation = None
escape = kwargs.get('escape', False)
for element in untl_elements.children:
# If the UNTL element should be... | [
"def",
"untlpy2highwirepy",
"(",
"untl_elements",
",",
"*",
"*",
"kwargs",
")",
":",
"highwire_list",
"=",
"[",
"]",
"title",
"=",
"None",
"publisher",
"=",
"None",
"creation",
"=",
"None",
"escape",
"=",
"kwargs",
".",
"get",
"(",
"'escape'",
",",
"Fals... | 45.813953 | 13.790698 |
def _splitstrip(string, sep=","):
"""return a list of stripped string by splitting the string given as
argument on `sep` (',' by default). Empty string are discarded.
>>> _splitstrip('a, b, c , 4,,')
['a', 'b', 'c', '4']
>>> _splitstrip('a')
['a']
>>> _splitstrip('a,\nb,\nc,')
['a', ... | [
"def",
"_splitstrip",
"(",
"string",
",",
"sep",
"=",
"\",\"",
")",
":",
"return",
"[",
"word",
".",
"strip",
"(",
")",
"for",
"word",
"in",
"string",
".",
"split",
"(",
"sep",
")",
"if",
"word",
".",
"strip",
"(",
")",
"]"
] | 30.809524 | 19.714286 |
def to_query(self):
"""
Returns a json-serializable representation.
"""
query = {}
for field_instance in self.fields:
query.update(field_instance.to_query())
return query | [
"def",
"to_query",
"(",
"self",
")",
":",
"query",
"=",
"{",
"}",
"for",
"field_instance",
"in",
"self",
".",
"fields",
":",
"query",
".",
"update",
"(",
"field_instance",
".",
"to_query",
"(",
")",
")",
"return",
"query"
] | 22.3 | 16.7 |
def read(string):
"""
Read a graph from a XML document and return it. Nodes and edges specified in the input will
be added to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: graph
@return: Graph
"""
dom = parseS... | [
"def",
"read",
"(",
"string",
")",
":",
"dom",
"=",
"parseString",
"(",
"string",
")",
"if",
"dom",
".",
"getElementsByTagName",
"(",
"\"graph\"",
")",
":",
"G",
"=",
"graph",
"(",
")",
"elif",
"dom",
".",
"getElementsByTagName",
"(",
"\"digraph\"",
")",... | 41.428571 | 23.809524 |
def StringEscape(self, string, match, **_):
"""Escape backslashes found inside a string quote.
Backslashes followed by anything other than ['"rnbt] will just be included
in the string.
Args:
string: The string that matched.
match: The match object (m.group(1) is the escaped code)
"""... | [
"def",
"StringEscape",
"(",
"self",
",",
"string",
",",
"match",
",",
"*",
"*",
"_",
")",
":",
"precondition",
".",
"AssertType",
"(",
"string",
",",
"Text",
")",
"if",
"match",
".",
"group",
"(",
"1",
")",
"in",
"\"'\\\"rnbt\"",
":",
"self",
".",
... | 32 | 17.666667 |
def str2dict(dotted_str, value=None, separator='.'):
""" Convert dotted string to dict splitting by :separator: """
dict_ = {}
parts = dotted_str.split(separator)
d, prev = dict_, None
for part in parts:
prev = d
d = d.setdefault(part, {})
else:
if value is not None:
... | [
"def",
"str2dict",
"(",
"dotted_str",
",",
"value",
"=",
"None",
",",
"separator",
"=",
"'.'",
")",
":",
"dict_",
"=",
"{",
"}",
"parts",
"=",
"dotted_str",
".",
"split",
"(",
"separator",
")",
"d",
",",
"prev",
"=",
"dict_",
",",
"None",
"for",
"p... | 29.333333 | 14.833333 |
def volume(self):
"""
Mesh volume - will throw a VTK error/warning if not a closed surface
Returns
-------
volume : float
Total volume of the mesh.
"""
mprop = vtk.vtkMassProperties()
mprop.SetInputData(self.tri_filter())
return mprop... | [
"def",
"volume",
"(",
"self",
")",
":",
"mprop",
"=",
"vtk",
".",
"vtkMassProperties",
"(",
")",
"mprop",
".",
"SetInputData",
"(",
"self",
".",
"tri_filter",
"(",
")",
")",
"return",
"mprop",
".",
"GetVolume",
"(",
")"
] | 24.615385 | 17.230769 |
def check_input(self, token):
"""
Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token
"""
if isinstance(token.payload, Evaluation):
return None
if isinstance(token.payload, Cluste... | [
"def",
"check_input",
"(",
"self",
",",
"token",
")",
":",
"if",
"isinstance",
"(",
"token",
".",
"payload",
",",
"Evaluation",
")",
":",
"return",
"None",
"if",
"isinstance",
"(",
"token",
".",
"payload",
",",
"ClusterEvaluation",
")",
":",
"return",
"N... | 36.142857 | 16.714286 |
def show_clock_output_clock_time_current_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_clock = ET.Element("show_clock")
config = show_clock
output = ET.SubElement(show_clock, "output")
clock_time = ET.SubElement(output, "clock... | [
"def",
"show_clock_output_clock_time_current_time",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_clock",
"=",
"ET",
".",
"Element",
"(",
"\"show_clock\"",
")",
"config",
"=",
"show_clock",
... | 40.461538 | 13.461538 |
def to_ruby(self):
''' Convert one MeCabToken into HTML '''
if self.need_ruby():
surface = self.surface
reading = self.reading_hira()
return '<ruby><rb>{sur}</rb><rt>{read}</rt></ruby>'.format(sur=surface, read=reading)
elif self.is_eos:
return ''
... | [
"def",
"to_ruby",
"(",
"self",
")",
":",
"if",
"self",
".",
"need_ruby",
"(",
")",
":",
"surface",
"=",
"self",
".",
"surface",
"reading",
"=",
"self",
".",
"reading_hira",
"(",
")",
"return",
"'<ruby><rb>{sur}</rb><rt>{read}</rt></ruby>'",
".",
"format",
"(... | 35.6 | 17.6 |
def add_nodes(self, nodes, nesting=1):
"""
Adds nodes and edges for generating the graph showing the relationship
between modules and submodules listed in nodes.
"""
hopNodes = set() # nodes in this hop
hopEdges = [] # edges in this hop
# get nodes and edges ... | [
"def",
"add_nodes",
"(",
"self",
",",
"nodes",
",",
"nesting",
"=",
"1",
")",
":",
"hopNodes",
"=",
"set",
"(",
")",
"# nodes in this hop",
"hopEdges",
"=",
"[",
"]",
"# edges in this hop",
"# get nodes and edges for this hop",
"for",
"i",
",",
"n",
"in",
"z... | 45.695652 | 10.652174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.