text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def add_local_lb(self, price_item_id, datacenter):
"""Creates a local load balancer in the specified data center.
:param int price_item_id: The price item ID for the load balancer
:param string datacenter: The datacenter to create the loadbalancer in
:returns: A dictionary containing th... | [
"def",
"add_local_lb",
"(",
"self",
",",
"price_item_id",
",",
"datacenter",
")",
":",
"product_order",
"=",
"{",
"'complexType'",
":",
"'SoftLayer_Container_Product_Order_Network_'",
"'LoadBalancer'",
",",
"'quantity'",
":",
"1",
",",
"'packageId'",
":",
"0",
",",
... | 41.764706 | 19.705882 |
def install(name, link, path, priority):
'''
Install symbolic links determining default commands
CLI Example:
.. code-block:: bash
salt '*' alternatives.install editor /usr/bin/editor /usr/bin/emacs23 50
'''
cmd = [_get_cmd(), '--install', link, name, path, six.text_type(priority)]
... | [
"def",
"install",
"(",
"name",
",",
"link",
",",
"path",
",",
"priority",
")",
":",
"cmd",
"=",
"[",
"_get_cmd",
"(",
")",
",",
"'--install'",
",",
"link",
",",
"name",
",",
"path",
",",
"six",
".",
"text_type",
"(",
"priority",
")",
"]",
"out",
... | 31.133333 | 25 |
def on_add_state_machine_after(self, observable, return_value, args):
""" This method specifies what happens when a state machine is added to the state machine manager
:param observable: the state machine manager
:param return_value: the new state machine
:param args:
:return:
... | [
"def",
"on_add_state_machine_after",
"(",
"self",
",",
"observable",
",",
"return_value",
",",
"args",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Execution status observer register new state machine sm_id: {}\"",
".",
"format",
"(",
"args",
"[",
"1",
"]",... | 55.555556 | 21.333333 |
def dump_all_handler_stats(self):
''' Return handler capture statistics
Return a dictionary of capture handler statistics of the form:
.. code-block:: none
[{
'name': The handler's name,
'reads': The number of packet reads this handler has received... | [
"def",
"dump_all_handler_stats",
"(",
"self",
")",
":",
"stats",
"=",
"[",
"]",
"for",
"h",
"in",
"self",
".",
"capture_handlers",
":",
"now",
"=",
"calendar",
".",
"timegm",
"(",
"time",
".",
"gmtime",
"(",
")",
")",
"rot_time",
"=",
"calendar",
".",
... | 31.363636 | 24.636364 |
def ls(ctx, name, list_instances):
"""List ELB instances"""
session = create_session(ctx.obj['AWS_PROFILE_NAME'])
client = session.client('elb')
inst = {'LoadBalancerDescriptions': []}
if name == '*':
inst = client.describe_load_balancers()
else:
try:
inst = client.d... | [
"def",
"ls",
"(",
"ctx",
",",
"name",
",",
"list_instances",
")",
":",
"session",
"=",
"create_session",
"(",
"ctx",
".",
"obj",
"[",
"'AWS_PROFILE_NAME'",
"]",
")",
"client",
"=",
"session",
".",
"client",
"(",
"'elb'",
")",
"inst",
"=",
"{",
"'LoadBa... | 36.043478 | 16.478261 |
def _find_closest_trackpointaA(self,Or,Op,Oz,ar,ap,az,interp=True):
"""
NAME:
_find_closest_trackpointaA
PURPOSE:
find the closest point on the stream track to a given point in
frequency-angle coordinates
INPUT:
Or,Op,Oz,ar,ap,az - phase-space ... | [
"def",
"_find_closest_trackpointaA",
"(",
"self",
",",
"Or",
",",
"Op",
",",
"Oz",
",",
"ar",
",",
"ap",
",",
"az",
",",
"interp",
"=",
"True",
")",
":",
"#Calculate angle offset along the stream parallel to the stream track,",
"# finding first the angle among a few wra... | 47.84375 | 23.84375 |
def after(self, idx):
"""Return datetime of oldest existing data record whose
datetime is >= idx.
Might not even be in the same year! If no such record exists,
return None."""
if not isinstance(idx, datetime):
raise TypeError("'%s' is not %s" % (idx, datetime))
... | [
"def",
"after",
"(",
"self",
",",
"idx",
")",
":",
"if",
"not",
"isinstance",
"(",
"idx",
",",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"\"'%s' is not %s\"",
"%",
"(",
"idx",
",",
"datetime",
")",
")",
"day",
"=",
"max",
"(",
"idx",
".",
"d... | 42.588235 | 14.470588 |
def gpg_decrypt(cfg, gpg_config=None):
"""Decrypt GPG objects in configuration.
Args:
cfg (dict): configuration dictionary
gpg_config (dict): gpg configuration
dict of arguments for gpg including:
homedir, binary, and keyring (require all if any)
example:... | [
"def",
"gpg_decrypt",
"(",
"cfg",
",",
"gpg_config",
"=",
"None",
")",
":",
"def",
"decrypt",
"(",
"obj",
")",
":",
"\"\"\"Decrypt the object.\n\n It is an inner function because we must first verify that gpg\n is ready. If we did them in the same function we would end ... | 36.968085 | 20.053191 |
def cached(fun):
"""
memoizing decorator for linkage functions.
Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because,
the way this is coded (interchangingly using sets and frozensets) is true
for this specific case. For other cases that is not necessarily guaranteed.
"""
... | [
"def",
"cached",
"(",
"fun",
")",
":",
"_cache",
"=",
"{",
"}",
"@",
"wraps",
"(",
"fun",
")",
"def",
"newfun",
"(",
"a",
",",
"b",
",",
"distance_function",
")",
":",
"frozen_a",
"=",
"frozenset",
"(",
"a",
")",
"frozen_b",
"=",
"frozenset",
"(",
... | 32.35 | 19.15 |
def check_palette(palette):
"""
Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay;
raises an exception otherwise.
"""
# None is the default and is allowed.
if palette is None:
return None
p = list(palette)
if not (0 ... | [
"def",
"check_palette",
"(",
"palette",
")",
":",
"# None is the default and is allowed.",
"if",
"palette",
"is",
"None",
":",
"return",
"None",
"p",
"=",
"list",
"(",
"palette",
")",
"if",
"not",
"(",
"0",
"<",
"len",
"(",
"p",
")",
"<=",
"256",
")",
... | 33.65625 | 15.09375 |
def check_game_end(self):
'''Checks for the game's win/lose conditions and 'alters' the
game state to reflect the condition found. If the game has not
been won or lost then it just returns the game state
unaltered.'''
if self.player in self.crashes.union(self.robots):
... | [
"def",
"check_game_end",
"(",
"self",
")",
":",
"if",
"self",
".",
"player",
"in",
"self",
".",
"crashes",
".",
"union",
"(",
"self",
".",
"robots",
")",
":",
"return",
"self",
".",
"end_game",
"(",
"'You Died!'",
")",
"elif",
"not",
"self",
".",
"ro... | 38.083333 | 19.583333 |
def print_stmt(self, print_loc, stmt):
"""
(2.6-2.7)
print_stmt: 'print' ( [ test (',' test)* [','] ] |
'>>' test [ (',' test)+ [','] ] )
"""
stmt.keyword_loc = print_loc
if stmt.loc is None:
stmt.loc = print_loc
else:
... | [
"def",
"print_stmt",
"(",
"self",
",",
"print_loc",
",",
"stmt",
")",
":",
"stmt",
".",
"keyword_loc",
"=",
"print_loc",
"if",
"stmt",
".",
"loc",
"is",
"None",
":",
"stmt",
".",
"loc",
"=",
"print_loc",
"else",
":",
"stmt",
".",
"loc",
"=",
"print_l... | 31.083333 | 12.083333 |
def _isinstance(expr, classname):
"""Check whether `expr` is an instance of the class with name
`classname`
This is like the builtin `isinstance`, but it take the `classname` a
string, instead of the class directly. Useful for when we don't want to
import the class for which we ... | [
"def",
"_isinstance",
"(",
"expr",
",",
"classname",
")",
":",
"for",
"cls",
"in",
"type",
"(",
"expr",
")",
".",
"__mro__",
":",
"if",
"cls",
".",
"__name__",
"==",
"classname",
":",
"return",
"True",
"return",
"False"
] | 41.357143 | 19.071429 |
def _merge_default_values(self):
"""Merge default values with resource data."""
values = self._get_default_values()
for key, value in values.items():
if not self.data.get(key):
self.data[key] = value | [
"def",
"_merge_default_values",
"(",
"self",
")",
":",
"values",
"=",
"self",
".",
"_get_default_values",
"(",
")",
"for",
"key",
",",
"value",
"in",
"values",
".",
"items",
"(",
")",
":",
"if",
"not",
"self",
".",
"data",
".",
"get",
"(",
"key",
")"... | 41 | 2.666667 |
def humanize_error(data, validation_error, max_sub_error_length=MAX_VALIDATION_ERROR_ITEM_LENGTH):
""" Provide a more helpful + complete validation error message than that provided automatically
Invalid and MultipleInvalid do not include the offending value in error messages,
and MultipleInvalid.__str__ onl... | [
"def",
"humanize_error",
"(",
"data",
",",
"validation_error",
",",
"max_sub_error_length",
"=",
"MAX_VALIDATION_ERROR_ITEM_LENGTH",
")",
":",
"if",
"isinstance",
"(",
"validation_error",
",",
"MultipleInvalid",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"sorted... | 58.866667 | 26.333333 |
def taxon_table(self):
"""
Returns the .tests list of taxa as a pandas dataframe.
By auto-generating this table from tests it means that
the table itself cannot be modified unless it is returned
and saved.
"""
if self.tests:
keys = sorted(self.test... | [
"def",
"taxon_table",
"(",
"self",
")",
":",
"if",
"self",
".",
"tests",
":",
"keys",
"=",
"sorted",
"(",
"self",
".",
"tests",
"[",
"0",
"]",
".",
"keys",
"(",
")",
")",
"if",
"isinstance",
"(",
"self",
".",
"tests",
",",
"list",
")",
":",
"ld... | 36.611111 | 15.611111 |
def from_ashrae_revised_clear_sky(cls, location, monthly_tau_beam,
monthly_tau_diffuse, timestep=1,
is_leap_year=False):
"""Create a wea object representing an ASHRAE Revised Clear Sky ("Tau Model")
ASHRAE Revised Clear Skies a... | [
"def",
"from_ashrae_revised_clear_sky",
"(",
"cls",
",",
"location",
",",
"monthly_tau_beam",
",",
"monthly_tau_diffuse",
",",
"timestep",
"=",
"1",
",",
"is_leap_year",
"=",
"False",
")",
":",
"# extract metadata",
"metadata",
"=",
"{",
"'source'",
":",
"location... | 52.55102 | 24.55102 |
def fromgtf(args):
"""
%prog fromgtf gtffile
Convert gtf to gff file. In gtf, the "transcript_id" will convert to "ID=",
the "transcript_id" in exon/CDS feature will be converted to "Parent=".
"""
p = OptionParser(fromgtf.__doc__)
p.add_option("--transcript_id", default="transcript_id",
... | [
"def",
"fromgtf",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"fromgtf",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--transcript_id\"",
",",
"default",
"=",
"\"transcript_id\"",
",",
"help",
"=",
"\"Field name for transcript [default: %default]... | 33.517857 | 17.767857 |
def imagecapture(self, window_name=None, x=0, y=0,
width=None, height=None):
"""
Captures screenshot of the whole desktop or given window
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type win... | [
"def",
"imagecapture",
"(",
"self",
",",
"window_name",
"=",
"None",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"if",
"x",
"or",
"y",
"or",
"(",
"width",
"and",
"width",
"!=",
"-",
... | 41.02439 | 18.097561 |
def _get_int64(data, position, dummy0, dummy1, dummy2):
"""Decode a BSON int64 to bson.int64.Int64."""
end = position + 8
return Int64(_UNPACK_LONG(data[position:end])[0]), end | [
"def",
"_get_int64",
"(",
"data",
",",
"position",
",",
"dummy0",
",",
"dummy1",
",",
"dummy2",
")",
":",
"end",
"=",
"position",
"+",
"8",
"return",
"Int64",
"(",
"_UNPACK_LONG",
"(",
"data",
"[",
"position",
":",
"end",
"]",
")",
"[",
"0",
"]",
"... | 46.25 | 12.75 |
def iter_transform(filename, key):
"""Generate encrypted file with given key.
This generator function reads the file
in chunks and encrypts them using AES-CTR,
with the specified key.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt ... | [
"def",
"iter_transform",
"(",
"filename",
",",
"key",
")",
":",
"# We are not specifying the IV here.",
"aes",
"=",
"AES",
".",
"new",
"(",
"key",
",",
"AES",
".",
"MODE_CTR",
",",
"counter",
"=",
"Counter",
".",
"new",
"(",
"128",
")",
")",
"with",
"ope... | 33.2 | 14.75 |
def Run(self, args):
"""Delete all the GRR temp files in path.
If path is a directory, look in the top level for filenames beginning with
Client.tempfile_prefix, and delete them.
If path is a regular file and starts with Client.tempfile_prefix delete it.
Args:
args: pathspec pointing to dir... | [
"def",
"Run",
"(",
"self",
",",
"args",
")",
":",
"allowed_temp_dirs",
"=",
"[",
"GetTempDirForRoot",
"(",
"root",
")",
"for",
"root",
"in",
"config",
".",
"CONFIG",
"[",
"\"Client.tempdir_roots\"",
"]",
"]",
"if",
"args",
".",
"path",
":",
"# Normalize th... | 34.6 | 22.76 |
def get_hex(self):
"""
Returns a HEX String, separated by spaces every byte
"""
s = binascii.hexlify(self.get_raw()).decode("ascii")
return " ".join(s[i:i + 2] for i in range(0, len(s), 2)) | [
"def",
"get_hex",
"(",
"self",
")",
":",
"s",
"=",
"binascii",
".",
"hexlify",
"(",
"self",
".",
"get_raw",
"(",
")",
")",
".",
"decode",
"(",
"\"ascii\"",
")",
"return",
"\" \"",
".",
"join",
"(",
"s",
"[",
"i",
":",
"i",
"+",
"2",
"]",
"for",... | 32 | 18 |
def simplified_solis(apparent_elevation, aod700=0.1, precipitable_water=1.,
pressure=101325., dni_extra=1364.):
"""
Calculate the clear sky GHI, DNI, and DHI according to the
simplified Solis model [1]_.
Reference [1]_ describes the accuracy of the model as being 15, 20,
and 18... | [
"def",
"simplified_solis",
"(",
"apparent_elevation",
",",
"aod700",
"=",
"0.1",
",",
"precipitable_water",
"=",
"1.",
",",
"pressure",
"=",
"101325.",
",",
"dni_extra",
"=",
"1364.",
")",
":",
"p",
"=",
"pressure",
"w",
"=",
"precipitable_water",
"# algorithm... | 31.674157 | 22.325843 |
def arg_list(self, ending_char=TokenTypes.RPAREN):
"""
arglist : expression, arglist
arglist : expression
arglist :
"""
args = []
while not self.cur_token.type == ending_char:
args.append(self.expression())
if self.cur_token.type =... | [
"def",
"arg_list",
"(",
"self",
",",
"ending_char",
"=",
"TokenTypes",
".",
"RPAREN",
")",
":",
"args",
"=",
"[",
"]",
"while",
"not",
"self",
".",
"cur_token",
".",
"type",
"==",
"ending_char",
":",
"args",
".",
"append",
"(",
"self",
".",
"expression... | 30.076923 | 11.923077 |
def lazy_gettext(self, singular, plural=None, n=1, locale=None) -> LazyProxy:
"""
Lazy get text
:param singular:
:param plural:
:param n:
:param locale:
:return:
"""
return LazyProxy(self.gettext, singular, plural, n, locale) | [
"def",
"lazy_gettext",
"(",
"self",
",",
"singular",
",",
"plural",
"=",
"None",
",",
"n",
"=",
"1",
",",
"locale",
"=",
"None",
")",
"->",
"LazyProxy",
":",
"return",
"LazyProxy",
"(",
"self",
".",
"gettext",
",",
"singular",
",",
"plural",
",",
"n"... | 26.181818 | 20.181818 |
def unlock(thing_name, key, session=None):
"""Unlock a thing
"""
return _request('get', '/unlock/{0}'.format(thing_name), params={'key': key}, session=session) | [
"def",
"unlock",
"(",
"thing_name",
",",
"key",
",",
"session",
"=",
"None",
")",
":",
"return",
"_request",
"(",
"'get'",
",",
"'/unlock/{0}'",
".",
"format",
"(",
"thing_name",
")",
",",
"params",
"=",
"{",
"'key'",
":",
"key",
"}",
",",
"session",
... | 42 | 15 |
def exec_(controller, cmd, *args):
"""Executes a subprocess in the foreground, blocking until returned."""
controller.logger.info("Executing: {0} {1}", cmd, " ".join(args))
try:
subprocess.check_call([cmd] + list(args))
except (OSError, subprocess.CalledProcessError) as err:
controller.... | [
"def",
"exec_",
"(",
"controller",
",",
"cmd",
",",
"*",
"args",
")",
":",
"controller",
".",
"logger",
".",
"info",
"(",
"\"Executing: {0} {1}\"",
",",
"cmd",
",",
"\" \"",
".",
"join",
"(",
"args",
")",
")",
"try",
":",
"subprocess",
".",
"check_call... | 45.5 | 20.625 |
def extern_call(self, context_handle, func, args_ptr, args_len):
"""Given a callable, call it."""
c = self._ffi.from_handle(context_handle)
runnable = c.from_value(func[0])
args = tuple(c.from_value(arg[0]) for arg in self._ffi.unpack(args_ptr, args_len))
return self.call(c, runnable, args) | [
"def",
"extern_call",
"(",
"self",
",",
"context_handle",
",",
"func",
",",
"args_ptr",
",",
"args_len",
")",
":",
"c",
"=",
"self",
".",
"_ffi",
".",
"from_handle",
"(",
"context_handle",
")",
"runnable",
"=",
"c",
".",
"from_value",
"(",
"func",
"[",
... | 51 | 13.333333 |
def iglob(pathname):
"""
Return an iterator which yields the same values as glob() without actually
storing them all simultaneously.
Parameters
----------
pathname : string
A glob pattern string which will be used for finding files
Returns
-------
iterator
An iterat... | [
"def",
"iglob",
"(",
"pathname",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"pathname",
")",
"basename_pattern",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"pathname",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os... | 28.636364 | 20 |
def add_existence(self, rev):
"""Add existence constraint for the field.
This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present.
Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent.
Of course, if the constraint is already abo... | [
"def",
"add_existence",
"(",
"self",
",",
"rev",
")",
":",
"if",
"len",
"(",
"self",
".",
"constraints",
")",
"==",
"1",
"and",
"(",
"# both 'exists' and strict equality don't require the extra clause",
"self",
".",
"constraints",
"[",
"0",
"]",
".",
"op",
"."... | 48.235294 | 25 |
def calc_qpout_v1(self):
"""Calculate the ARMA results for the different response functions.
Required derived parameter:
|Nmb|
Required flux sequences:
|QMA|
|QAR|
Calculated flux sequence:
|QPOut|
Examples:
Initialize an arma model with three different response ... | [
"def",
"calc_qpout_v1",
"(",
"self",
")",
":",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"for",
"idx",
"in",
"range",
"(",
"der",
".",
"nmb",
")",
... | 26.368421 | 18.842105 |
def columnInfo(self):
"""
display metadata about the table, size, number of rows, columns and their data type
"""
code = "proc contents data=" + self.libref + '.' + self.table + ' ' + self._dsopts() + ";ods select Variables;run;"
if self.sas.nosub:
print(code)
... | [
"def",
"columnInfo",
"(",
"self",
")",
":",
"code",
"=",
"\"proc contents data=\"",
"+",
"self",
".",
"libref",
"+",
"'.'",
"+",
"self",
".",
"table",
"+",
"' '",
"+",
"self",
".",
"_dsopts",
"(",
")",
"+",
"\";ods select Variables;run;\"",
"if",
"self",
... | 35.8125 | 21.3125 |
def get_connection_by_id(self, id):
'''Search for a connection on this port by its ID.'''
with self._mutex:
for conn in self.connections:
if conn.id == id:
return conn
return None | [
"def",
"get_connection_by_id",
"(",
"self",
",",
"id",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"conn",
"in",
"self",
".",
"connections",
":",
"if",
"conn",
".",
"id",
"==",
"id",
":",
"return",
"conn",
"return",
"None"
] | 35.571429 | 10.714286 |
def cache_response(self, request, response, body=None):
"""
Algorithm for caching requests.
This assumes a requests Response object.
"""
# From httplib2: Don't cache 206's since we aren't going to
# handle byte range requests
if response.status not... | [
"def",
"cache_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"body",
"=",
"None",
")",
":",
"# From httplib2: Don't cache 206's since we aren't going to",
"# handle byte range requests",
"if",
"response",
".",
"status",
"not",
"in",
"[",
"2... | 37.241379 | 18.862069 |
def enableBranch(self, enabled):
""" Sets the enabled member to True or False for a node and all it's children
"""
self.enabled = enabled
for child in self.childItems:
child.enableBranch(enabled) | [
"def",
"enableBranch",
"(",
"self",
",",
"enabled",
")",
":",
"self",
".",
"enabled",
"=",
"enabled",
"for",
"child",
"in",
"self",
".",
"childItems",
":",
"child",
".",
"enableBranch",
"(",
"enabled",
")"
] | 39 | 3.666667 |
def mass_loss_loon05(L,Teff):
'''
mass loss rate van Loon etal (2005).
Parameters
----------
L : float
L in L_sun.
Teff : float
Teff in K.
Returns
-------
Mdot
Mdot in Msun/yr
Notes
-----
ref: van Loon etal 2005, A&A 438, 273
... | [
"def",
"mass_loss_loon05",
"(",
"L",
",",
"Teff",
")",
":",
"Mdot",
"=",
"-",
"5.65",
"+",
"np",
".",
"log10",
"(",
"old_div",
"(",
"L",
",",
"10.",
"**",
"4",
")",
")",
"-",
"6.3",
"*",
"np",
".",
"log10",
"(",
"old_div",
"(",
"Teff",
",",
"... | 16.916667 | 26.583333 |
def check_for_update(self, force=True, download=False):
""" Returns a :class:`~plexapi.base.Release` object containing release info.
Parameters:
force (bool): Force server to check for new releases
download (bool): Download if a update is available.
"""
... | [
"def",
"check_for_update",
"(",
"self",
",",
"force",
"=",
"True",
",",
"download",
"=",
"False",
")",
":",
"part",
"=",
"'/updater/check?download=%s'",
"%",
"(",
"1",
"if",
"download",
"else",
"0",
")",
"if",
"force",
":",
"self",
".",
"query",
"(",
"... | 42.615385 | 17.769231 |
def __get_WIOD_env_extension(root_path, year, ll_co, para):
""" Parses the wiod environmental extension
Extension can either be given as original .zip files or as extracted
data in a folder with the same name as the corresponding zip file (with-
out the extension).
This function is based on the st... | [
"def",
"__get_WIOD_env_extension",
"(",
"root_path",
",",
"year",
",",
"ll_co",
",",
"para",
")",
":",
"ll_root_content",
"=",
"[",
"ff",
"for",
"ff",
"in",
"os",
".",
"listdir",
"(",
"root_path",
")",
"if",
"ff",
".",
"startswith",
"(",
"para",
"[",
"... | 34.924528 | 20.484277 |
def border(self, ax, wcs, **kw_mpl_pathpatch):
"""
Draws the MOC border(s) on a matplotlib axis.
This performs the projection of the sky coordinates defining the perimeter of the MOC to the pixel image coordinate system.
You are able to specify various styling kwargs for `matplotlib.pat... | [
"def",
"border",
"(",
"self",
",",
"ax",
",",
"wcs",
",",
"*",
"*",
"kw_mpl_pathpatch",
")",
":",
"border",
".",
"border",
"(",
"self",
",",
"ax",
",",
"wcs",
",",
"*",
"*",
"kw_mpl_pathpatch",
")"
] | 44.767442 | 20.348837 |
def make_federation_entity(config, eid='', httpcli=None, verify_ssl=True):
"""
Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based
on given configuration.
:param config: Federation entity configuration
:param eid: Entity ID
:param httpcli: A http client instance to use whe... | [
"def",
"make_federation_entity",
"(",
"config",
",",
"eid",
"=",
"''",
",",
"httpcli",
"=",
"None",
",",
"verify_ssl",
"=",
"True",
")",
":",
"args",
"=",
"{",
"}",
"if",
"not",
"eid",
":",
"try",
":",
"eid",
"=",
"config",
"[",
"'entity_id'",
"]",
... | 33.307692 | 20.046154 |
def timelimit(timeout):
"""borrowed from web.py"""
def _1(function):
def _2(*args, **kw):
class Dispatch(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
self.error = None
... | [
"def",
"timelimit",
"(",
"timeout",
")",
":",
"def",
"_1",
"(",
"function",
")",
":",
"def",
"_2",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"class",
"Dispatch",
"(",
"threading",
".",
"Thread",
")",
":",
"def",
"__init__",
"(",
"self",
")... | 29.5 | 14.5 |
def geocode(self, query, **kwargs):
"""
Given a string to search for, return the results from OpenCage's Geocoder.
:param string query: String to search for
:returns: Dict results
:raises InvalidInputError: if the query string is not a unicode string
:raises RateLimitEx... | [
"def",
"geocode",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY2",
":",
"# py3 doesn't have unicode() function, and instead we check the text_type later",
"try",
":",
"query",
"=",
"unicode",
"(",
"query",
")",
"except",
"Un... | 35.6 | 25.56 |
def set_progress_brackets(self, start, end):
"""Set brackets to set around a progress bar."""
self.sep_start = start
self.sep_end = end | [
"def",
"set_progress_brackets",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"self",
".",
"sep_start",
"=",
"start",
"self",
".",
"sep_end",
"=",
"end"
] | 39 | 7 |
def handle_start_stateful_processing(self, start_msg):
"""Called when we receive StartInstanceStatefulProcessing message
:param start_msg: StartInstanceStatefulProcessing type
"""
Log.info("Received start stateful processing for %s" % start_msg.checkpoint_id)
self.is_stateful_started = True
self... | [
"def",
"handle_start_stateful_processing",
"(",
"self",
",",
"start_msg",
")",
":",
"Log",
".",
"info",
"(",
"\"Received start stateful processing for %s\"",
"%",
"start_msg",
".",
"checkpoint_id",
")",
"self",
".",
"is_stateful_started",
"=",
"True",
"self",
".",
"... | 49 | 11.857143 |
def add_filter(self, filter_key, operator, value):
""" Adds a filter given a key, operator, and value"""
filter_key = self._metadata_map.get(filter_key, filter_key)
self.filters.append({'filter': filter_key, 'operator': operator, 'value': value}) | [
"def",
"add_filter",
"(",
"self",
",",
"filter_key",
",",
"operator",
",",
"value",
")",
":",
"filter_key",
"=",
"self",
".",
"_metadata_map",
".",
"get",
"(",
"filter_key",
",",
"filter_key",
")",
"self",
".",
"filters",
".",
"append",
"(",
"{",
"'filte... | 66.75 | 21.5 |
def get(self, record_id):
"""
Retrieves a record by its id
>>> record = airtable.get('recwPQIfs4wKPyc9D')
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Record
"""
record_url = self.record_url(record... | [
"def",
"get",
"(",
"self",
",",
"record_id",
")",
":",
"record_url",
"=",
"self",
".",
"record_url",
"(",
"record_id",
")",
"return",
"self",
".",
"_get",
"(",
"record_url",
")"
] | 24.928571 | 15.928571 |
def get_logger(level=None, name=None, filename=None):
"""
Create a logger or return the current one if already instantiated.
Parameters
----------
level : int
one of the logger.level constants
name : string
name of the logger
filename : string
name of the log file
... | [
"def",
"get_logger",
"(",
"level",
"=",
"None",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"level",
"is",
"None",
":",
"level",
"=",
"settings",
".",
"log_level",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"settings",
... | 29.659574 | 21.319149 |
def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=None):
"""Calculates the block_struct array for the outp... | [
"def",
"_calculate_block_structure",
"(",
"self",
",",
"inequalities",
",",
"equalities",
",",
"momentinequalities",
",",
"momentequalities",
",",
"extramomentmatrix",
",",
"removeequalities",
",",
"block_struct",
"=",
"None",
")",
":",
"if",
"block_struct",
"is",
"... | 48.11828 | 15.709677 |
def _normalize(x, cmin=None, cmax=None, clip=True):
"""Normalize an array from the range [cmin, cmax] to [0,1],
with optional clipping."""
if not isinstance(x, np.ndarray):
x = np.array(x)
if cmin is None:
cmin = x.min()
if cmax is None:
cmax = x.max()
if cmin == cmax:
... | [
"def",
"_normalize",
"(",
"x",
",",
"cmin",
"=",
"None",
",",
"cmax",
"=",
"None",
",",
"clip",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"if"... | 29.823529 | 13.176471 |
def next_token(self, tokenum, value, scol):
"""Determine what to do with the next token"""
# Make self.current reflect these values
self.current.set(tokenum, value, scol)
# Determine indent_type based on this token
if self.current.tokenum == INDENT and self.current.value:
... | [
"def",
"next_token",
"(",
"self",
",",
"tokenum",
",",
"value",
",",
"scol",
")",
":",
"# Make self.current reflect these values",
"self",
".",
"current",
".",
"set",
"(",
"tokenum",
",",
"value",
",",
"scol",
")",
"# Determine indent_type based on this token",
"i... | 38.488889 | 19.777778 |
def _load_paths(self, paths, depth=0):
'''
Goes recursevly through the given list of paths
in order to find and pass all preset files to ```_load_preset()```
'''
if depth > self.MAX_DEPTH:
return
for path in paths:
try:
# avoid em... | [
"def",
"_load_paths",
"(",
"self",
",",
"paths",
",",
"depth",
"=",
"0",
")",
":",
"if",
"depth",
">",
"self",
".",
"MAX_DEPTH",
":",
"return",
"for",
"path",
"in",
"paths",
":",
"try",
":",
"# avoid empty string",
"if",
"not",
"path",
":",
"continue",... | 40.307692 | 20.666667 |
def get_or_create_iexact(self, **kwargs):
"""
Case insensitive title version of ``get_or_create``. Also
allows for multiple existing results.
"""
lookup = dict(**kwargs)
try:
lookup["title__iexact"] = lookup.pop("title")
except KeyError:
pa... | [
"def",
"get_or_create_iexact",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"lookup",
"=",
"dict",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"lookup",
"[",
"\"title__iexact\"",
"]",
"=",
"lookup",
".",
"pop",
"(",
"\"title\"",
")",
"except",
"KeyErr... | 31.928571 | 13.071429 |
def color(self, x, y, paint_method):
"""
:param paint_method: 'point' or 'replace' or 'floodfill' or
'filltoborder' or 'reset'
:type paint_method: str or pgmagick.PaintMethod
"""
paint_method = _convert_paintmethod(paint_method)
color = pgmagi... | [
"def",
"color",
"(",
"self",
",",
"x",
",",
"y",
",",
"paint_method",
")",
":",
"paint_method",
"=",
"_convert_paintmethod",
"(",
"paint_method",
")",
"color",
"=",
"pgmagick",
".",
"DrawableColor",
"(",
"x",
",",
"y",
",",
"paint_method",
")",
"self",
"... | 42.444444 | 11.333333 |
def audiosamples(language, word, key = ''):
''' Returns a list of URLs to suitable audiosamples for a given word. '''
from lltk.audiosamples import forvo, google
urls = []
urls += forvo(language, word, key)
urls += google(language, word)
return urls | [
"def",
"audiosamples",
"(",
"language",
",",
"word",
",",
"key",
"=",
"''",
")",
":",
"from",
"lltk",
".",
"audiosamples",
"import",
"forvo",
",",
"google",
"urls",
"=",
"[",
"]",
"urls",
"+=",
"forvo",
"(",
"language",
",",
"word",
",",
"key",
")",
... | 27.666667 | 21.444444 |
def parse(cls, fptr, offset, length):
"""Parse JPX free box.
Parameters
----------
f : file
Open file object.
offset : int
Start position of box in bytes.
length : int
Length of the box in bytes.
Returns
-------
... | [
"def",
"parse",
"(",
"cls",
",",
"fptr",
",",
"offset",
",",
"length",
")",
":",
"# Must seek to end of box.",
"nbytes",
"=",
"offset",
"+",
"length",
"-",
"fptr",
".",
"tell",
"(",
")",
"fptr",
".",
"read",
"(",
"nbytes",
")",
"return",
"cls",
"(",
... | 24.952381 | 15.285714 |
def save(self, filename, format=None):
"""
Saves the SArray to file.
The saved SArray will be in a directory named with the `targetfile`
parameter.
Parameters
----------
filename : string
A local path or a remote URL. If format is 'text', it will be... | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"format",
"=",
"None",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"if",
"format",
"is",
"None",
":",
"if",
"filename",
".",
"endswith",
"(",
"(",
"'.csv'",
",",
"'.csv.gz'",
... | 41.820513 | 21.512821 |
def _do_put(self):
"""
HTTP Put Request
"""
return requests.put(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token)) | [
"def",
"_do_put",
"(",
"self",
")",
":",
"return",
"requests",
".",
"put",
"(",
"self",
".",
"_url",
",",
"data",
"=",
"self",
".",
"_data",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"auth",
"=",
"(",
"self",
".",
"_email",
",",
"self",
... | 35.8 | 22.6 |
def _check_pool_attr(self, attr, req_attr=None):
""" Check pool attributes.
"""
if req_attr is None:
req_attr = []
# check attribute names
self._check_attr(attr, req_attr, _pool_attrs)
# validate IPv4 prefix length
if attr.get('ipv4_default_prefix_l... | [
"def",
"_check_pool_attr",
"(",
"self",
",",
"attr",
",",
"req_attr",
"=",
"None",
")",
":",
"if",
"req_attr",
"is",
"None",
":",
"req_attr",
"=",
"[",
"]",
"# check attribute names",
"self",
".",
"_check_attr",
"(",
"attr",
",",
"req_attr",
",",
"_pool_at... | 38.30303 | 20.818182 |
def get(self, name_or_klass):
"""
Gets a mode by name (or class)
:param name_or_klass: The name or the class of the mode to get
:type name_or_klass: str or type
:rtype: pyqode.core.api.Mode
"""
if not isinstance(name_or_klass, str):
name_or_klass = na... | [
"def",
"get",
"(",
"self",
",",
"name_or_klass",
")",
":",
"if",
"not",
"isinstance",
"(",
"name_or_klass",
",",
"str",
")",
":",
"name_or_klass",
"=",
"name_or_klass",
".",
"__name__",
"return",
"self",
".",
"_modes",
"[",
"name_or_klass",
"]"
] | 33.818182 | 9.454545 |
def process(self, user, timestamp, data=None):
"""
Processes a user event.
:Parameters:
user : `hashable`
A hashable value to identify a user (`int` or `str` are OK)
timestamp : :class:`mwtypes.Timestamp`
The timestamp of the event
... | [
"def",
"process",
"(",
"self",
",",
"user",
",",
"timestamp",
",",
"data",
"=",
"None",
")",
":",
"event",
"=",
"Event",
"(",
"user",
",",
"mwtypes",
".",
"Timestamp",
"(",
"timestamp",
")",
",",
"self",
".",
"event_i",
",",
"data",
")",
"self",
".... | 33.65625 | 18.90625 |
def add_or_return_host(self, host):
"""
Returns a tuple (host, new), where ``host`` is a Host
instance, and ``new`` is a bool indicating whether
the host was newly added.
"""
with self._hosts_lock:
try:
return self._hosts[host.endpoint], False
... | [
"def",
"add_or_return_host",
"(",
"self",
",",
"host",
")",
":",
"with",
"self",
".",
"_hosts_lock",
":",
"try",
":",
"return",
"self",
".",
"_hosts",
"[",
"host",
".",
"endpoint",
"]",
",",
"False",
"except",
"KeyError",
":",
"self",
".",
"_hosts",
"[... | 35.083333 | 10.75 |
def get_br(self):
"""Returns the bottom right border of the cell"""
cell_below = CellBorders(self.cell_attributes,
*self.cell.get_below_key_rect())
return cell_below.get_r() | [
"def",
"get_br",
"(",
"self",
")",
":",
"cell_below",
"=",
"CellBorders",
"(",
"self",
".",
"cell_attributes",
",",
"*",
"self",
".",
"cell",
".",
"get_below_key_rect",
"(",
")",
")",
"return",
"cell_below",
".",
"get_r",
"(",
")"
] | 37.666667 | 18.166667 |
def apply_correlation(self, sites, imt, residuals, stddev_intra):
"""
Apply correlation to randomly sampled residuals.
See Parent function
"""
# stddev_intra is repeated if it is only 1 value for all the residuals
if stddev_intra.shape[0] == 1:
stddev_intra =... | [
"def",
"apply_correlation",
"(",
"self",
",",
"sites",
",",
"imt",
",",
"residuals",
",",
"stddev_intra",
")",
":",
"# stddev_intra is repeated if it is only 1 value for all the residuals",
"if",
"stddev_intra",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
":",
"stddev_i... | 43.8 | 19.290909 |
def create(quiet, name, base_uri, symlink_path):
"""Create a proto dataset."""
_validate_name(name)
admin_metadata = dtoolcore.generate_admin_metadata(name)
parsed_base_uri = dtoolcore.utils.generous_parse_uri(base_uri)
if parsed_base_uri.scheme == "symlink":
if symlink_path is None:
... | [
"def",
"create",
"(",
"quiet",
",",
"name",
",",
"base_uri",
",",
"symlink_path",
")",
":",
"_validate_name",
"(",
"name",
")",
"admin_metadata",
"=",
"dtoolcore",
".",
"generate_admin_metadata",
"(",
"name",
")",
"parsed_base_uri",
"=",
"dtoolcore",
".",
"uti... | 36.338028 | 22.859155 |
def decodeEntities(self, len, what, end, end2, end3):
"""This function is deprecated, we now always process entities
content through xmlStringDecodeEntities TODO: remove it in
next major release. [67] Reference ::= EntityRef | CharRef
[69] PEReference ::= '%' Name ';' """
... | [
"def",
"decodeEntities",
"(",
"self",
",",
"len",
",",
"what",
",",
"end",
",",
"end2",
",",
"end3",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlDecodeEntities",
"(",
"self",
".",
"_o",
",",
"len",
",",
"what",
",",
"end",
",",
"end2",
",",
"end3"... | 58.142857 | 18.857143 |
def compile_insert_get_id(self, query, values, sequence=None):
"""
Compile an insert and get ID statement into SQL.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param values: The values to insert
:type values: dict
:param sequence: The id se... | [
"def",
"compile_insert_get_id",
"(",
"self",
",",
"query",
",",
"values",
",",
"sequence",
"=",
"None",
")",
":",
"if",
"sequence",
"is",
"None",
":",
"sequence",
"=",
"\"id\"",
"return",
"\"%s RETURNING %s\"",
"%",
"(",
"self",
".",
"compile_insert",
"(",
... | 25.695652 | 16.391304 |
def update(self, value=None):
"""
Update progress bar via the console or notebook accordingly.
"""
# Update self.value
if value is None:
value = self._current_value + 1
self._current_value = value
# Choose the appropriate environment
if self.... | [
"def",
"update",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"# Update self.value",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"self",
".",
"_current_value",
"+",
"1",
"self",
".",
"_current_value",
"=",
"value",
"# Choose the appropriate environmen... | 27.5 | 14.277778 |
def remove(self,num):
"""Remove a finished (completed or dead) job."""
try:
job = self.all[num]
except KeyError:
error('Job #%s not found' % num)
else:
stat_code = job.stat_code
if stat_code == self._s_running:
error('Job #... | [
"def",
"remove",
"(",
"self",
",",
"num",
")",
":",
"try",
":",
"job",
"=",
"self",
".",
"all",
"[",
"num",
"]",
"except",
"KeyError",
":",
"error",
"(",
"'Job #%s not found'",
"%",
"num",
")",
"else",
":",
"stat_code",
"=",
"job",
".",
"stat_code",
... | 34.5625 | 13.9375 |
def _default_data(self, *args, **kwargs):
"""
Generate a one-time signature and other data required to send a secure
POST request to the Bitstamp API.
"""
data = super(Trading, self)._default_data(*args, **kwargs)
data['key'] = self.key
nonce = self.get_nonce()
... | [
"def",
"_default_data",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"super",
"(",
"Trading",
",",
"self",
")",
".",
"_default_data",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"data",
"[",
"'key'",
"]",
"="... | 37.3125 | 13.9375 |
def load_annot(self):
"""Action: load a file for annotations."""
if self.parent.info.filename is not None:
filename = splitext(self.parent.info.filename)[0] + '_scores.xml'
else:
filename = None
filename, _ = QFileDialog.getOpenFileName(self, 'Load annotation fil... | [
"def",
"load_annot",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"info",
".",
"filename",
"is",
"not",
"None",
":",
"filename",
"=",
"splitext",
"(",
"self",
".",
"parent",
".",
"info",
".",
"filename",
")",
"[",
"0",
"]",
"+",
"'_scor... | 35.35 | 21.45 |
def down(self, migration_id):
"""Rollback to migration."""
if not self.check_directory():
return
for migration in self.get_migrations_to_down(migration_id):
logger.info('Rollback migration %s' % migration.filename)
migration_module = self.load_migration_file... | [
"def",
"down",
"(",
"self",
",",
"migration_id",
")",
":",
"if",
"not",
"self",
".",
"check_directory",
"(",
")",
":",
"return",
"for",
"migration",
"in",
"self",
".",
"get_migrations_to_down",
"(",
"migration_id",
")",
":",
"logger",
".",
"info",
"(",
"... | 38.933333 | 22.933333 |
def do_notification_type_list(mc, args):
'''List notification types supported by monasca.'''
try:
notification_types = mc.notificationtypes.list()
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
if ar... | [
"def",
"do_notification_type_list",
"(",
"mc",
",",
"args",
")",
":",
"try",
":",
"notification_types",
"=",
"mc",
".",
"notificationtypes",
".",
"list",
"(",
")",
"except",
"(",
"osc_exc",
".",
"ClientException",
",",
"k_exc",
".",
"HttpError",
")",
"as",
... | 42.666667 | 25.466667 |
def get_mac_address_table_input_request_type_get_interface_based_request_forwarding_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_address_table = ET.Element("get_mac_address_table")
config = get_mac_address_table
... | [
"def",
"get_mac_address_table_input_request_type_get_interface_based_request_forwarding_interface_interface_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_mac_address_table",
"=",
"ET",
".",
"Elemen... | 56.333333 | 26.133333 |
def setDayWidth(self, width):
"""
Sets the day width that will be used for drawing this gantt widget.
:param width | <int>
"""
self._dayWidth = width
start = self.ganttWidget().dateStart()
end = self.ganttWidget().dateEnd()
... | [
"def",
"setDayWidth",
"(",
"self",
",",
"width",
")",
":",
"self",
".",
"_dayWidth",
"=",
"width",
"start",
"=",
"self",
".",
"ganttWidget",
"(",
")",
".",
"dateStart",
"(",
")",
"end",
"=",
"self",
".",
"ganttWidget",
"(",
")",
".",
"dateEnd",
"(",
... | 28.166667 | 14.833333 |
def display(self, complete=False):
"""
Display information about the point source.
:param complete : if True, displays also information on fixed parameters
:return: (none)
"""
# Switch on the complete display flag
self._complete_display = bool(complete)
... | [
"def",
"display",
"(",
"self",
",",
"complete",
"=",
"False",
")",
":",
"# Switch on the complete display flag",
"self",
".",
"_complete_display",
"=",
"bool",
"(",
"complete",
")",
"# This will automatically choose the best representation among repr and repr_html",
"super",
... | 27.388889 | 21.833333 |
def initialize_ui(self):
"""
Initializes the Component ui.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Initializing '{0}' Component ui.".format(self.__class__.__name__))
self.__model = ComponentsModel(self, horizontal_headers=self.__headers)
... | [
"def",
"initialize_ui",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Initializing '{0}' Component ui.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"self",
".",
"__model",
"=",
"ComponentsModel",
"(",
"self",
",",
"... | 41.65625 | 30.09375 |
def is_attribute_deprecated(self, attribute):
"""
Check if the attribute is deprecated by the current KMIP version.
Args:
attribute (string): The name of the attribute
(e.g., 'Unique Identifier'). Required.
"""
rule_set = self._attribute_rule_sets.get... | [
"def",
"is_attribute_deprecated",
"(",
"self",
",",
"attribute",
")",
":",
"rule_set",
"=",
"self",
".",
"_attribute_rule_sets",
".",
"get",
"(",
"attribute",
")",
"if",
"rule_set",
".",
"version_deprecated",
":",
"if",
"self",
".",
"_version",
">=",
"rule_set... | 33.1875 | 16.6875 |
def predict_topk(self, dataset, output_type="probability", k=3, batch_size=64):
"""
Return top-k predictions for the ``dataset``, using the trained model.
Predictions are returned as an SFrame with three columns: `id`,
`class`, and `probability`, `margin`, or `rank`, depending on the ``... | [
"def",
"predict_topk",
"(",
"self",
",",
"dataset",
",",
"output_type",
"=",
"\"probability\"",
",",
"k",
"=",
"3",
",",
"batch_size",
"=",
"64",
")",
":",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"(",
"_tc",
".",
"SFrame",
",",
"_tc",
".",
"S... | 40.875 | 21.75 |
def prep_patterns(filenames):
"""Load pattern files passed via options and return list of patterns."""
patterns = []
for filename in filenames:
try:
with open(filename) as file:
patterns += [l.rstrip('\n') for l in file]
except: # pylint: disable=W0702
... | [
"def",
"prep_patterns",
"(",
"filenames",
")",
":",
"patterns",
"=",
"[",
"]",
"for",
"filename",
"in",
"filenames",
":",
"try",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"file",
":",
"patterns",
"+=",
"[",
"l",
".",
"rstrip",
"(",
"'\\n'",
")... | 29.368421 | 18.736842 |
def package_url(self):
"""Return the package URL associated with this metadata"""
if self.resource_file == DEFAULT_METATAB_FILE or self.target_format in ('txt','ipynb'):
u = self.inner.clone().clear_fragment()
u.path = dirname(self.path) + '/'
u.scheme_extension = 'm... | [
"def",
"package_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"resource_file",
"==",
"DEFAULT_METATAB_FILE",
"or",
"self",
".",
"target_format",
"in",
"(",
"'txt'",
",",
"'ipynb'",
")",
":",
"u",
"=",
"self",
".",
"inner",
".",
"clone",
"(",
")",
"."... | 40.181818 | 24.181818 |
def draw_edge_visibility(gl, v, e, f, hidden_wireframe=True):
"""Assumes camera is set up correctly in gl context."""
gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
ec = np.arange(1, len(e)+1)
ec = np.tile(col(ec), (1, 3))
ec[:, 0] = ec[:, 0] & 255
ec[:, 1] = (ec[:, 1] >> 8 ) & 255
ec... | [
"def",
"draw_edge_visibility",
"(",
"gl",
",",
"v",
",",
"e",
",",
"f",
",",
"hidden_wireframe",
"=",
"True",
")",
":",
"gl",
".",
"Clear",
"(",
"GL_COLOR_BUFFER_BIT",
"|",
"GL_DEPTH_BUFFER_BIT",
")",
"ec",
"=",
"np",
".",
"arange",
"(",
"1",
",",
"len... | 34.681818 | 14.545455 |
def set_config(new_config={}):
""" Reset config options to defaults, and then update (optionally)
with the provided dictionary of options. """
# The default base configuration.
flask_app.base_config = dict(working_directory='.',
template='collapse-input',
... | [
"def",
"set_config",
"(",
"new_config",
"=",
"{",
"}",
")",
":",
"# The default base configuration.",
"flask_app",
".",
"base_config",
"=",
"dict",
"(",
"working_directory",
"=",
"'.'",
",",
"template",
"=",
"'collapse-input'",
",",
"debug",
"=",
"False",
",",
... | 46.222222 | 7.333333 |
def formatted_command(self, command):
"""Issue a raw, formatted command to the device.
This function is invoked by both query and command and is the point
where we actually send bytes out over the network. This function does
the wrapping and formatting required by the Anthem API so tha... | [
"def",
"formatted_command",
"(",
"self",
",",
"command",
")",
":",
"command",
"=",
"command",
"command",
"=",
"command",
".",
"encode",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'> %s'",
",",
"command",
")",
"try",
":",
"self",
".",
"transport"... | 36.04 | 22.4 |
def mangle(self, name, x):
"""
Mangle the name by hashing the I{name} and appending I{x}.
@return: the mangled name.
"""
h = hashlib.md5(name.encode('utf8')).hexdigest()
return '%s-%s' % (h, x) | [
"def",
"mangle",
"(",
"self",
",",
"name",
",",
"x",
")",
":",
"h",
"=",
"hashlib",
".",
"md5",
"(",
"name",
".",
"encode",
"(",
"'utf8'",
")",
")",
".",
"hexdigest",
"(",
")",
"return",
"'%s-%s'",
"%",
"(",
"h",
",",
"x",
")"
] | 33.571429 | 10.142857 |
def unlock_keychain(username):
""" If the user is running via SSH, their Keychain must be unlocked first. """
if 'SSH_TTY' not in os.environ:
return
# Don't unlock if we've already seen this user.
if username in _unlocked:
return
_unlocked.add(username)
if sys.platform == 'da... | [
"def",
"unlock_keychain",
"(",
"username",
")",
":",
"if",
"'SSH_TTY'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"# Don't unlock if we've already seen this user.",
"if",
"username",
"in",
"_unlocked",
":",
"return",
"_unlocked",
".",
"add",
"(",
"username... | 34.266667 | 26 |
def unzip(x, split_dim, current_length, num_splits=2, name=None):
"""Splits a tensor by unzipping along the split_dim.
For example the following array split into 2 would be:
[1, 2, 3, 4, 5, 6] -> [1, 3, 5], [2, 4, 6]
and by 3:
[1, 2, 3, 4] -> [1, 4], [2], [3]
Args:
x: The tensor to split.
... | [
"def",
"unzip",
"(",
"x",
",",
"split_dim",
",",
"current_length",
",",
"num_splits",
"=",
"2",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'unzip'",
",",
"[",
"x",
"]",
")",
"as",
"scope",
":",
"x",
"=... | 36.961538 | 14.615385 |
def addVariantSet(self):
"""
Adds a new VariantSet into this repo.
"""
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
dataUrls = self._args.dataFiles
name = self._args.name
if len(dataUrls) == 1:
if self._args.na... | [
"def",
"addVariantSet",
"(",
"self",
")",
":",
"self",
".",
"_openRepo",
"(",
")",
"dataset",
"=",
"self",
".",
"_repo",
".",
"getDatasetByName",
"(",
"self",
".",
"_args",
".",
"datasetName",
")",
"dataUrls",
"=",
"self",
".",
"_args",
".",
"dataFiles",... | 52.639535 | 17.360465 |
def near_dupe_hashes(labels, values, languages=None, **kw):
"""
Hash the given address into normalized strings that can be used to group similar
addresses together for more detailed pairwise comparison. This can be thought of
as the blocking function in record linkage or locally-sensitive hashing in the... | [
"def",
"near_dupe_hashes",
"(",
"labels",
",",
"values",
",",
"languages",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"return",
"_near_dupe",
".",
"near_dupe_hashes",
"(",
"labels",
",",
"values",
",",
"languages",
"=",
"languages",
",",
"*",
"*",
"kw",... | 55.702703 | 28.567568 |
def unregister_area(self, area_code, index):
"""'Unshares' a memory area previously shared with Srv_RegisterArea().
That memory block will be no longer visible by the clients.
"""
return self.library.Srv_UnregisterArea(self.pointer, area_code, index) | [
"def",
"unregister_area",
"(",
"self",
",",
"area_code",
",",
"index",
")",
":",
"return",
"self",
".",
"library",
".",
"Srv_UnregisterArea",
"(",
"self",
".",
"pointer",
",",
"area_code",
",",
"index",
")"
] | 55.6 | 13.8 |
def transfer(self, user):
"""Transfers app to given username's account."""
r = self._h._http_resource(
method='PUT',
resource=('apps', self.name),
data={'app[transfer_owner]': user}
)
return r.ok | [
"def",
"transfer",
"(",
"self",
",",
"user",
")",
":",
"r",
"=",
"self",
".",
"_h",
".",
"_http_resource",
"(",
"method",
"=",
"'PUT'",
",",
"resource",
"=",
"(",
"'apps'",
",",
"self",
".",
"name",
")",
",",
"data",
"=",
"{",
"'app[transfer_owner]'"... | 28.444444 | 14.888889 |
def show_prediction(estimator, doc, **kwargs):
""" Return an explanation of estimator prediction
as an IPython.display.HTML object. Use this function
to show information about classifier prediction in IPython.
:func:`show_prediction` accepts all
:func:`eli5.explain_prediction` arguments and all
... | [
"def",
"show_prediction",
"(",
"estimator",
",",
"doc",
",",
"*",
"*",
"kwargs",
")",
":",
"format_kwargs",
",",
"explain_kwargs",
"=",
"_split_kwargs",
"(",
"kwargs",
")",
"expl",
"=",
"explain_prediction",
"(",
"estimator",
",",
"doc",
",",
"*",
"*",
"ex... | 44.57047 | 26.328859 |
def provStacks(self, offs, size):
'''
Returns a stream of provenance stacks at the given offset
'''
for _, iden in self.provseq.slice(offs, size):
stack = self.getProvStack(iden)
if stack is None:
continue
yield (iden, stack) | [
"def",
"provStacks",
"(",
"self",
",",
"offs",
",",
"size",
")",
":",
"for",
"_",
",",
"iden",
"in",
"self",
".",
"provseq",
".",
"slice",
"(",
"offs",
",",
"size",
")",
":",
"stack",
"=",
"self",
".",
"getProvStack",
"(",
"iden",
")",
"if",
"sta... | 33.444444 | 15.888889 |
def replace_entity_resource(model, oldres, newres):
'''
Replace one entity in the model with another with the same links
:param model: Versa model to be updated
:param oldres: old/former resource IRI to be replaced
:param newres: new/replacement resource IRI
:return: None
'''
oldrids = ... | [
"def",
"replace_entity_resource",
"(",
"model",
",",
"oldres",
",",
"newres",
")",
":",
"oldrids",
"=",
"set",
"(",
")",
"for",
"rid",
",",
"link",
"in",
"model",
":",
"if",
"link",
"[",
"ORIGIN",
"]",
"==",
"oldres",
"or",
"link",
"[",
"TARGET",
"]"... | 40.352941 | 27.176471 |
def get_assets_metadata(self):
"""Gets the metadata for the assets.
return: (osid.Metadata) - metadata for the assets
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template
... | [
"def",
"get_assets_metadata",
"(",
"self",
")",
":",
"# Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_mdata",
"[",
"'assets'",
"]",
")",
"metadata",
".",
"update",
"(",
"{",
"'existin... | 42 | 21.545455 |
def send_ready_for_review(build_id, release_name, release_number):
"""Sends an email indicating that the release is ready for review."""
build = models.Build.query.get(build_id)
if not build.send_email:
logging.debug(
'Not sending ready for review email because build does not have '
... | [
"def",
"send_ready_for_review",
"(",
"build_id",
",",
"release_name",
",",
"release_number",
")",
":",
"build",
"=",
"models",
".",
"Build",
".",
"query",
".",
"get",
"(",
"build_id",
")",
"if",
"not",
"build",
".",
"send_email",
":",
"logging",
".",
"debu... | 33.75 | 21.576923 |
def by_land_area_in_sqmi(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.land_area_in_sqmi.name,
ascending=False,
... | [
"def",
"by_land_area_in_sqmi",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"land_area_in_sqmi",
".",
"name",
",",
"ascend... | 40.9375 | 11.6875 |
def body_block_content_render(tag, recursive=False, base_url=None):
"""
Render the tag as body content and call recursively if
the tag has child tags
"""
block_content_list = []
tag_content = OrderedDict()
if tag.name == "p":
for block_content in body_block_paragraph_render(tag, bas... | [
"def",
"body_block_content_render",
"(",
"tag",
",",
"recursive",
"=",
"False",
",",
"base_url",
"=",
"None",
")",
":",
"block_content_list",
"=",
"[",
"]",
"tag_content",
"=",
"OrderedDict",
"(",
")",
"if",
"tag",
".",
"name",
"==",
"\"p\"",
":",
"for",
... | 40.482759 | 22.241379 |
def replace(self, left=None, lower=None, upper=None, right=None, ignore_inf=True):
"""
Create a new interval based on the current one and the provided values.
If current interval is not atomic, it is extended or restricted such that
its enclosure satisfies the new bounds. In other words... | [
"def",
"replace",
"(",
"self",
",",
"left",
"=",
"None",
",",
"lower",
"=",
"None",
",",
"upper",
"=",
"None",
",",
"right",
"=",
"None",
",",
"ignore_inf",
"=",
"True",
")",
":",
"enclosure",
"=",
"self",
".",
"to_atomic",
"(",
")",
"if",
"callabl... | 43.714286 | 28.367347 |
def kill_all(self):
""" Kill all currently running jobs. """
logger.info('Job {0} killing all currently running tasks'.format(self.name))
for task in self.tasks.itervalues():
if task.started_at and not task.completed_at:
task.kill() | [
"def",
"kill_all",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Job {0} killing all currently running tasks'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"for",
"task",
"in",
"self",
".",
"tasks",
".",
"itervalues",
"(",
")",
":",
"if",
"... | 46.5 | 16.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.