text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def listReleaseVersions(self, release_version="", dataset='', logical_file_name=''):
"""
List release versions
"""
if dataset and ('%' in dataset or '*' in dataset):
dbsExceptionHandler('dbsException-invalid-input',
" DBSReleaseVersion/listReleaseVersions. No ... | [
"def",
"listReleaseVersions",
"(",
"self",
",",
"release_version",
"=",
"\"\"",
",",
"dataset",
"=",
"''",
",",
"logical_file_name",
"=",
"''",
")",
":",
"if",
"dataset",
"and",
"(",
"'%'",
"in",
"dataset",
"or",
"'*'",
"in",
"dataset",
")",
":",
"dbsExc... | 40 | 20.642857 |
def populate_from_path(bucket, source, checksum=True, key_prefix='',
chunk_size=None):
"""Populate a ``bucket`` from all files in path.
:param bucket: The bucket (instance or id) to create the object in.
:param source: The file or directory path.
:param checksum: If ``True`` then... | [
"def",
"populate_from_path",
"(",
"bucket",
",",
"source",
",",
"checksum",
"=",
"True",
",",
"key_prefix",
"=",
"''",
",",
"chunk_size",
"=",
"None",
")",
":",
"from",
".",
"models",
"import",
"FileInstance",
",",
"ObjectVersion",
"def",
"create_file",
"(",... | 42.139535 | 19.046512 |
def _parse_message(self, data):
"""
Parse the message from the device.
:param data: message data
:type data: string
:raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
"""
match = self._regex.match(str(data))
if match is None:
raise ... | [
"def",
"_parse_message",
"(",
"self",
",",
"data",
")",
":",
"match",
"=",
"self",
".",
"_regex",
".",
"match",
"(",
"str",
"(",
"data",
")",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"InvalidMessageError",
"(",
"'Received invalid message: {0}'",
"."... | 37.844444 | 14.866667 |
def get_node_bundle(manager, handle_id=None, node=None):
"""
:param manager: Neo4jDBSessionManager
:param handle_id: Unique id
:type handle_id: str|unicode
:param node: Node object
:type node: neo4j.v1.types.Node
:return: dict
"""
if not node:
node = get_node(manager, handle_... | [
"def",
"get_node_bundle",
"(",
"manager",
",",
"handle_id",
"=",
"None",
",",
"node",
"=",
"None",
")",
":",
"if",
"not",
"node",
":",
"node",
"=",
"get_node",
"(",
"manager",
",",
"handle_id",
"=",
"handle_id",
",",
"legacy",
"=",
"False",
")",
"d",
... | 28.909091 | 14.545455 |
def _get_structure(self, data, primitive):
"""
Generate structure from part of the cif.
"""
def get_num_implicit_hydrogens(sym):
num_h = {"Wat": 2, "wat": 2, "O-H": 1}
return num_h.get(sym[:3], 0)
lattice = self.get_lattice(data)
# if magCIF, ge... | [
"def",
"_get_structure",
"(",
"self",
",",
"data",
",",
"primitive",
")",
":",
"def",
"get_num_implicit_hydrogens",
"(",
"sym",
")",
":",
"num_h",
"=",
"{",
"\"Wat\"",
":",
"2",
",",
"\"wat\"",
":",
"2",
",",
"\"O-H\"",
":",
"1",
"}",
"return",
"num_h"... | 41.388889 | 19.388889 |
def _logging_callback(level, domain, message, data):
""" Callback that outputs libgphoto2's logging message via
Python's standard logging facilities.
:param level: libgphoto2 logging level
:param domain: component the message originates from
:param message: logging message
:param data: ... | [
"def",
"_logging_callback",
"(",
"level",
",",
"domain",
",",
"message",
",",
"data",
")",
":",
"domain",
"=",
"ffi",
".",
"string",
"(",
"domain",
")",
".",
"decode",
"(",
")",
"message",
"=",
"ffi",
".",
"string",
"(",
"message",
")",
".",
"decode"... | 35.5 | 11.6875 |
def get_arg_info(self, state, is_fp=None, sizes=None):
"""
This is just a simple wrapper that collects the information from various locations
is_fp and sizes are passed to self.arg_locs and self.get_args
:param angr.SimState state: The state to evaluate and extract the values from
... | [
"def",
"get_arg_info",
"(",
"self",
",",
"state",
",",
"is_fp",
"=",
"None",
",",
"sizes",
"=",
"None",
")",
":",
"argument_types",
"=",
"self",
".",
"func_ty",
".",
"args",
"argument_names",
"=",
"self",
".",
"func_ty",
".",
"arg_names",
"if",
"self",
... | 68.333333 | 33.166667 |
def max_pool(input_layer, kernel, stride, edges=PAD_SAME, name=PROVIDED):
"""Performs max pooling.
`kernel` is the patch that will be pooled and it describes the pooling along
each of the 4 dimensions. `stride` is how big to take each step.
Because more often than not, pooling is only done
on the width and... | [
"def",
"max_pool",
"(",
"input_layer",
",",
"kernel",
",",
"stride",
",",
"edges",
"=",
"PAD_SAME",
",",
"name",
"=",
"PROVIDED",
")",
":",
"return",
"_pool",
"(",
"input_layer",
",",
"tf",
".",
"nn",
".",
"max_pool",
",",
"kernel",
",",
"stride",
",",... | 43.965517 | 23.448276 |
def _get_mro(cls):
"""
Returns the bases classes for cls sorted by the MRO.
Works around an issue on Jython where inspect.getmro will not return all
base classes if multiple classes share the same name. Instead, this
function will return a tuple containing the class itself, and the contents
of ... | [
"def",
"_get_mro",
"(",
"cls",
")",
":",
"if",
"platform",
".",
"python_implementation",
"(",
")",
"==",
"\"Jython\"",
":",
"return",
"(",
"cls",
",",
")",
"+",
"cls",
".",
"__bases__",
"return",
"inspect",
".",
"getmro",
"(",
"cls",
")"
] | 42.083333 | 20.083333 |
def find_element_by_jquery(browser, selector):
"""Find a single HTML element using jQuery-style selectors."""
elements = find_elements_by_jquery(browser, selector)
if not elements:
raise AssertionError("No matching element found.")
if len(elements) > 1:
raise AssertionError("Multiple mat... | [
"def",
"find_element_by_jquery",
"(",
"browser",
",",
"selector",
")",
":",
"elements",
"=",
"find_elements_by_jquery",
"(",
"browser",
",",
"selector",
")",
"if",
"not",
"elements",
":",
"raise",
"AssertionError",
"(",
"\"No matching element found.\"",
")",
"if",
... | 44.875 | 14.875 |
def distb(self, tb=None, file=None):
"""Disassemble a traceback (default: last traceback)."""
if tb is None:
try:
tb = sys.last_traceback
except AttributeError:
raise RuntimeError("no last traceback to disassemble")
while tb.tb_next: tb... | [
"def",
"distb",
"(",
"self",
",",
"tb",
"=",
"None",
",",
"file",
"=",
"None",
")",
":",
"if",
"tb",
"is",
"None",
":",
"try",
":",
"tb",
"=",
"sys",
".",
"last_traceback",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"\"no last trace... | 43.777778 | 12.888889 |
def registerevent(self, event_name, fn_name, *args):
"""
Register at-spi event
@param event_name: Event name in at-spi format.
@type event_name: string
@param fn_name: Callback function
@type fn_name: function
@param *args: arguments to be passed to the callback ... | [
"def",
"registerevent",
"(",
"self",
",",
"event_name",
",",
"fn_name",
",",
"*",
"args",
")",
":",
"if",
"not",
"isinstance",
"(",
"event_name",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"event_name should be string\"",
")",
"self",
".",
"_pollEve... | 37.444444 | 15.777778 |
def search_response(self, request):
"""
creates a key from the request and searches the cache with it
:param request:
:return CacheElement: returns None if there's a cache miss
"""
logger.debug("Cache Search Response")
if self.cache.is_empty() is True:
... | [
"def",
"search_response",
"(",
"self",
",",
"request",
")",
":",
"logger",
".",
"debug",
"(",
"\"Cache Search Response\"",
")",
"if",
"self",
".",
"cache",
".",
"is_empty",
"(",
")",
"is",
"True",
":",
"logger",
".",
"debug",
"(",
"\"Empty Cache\"",
")",
... | 26 | 16.56 |
def delete_currency_by_id(cls, currency_id, **kwargs):
"""Delete Currency
Delete an instance of Currency by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_currency_by_id(curren... | [
"def",
"delete_currency_by_id",
"(",
"cls",
",",
"currency_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_delete_currency_by_i... | 41.52381 | 20.142857 |
def argmin(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column and returns a list containing a single row (dict from
columns to cells) that has the minimum numerical value in the given column. We return a list
instead of a single dict to b... | [
"def",
"argmin",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"ComparableColumn",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"return",
"[",
"]",
"value_row_pairs",
"=",
"[",
"(",
"row",
".",
... | 50 | 26.428571 |
def get_model_spec_ting(atomic_number):
"""
X_u_template[0:2] are teff, logg, vturb in km/s
X_u_template[:,3] -> onward, put atomic number
atomic_number is 6 for C, 7 for N
"""
DATA_DIR = "/Users/annaho/Data/LAMOST/Mass_And_Age"
temp = np.load("%s/X_u_template_KGh_res=1800.npz" %DATA_DIR)
... | [
"def",
"get_model_spec_ting",
"(",
"atomic_number",
")",
":",
"DATA_DIR",
"=",
"\"/Users/annaho/Data/LAMOST/Mass_And_Age\"",
"temp",
"=",
"np",
".",
"load",
"(",
"\"%s/X_u_template_KGh_res=1800.npz\"",
"%",
"DATA_DIR",
")",
"X_u_template",
"=",
"temp",
"[",
"\"X_u_templ... | 37.25 | 8.333333 |
def clustering_coef_wd(W):
'''
The weighted clustering coefficient is the average "intensity" of
triangles around a node.
Parameters
----------
W : NxN np.ndarray
weighted directed connection matrix
Returns
-------
C : Nx1 np.ndarray
clustering coefficient vector
... | [
"def",
"clustering_coef_wd",
"(",
"W",
")",
":",
"A",
"=",
"np",
".",
"logical_not",
"(",
"W",
"==",
"0",
")",
".",
"astype",
"(",
"float",
")",
"# adjacency matrix",
"S",
"=",
"cuberoot",
"(",
"W",
")",
"+",
"cuberoot",
"(",
"W",
".",
"T",
")",
... | 33.617647 | 22.794118 |
def timTuVi(cuc, ngaySinhAmLich):
"""Tìm vị trí của sao Tử vi
Args:
cuc (TYPE): Description
ngaySinhAmLich (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description
"""
cungDan = 3 # Vị trí cung Dần ban đầu là 3
cucBanDau = cuc
if c... | [
"def",
"timTuVi",
"(",
"cuc",
",",
"ngaySinhAmLich",
")",
":",
"cungDan",
"=",
"3",
"# Vị trí cung Dần ban đầu là 3",
"cucBanDau",
"=",
"cuc",
"if",
"cuc",
"not",
"in",
"[",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
"]",
":",
"# Tránh trường hợp infin... | 28.541667 | 16.958333 |
def analogous(clr, angle=10, contrast=0.25):
"""
Returns colors that are next to each other on the wheel.
These yield natural color schemes (like shades of water or sky).
The angle determines how far the colors are apart,
making it bigger will introduce more variation.
The contrast determines t... | [
"def",
"analogous",
"(",
"clr",
",",
"angle",
"=",
"10",
",",
"contrast",
"=",
"0.25",
")",
":",
"contrast",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"contrast",
",",
"1.0",
")",
")",
"clr",
"=",
"color",
"(",
"clr",
")",
"colors",
"=",
"colorlist"... | 31.423077 | 17.038462 |
def get_timezone(as_timedelta=False):
""" utility to get the machine's timezone """
try:
offset_hour = -(time.altzone if time.daylight else time.timezone)
except Exception as e:
offset_hour = -(datetime.datetime.now() -
datetime.datetime.utcnow()).seconds
offset_... | [
"def",
"get_timezone",
"(",
"as_timedelta",
"=",
"False",
")",
":",
"try",
":",
"offset_hour",
"=",
"-",
"(",
"time",
".",
"altzone",
"if",
"time",
".",
"daylight",
"else",
"time",
".",
"timezone",
")",
"except",
"Exception",
"as",
"e",
":",
"offset_hour... | 34.6 | 20 |
def setCurrentState(self, state):
"""
Sets the current state for this edit to the inputed state.
:param state | <XLineEdit.State>
"""
self._currentState = state
palette = self.palette()
if state == XLineEdit.State.Normal:
... | [
"def",
"setCurrentState",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_currentState",
"=",
"state",
"palette",
"=",
"self",
".",
"palette",
"(",
")",
"if",
"state",
"==",
"XLineEdit",
".",
"State",
".",
"Normal",
":",
"palette",
"=",
"QApplication... | 41.166667 | 18.583333 |
def movementCompute(self, displacement, noiseFactor = 0):
"""
Shift the current active cells by a vector.
@param displacement (pair of floats)
A translation vector [di, dj].
"""
if noiseFactor != 0:
displacement = copy.deepcopy(displacement)
xnoise = np.random.normal(0, noiseFactor... | [
"def",
"movementCompute",
"(",
"self",
",",
"displacement",
",",
"noiseFactor",
"=",
"0",
")",
":",
"if",
"noiseFactor",
"!=",
"0",
":",
"displacement",
"=",
"copy",
".",
"deepcopy",
"(",
"displacement",
")",
"xnoise",
"=",
"np",
".",
"random",
".",
"nor... | 34.451613 | 19.741935 |
def wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd,
ab, xdirect, msrc, mrec, use_ne_eval):
r"""Calculate wavenumber domain solution.
Return the wavenumber domain solutions ``PJ0``, ``PJ1``, and ``PJ0b``,
which have to be transformed with a Hankel transform to the f... | [
"def",
"wavenumber",
"(",
"zsrc",
",",
"zrec",
",",
"lsrc",
",",
"lrec",
",",
"depth",
",",
"etaH",
",",
"etaV",
",",
"zetaH",
",",
"zetaV",
",",
"lambd",
",",
"ab",
",",
"xdirect",
",",
"msrc",
",",
"mrec",
",",
"use_ne_eval",
")",
":",
"# ** CALC... | 37.626506 | 26.518072 |
def bfs(graph, start=0):
"""Shortest path in unweighted graph by BFS
:param graph: directed graph in listlist or listdict format
:param int start: source vertex
:returns: distance table, precedence table
:complexity: `O(|V|+|E|)`
"""
to_visit = deque()
dist = [float('inf'... | [
"def",
"bfs",
"(",
"graph",
",",
"start",
"=",
"0",
")",
":",
"to_visit",
"=",
"deque",
"(",
")",
"dist",
"=",
"[",
"float",
"(",
"'inf'",
")",
"]",
"*",
"len",
"(",
"graph",
")",
"prec",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"graph",
")",
... | 35 | 11.714286 |
def _update_values_in_window(self):
"""Update which values are in the current window."""
window_bound_upper = self._window_bound_lower + self.window_size
self._x_in_window = self.x[self._window_bound_lower:window_bound_upper]
self._y_in_window = self.y[self._window_bound_lower:window_bou... | [
"def",
"_update_values_in_window",
"(",
"self",
")",
":",
"window_bound_upper",
"=",
"self",
".",
"_window_bound_lower",
"+",
"self",
".",
"window_size",
"self",
".",
"_x_in_window",
"=",
"self",
".",
"x",
"[",
"self",
".",
"_window_bound_lower",
":",
"window_bo... | 65 | 23 |
def do(self, arg):
".exchain - Show the SEH chain"
thread = self.get_thread_from_prefix()
print "Exception handlers for thread %d" % thread.get_tid()
print
table = Table()
table.addRow("Block", "Function")
bits = thread.get_bits()
for (seh, seh_func) in thread.get_seh_chain():
if... | [
"def",
"do",
"(",
"self",
",",
"arg",
")",
":",
"thread",
"=",
"self",
".",
"get_thread_from_prefix",
"(",
")",
"print",
"\"Exception handlers for thread %d\"",
"%",
"thread",
".",
"get_tid",
"(",
")",
"print",
"table",
"=",
"Table",
"(",
")",
"table",
"."... | 35 | 12.733333 |
def init_app(application):
"""
Associates the error handler
"""
for code in werkzeug.exceptions.default_exceptions:
application.register_error_handler(code, handle_http_exception) | [
"def",
"init_app",
"(",
"application",
")",
":",
"for",
"code",
"in",
"werkzeug",
".",
"exceptions",
".",
"default_exceptions",
":",
"application",
".",
"register_error_handler",
"(",
"code",
",",
"handle_http_exception",
")"
] | 33 | 11.333333 |
def is_Quadratic(self):
"""Returns True if the expression is a polynomial with degree exactly 2 (read-only)."""
if self.expression.is_Atom:
return False
if all((len(key.free_symbols) < 2 and (key.is_Add or key.is_Mul or key.is_Atom)
for key in self.expression.as_coeff... | [
"def",
"is_Quadratic",
"(",
"self",
")",
":",
"if",
"self",
".",
"expression",
".",
"is_Atom",
":",
"return",
"False",
"if",
"all",
"(",
"(",
"len",
"(",
"key",
".",
"free_symbols",
")",
"<",
"2",
"and",
"(",
"key",
".",
"is_Add",
"or",
"key",
".",... | 43.763158 | 15.578947 |
def do_page_wrap(self, args: List[str]):
"""Read in a text file and display its output in a pager, wrapping long lines if they don't fit.
Usage: page_wrap <file_path>
"""
if not args:
self.perror('page_wrap requires a path to a file as an argument', traceback_war=False)
... | [
"def",
"do_page_wrap",
"(",
"self",
",",
"args",
":",
"List",
"[",
"str",
"]",
")",
":",
"if",
"not",
"args",
":",
"self",
".",
"perror",
"(",
"'page_wrap requires a path to a file as an argument'",
",",
"traceback_war",
"=",
"False",
")",
"return",
"self",
... | 41.111111 | 16.333333 |
def _create_json(self):
"""
JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON
"""
data_json = super(GroupLDAP, self)._create_json()
data_json.update({
'realmAttributes': self.realmAttributes,
'external': True,
... | [
"def",
"_create_json",
"(",
"self",
")",
":",
"data_json",
"=",
"super",
"(",
"GroupLDAP",
",",
"self",
")",
".",
"_create_json",
"(",
")",
"data_json",
".",
"update",
"(",
"{",
"'realmAttributes'",
":",
"self",
".",
"realmAttributes",
",",
"'external'",
"... | 34.3 | 17.7 |
def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_objects_list_item.OnlineDatabaseObjectsListItem
'''
oprot.wr... | [
"def",
"write",
"(",
"self",
",",
"oprot",
")",
":",
"oprot",
".",
"write_struct_begin",
"(",
"'OnlineDatabaseObjectsListItem'",
")",
"oprot",
".",
"write_field_begin",
"(",
"name",
"=",
"'detail_href'",
",",
"type",
"=",
"11",
",",
"id",
"=",
"None",
")",
... | 33.3125 | 24.9375 |
def listdir(self, directory_path=None, hidden_files=False):
"""
Return a list of files and directories in a given directory.
:param directory_path: Optional str (defaults to current directory)
:param hidden_files: Include hidden files
:return: Directory listing
"""
... | [
"def",
"listdir",
"(",
"self",
",",
"directory_path",
"=",
"None",
",",
"hidden_files",
"=",
"False",
")",
":",
"# Change current directory if a directory path is specified, otherwise use current",
"if",
"directory_path",
":",
"self",
".",
"chdir",
"(",
"directory_path",
... | 36.052632 | 20.473684 |
def irfs(self, **kwargs):
""" Get the name of IFRs associted with a particular dataset
"""
dsval = kwargs.get('dataset', self.dataset(**kwargs))
tokens = dsval.split('_')
irf_name = "%s_%s_%s" % (DATASET_DICTIONARY['%s_%s' % (tokens[0], tokens[1])],
... | [
"def",
"irfs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"dsval",
"=",
"kwargs",
".",
"get",
"(",
"'dataset'",
",",
"self",
".",
"dataset",
"(",
"*",
"*",
"kwargs",
")",
")",
"tokens",
"=",
"dsval",
".",
"split",
"(",
"'_'",
")",
"irf_name"... | 47.777778 | 16.555556 |
def write(graph, fileformat=None, filename=None):
"""
A basic graph writer (to stdout) for any of the sources.
this will write raw triples in rdfxml, unless specified.
to write turtle, specify format='turtle'
an optional file can be supplied instead of stdout
:return: Non... | [
"def",
"write",
"(",
"graph",
",",
"fileformat",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"filewriter",
"=",
"None",
"if",
"fileformat",
"is",
"None",
":",
"fileformat",
"=",
"'turtle'",
"if",
"filename",
"is",
"not",
"None",
":",
"with",
"... | 34.227273 | 18.5 |
def delete(self, id):
"""Delete a file.
Parameters:
* id: The Puush ID of the file to delete.
"""
res = self._api_request('del', data={'i': id})[0]
if res[0] == '-1':
raise PuushError("File deletion failed.") | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"res",
"=",
"self",
".",
"_api_request",
"(",
"'del'",
",",
"data",
"=",
"{",
"'i'",
":",
"id",
"}",
")",
"[",
"0",
"]",
"if",
"res",
"[",
"0",
"]",
"==",
"'-1'",
":",
"raise",
"PuushError",
... | 30.333333 | 14.333333 |
def managed_process(process):
"""Wrapper for subprocess.Popen to work across various Python versions, when using the with syntax."""
try:
yield process
finally:
for stream in [process.stdout, process.stdin, process.stderr]:
if stream:
stream.close()
proces... | [
"def",
"managed_process",
"(",
"process",
")",
":",
"try",
":",
"yield",
"process",
"finally",
":",
"for",
"stream",
"in",
"[",
"process",
".",
"stdout",
",",
"process",
".",
"stdin",
",",
"process",
".",
"stderr",
"]",
":",
"if",
"stream",
":",
"strea... | 35.555556 | 18.444444 |
def convert_mysql_timestamp(timestamp):
"""Convert a MySQL TIMESTAMP to a Timestamp object.
MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME:
>>> mysql_timestamp_converter('2007-02-25 22:32:17')
datetime.datetime(2007, 2, 25, 22, 32, 17)
MySQL < 4.1 uses a big string of numbers:
... | [
"def",
"convert_mysql_timestamp",
"(",
"timestamp",
")",
":",
"if",
"timestamp",
"[",
"4",
"]",
"==",
"'-'",
":",
"return",
"convert_datetime",
"(",
"timestamp",
")",
"timestamp",
"+=",
"\"0\"",
"*",
"(",
"14",
"-",
"len",
"(",
"timestamp",
")",
")",
"# ... | 33.451613 | 21.451613 |
def str_to_bitstring(data):
"""Convert a string to a list of bits"""
assert isinstance(data, bytes), "Data must be an instance of bytes"
byte_list = data_to_byte_list(data)
bit_list = [bit for data_byte in byte_list for bit in byte_to_bitstring(data_byte)]
return bit_list | [
"def",
"str_to_bitstring",
"(",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
",",
"\"Data must be an instance of bytes\"",
"byte_list",
"=",
"data_to_byte_list",
"(",
"data",
")",
"bit_list",
"=",
"[",
"bit",
"for",
"data_byte",
"in"... | 47.833333 | 18.833333 |
def _process_second_group(self, group):
"""
Process the second group of a (replace) rule.
"""
def _replace_codepoint(match):
"""
Replace the matched Unicode hex code
with the corresponding unicode character
"""
result = self._ma... | [
"def",
"_process_second_group",
"(",
"self",
",",
"group",
")",
":",
"def",
"_replace_codepoint",
"(",
"match",
")",
":",
"\"\"\"\n Replace the matched Unicode hex code\n with the corresponding unicode character\n \"\"\"",
"result",
"=",
"self",
"... | 30.842105 | 11.578947 |
def __parameter_descriptor(self, param):
"""Creates descriptor for a parameter.
Args:
param: The parameter to be described.
Returns:
Dictionary containing a descriptor for the parameter.
"""
descriptor = {}
param_type, param_format = self.__field_to_parameter_type_and_format(param... | [
"def",
"__parameter_descriptor",
"(",
"self",
",",
"param",
")",
":",
"descriptor",
"=",
"{",
"}",
"param_type",
",",
"param_format",
"=",
"self",
".",
"__field_to_parameter_type_and_format",
"(",
"param",
")",
"# Required",
"if",
"param",
".",
"required",
":",
... | 25.166667 | 21.47619 |
def rel_path(base, path):
"""Return path relative to base."""
if base == path:
return ''
assert is_prefix(base, path), "{} not a prefix of {}".format(base, path)
return path[len(base):].strip('.') | [
"def",
"rel_path",
"(",
"base",
",",
"path",
")",
":",
"if",
"base",
"==",
"path",
":",
"return",
"''",
"assert",
"is_prefix",
"(",
"base",
",",
"path",
")",
",",
"\"{} not a prefix of {}\"",
".",
"format",
"(",
"base",
",",
"path",
")",
"return",
"pat... | 35.833333 | 16 |
def callback(self, msg):
"""Accept a message that was published, process and forward
Parameters
----------
msg : tuple, (str, str, str)
The message sent over the line. The `tuple` is of the form:
(message_type, channel, payload).
Notes
-----
... | [
"def",
"callback",
"(",
"self",
",",
"msg",
")",
":",
"message_type",
",",
"channel",
",",
"payload",
"=",
"msg",
"if",
"message_type",
"!=",
"'message'",
":",
"return",
"try",
":",
"payload",
"=",
"self",
".",
"_decode",
"(",
"payload",
")",
"except",
... | 27.868421 | 19.710526 |
def fromkeys(cls, iterable, value, **kwargs):
"""
Return a new pqict mapping keys from an iterable to the same value.
"""
return cls(((k, value) for k in iterable), **kwargs) | [
"def",
"fromkeys",
"(",
"cls",
",",
"iterable",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
"(",
"(",
"(",
"k",
",",
"value",
")",
"for",
"k",
"in",
"iterable",
")",
",",
"*",
"*",
"kwargs",
")"
] | 33.666667 | 16.666667 |
def result(self):
"""Formats the result."""
return {
"count": self._count,
"total": self._total,
"average": float(self._total) / self._count if self._count else 0
} | [
"def",
"result",
"(",
"self",
")",
":",
"return",
"{",
"\"count\"",
":",
"self",
".",
"_count",
",",
"\"total\"",
":",
"self",
".",
"_total",
",",
"\"average\"",
":",
"float",
"(",
"self",
".",
"_total",
")",
"/",
"self",
".",
"_count",
"if",
"self",... | 26.857143 | 20.428571 |
def _parse_template_vars(self):
""" find all template variables in self._code, excluding the
function name.
"""
template_vars = set()
for var in parsing.find_template_variables(self._code):
var = var.lstrip('$')
if var == self.name:
contin... | [
"def",
"_parse_template_vars",
"(",
"self",
")",
":",
"template_vars",
"=",
"set",
"(",
")",
"for",
"var",
"in",
"parsing",
".",
"find_template_variables",
"(",
"self",
".",
"_code",
")",
":",
"var",
"=",
"var",
".",
"lstrip",
"(",
"'$'",
")",
"if",
"v... | 37.785714 | 10.857143 |
def _demote_all(self):
"""
Convert the multi-depth pixeldict into a single set of pixels at the deepest layer.
The result is cached, and reset when any changes are made to this region.
"""
# only do the calculations if the demoted list is empty
if len(self.demoted) == 0:... | [
"def",
"_demote_all",
"(",
"self",
")",
":",
"# only do the calculations if the demoted list is empty",
"if",
"len",
"(",
"self",
".",
"demoted",
")",
"==",
"0",
":",
"pd",
"=",
"self",
".",
"pixeldict",
"for",
"d",
"in",
"range",
"(",
"1",
",",
"self",
".... | 40 | 19.066667 |
def merge(self, other):
""" Merge all children stats. """
for this, other in zip(self.stats, other.stats):
this.merge(other) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"for",
"this",
",",
"other",
"in",
"zip",
"(",
"self",
".",
"stats",
",",
"other",
".",
"stats",
")",
":",
"this",
".",
"merge",
"(",
"other",
")"
] | 37.25 | 11 |
def get_changes(self, factory_name, global_factory=False, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get the changes this refactoring makes
`factory_name` indicates the name of the factory function to
be added. If `global_factory` is `True` the factory wil... | [
"def",
"get_changes",
"(",
"self",
",",
"factory_name",
",",
"global_factory",
"=",
"False",
",",
"resources",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"if",
"resources",
"is",
"None",
":",
"resources",
... | 47.095238 | 22.238095 |
def _ensure_slack(self, connector: Any, retries: int,
backoff: Callable[[int], float]) -> None:
""" Ensure we have a SlackClient. """
connector = self._env_var if connector is None else connector
slack: SlackClient = _create_slack(connector)
self._slack = _SlackClie... | [
"def",
"_ensure_slack",
"(",
"self",
",",
"connector",
":",
"Any",
",",
"retries",
":",
"int",
",",
"backoff",
":",
"Callable",
"[",
"[",
"int",
"]",
",",
"float",
"]",
")",
"->",
"None",
":",
"connector",
"=",
"self",
".",
"_env_var",
"if",
"connect... | 41.3 | 15.2 |
def detect_framebuffer(self, glo=None) -> 'Framebuffer':
'''
Detect framebuffer.
Args:
glo (int): Framebuffer object.
Returns:
:py:class:`Framebuffer` object
'''
res = Framebuffer.__new__(Framebuffer)
res.mglo, res._s... | [
"def",
"detect_framebuffer",
"(",
"self",
",",
"glo",
"=",
"None",
")",
"->",
"'Framebuffer'",
":",
"res",
"=",
"Framebuffer",
".",
"__new__",
"(",
"Framebuffer",
")",
"res",
".",
"mglo",
",",
"res",
".",
"_size",
",",
"res",
".",
"_samples",
",",
"res... | 28.222222 | 20.777778 |
def print_tree(
expr, attr='operands', padding='', exclude_type=None, depth=None,
unicode=True, srepr_leaves=False, _last=False, _root=True, _level=0,
_print=True):
"""Print a tree representation of the structure of `expr`
Args:
expr (Expression): expression to render
at... | [
"def",
"print_tree",
"(",
"expr",
",",
"attr",
"=",
"'operands'",
",",
"padding",
"=",
"''",
",",
"exclude_type",
"=",
"None",
",",
"depth",
"=",
"None",
",",
"unicode",
"=",
"True",
",",
"srepr_leaves",
"=",
"False",
",",
"_last",
"=",
"False",
",",
... | 39.158537 | 19.52439 |
def strip_praw_submission(cls, sub):
"""
Parse through a submission and return a dict with data ready to be
displayed through the terminal.
Definitions:
permalink - URL to the reddit page with submission comments.
url_full - URL that the submission points to.
... | [
"def",
"strip_praw_submission",
"(",
"cls",
",",
"sub",
")",
":",
"reddit_link",
"=",
"re",
".",
"compile",
"(",
"r'https?://(www\\.)?(np\\.)?redd(it\\.com|\\.it)/r/.*'",
")",
"author",
"=",
"getattr",
"(",
"sub",
",",
"'author'",
",",
"'[deleted]'",
")",
"name",
... | 41.463768 | 16.304348 |
def show_plane(orig, n, scale=1.0, **kwargs):
"""
Show the plane with the given origin and normal. scale give its size
"""
b1 = orthogonal_vector(n)
b1 /= la.norm(b1)
b2 = np.cross(b1, n)
b2 /= la.norm(b2)
verts = [orig + scale*(-b1 - b2),
orig + scale*(b1 - b2),
... | [
"def",
"show_plane",
"(",
"orig",
",",
"n",
",",
"scale",
"=",
"1.0",
",",
"*",
"*",
"kwargs",
")",
":",
"b1",
"=",
"orthogonal_vector",
"(",
"n",
")",
"b1",
"/=",
"la",
".",
"norm",
"(",
"b1",
")",
"b2",
"=",
"np",
".",
"cross",
"(",
"b1",
"... | 32.357143 | 9.214286 |
def getparam(self, name, default=None, parents=False):
'''A parameter in this :class:`.Router`
'''
value = getattr(self, name, None)
if value is None:
if parents and self._parent:
return self._parent.getparam(name, default, parents)
else:
... | [
"def",
"getparam",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"parents",
"=",
"False",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"name",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"if",
"parents",
"and",
"self",... | 33.636364 | 15.454545 |
def group(self, group_type=None, owner=None, **kwargs):
"""
Create the Group TI object.
Args:
owner:
group_type:
**kwargs:
Return:
"""
group = None
if not group_type:
return Group(self.tcex, None, None, owner=own... | [
"def",
"group",
"(",
"self",
",",
"group_type",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"group",
"=",
"None",
"if",
"not",
"group_type",
":",
"return",
"Group",
"(",
"self",
".",
"tcex",
",",
"None",
",",
"None",
... | 33.985507 | 15.898551 |
def export_dist(self, args):
"""Copies a created dist to an output dir.
This makes it easy to navigate to the dist to investigate it
or call build.py, though you do not in general need to do this
and can use the apk command instead.
"""
ctx = self.ctx
dist = dist... | [
"def",
"export_dist",
"(",
"self",
",",
"args",
")",
":",
"ctx",
"=",
"self",
".",
"ctx",
"dist",
"=",
"dist_from_args",
"(",
"ctx",
",",
"args",
")",
"if",
"dist",
".",
"needs_build",
":",
"raise",
"BuildInterruptingException",
"(",
"'You asked to export a ... | 42.722222 | 17.666667 |
def in6_isllsnmaddr(str):
"""
Return True if provided address is a link-local solicited node
multicast address, i.e. belongs to ff02::1:ff00:0/104. False is
returned otherwise.
"""
temp = in6_and(b"\xff" * 13 + b"\x00" * 3, inet_pton(socket.AF_INET6, str))
temp2 = b'\xff\x02\x00\x00\x00\x00\... | [
"def",
"in6_isllsnmaddr",
"(",
"str",
")",
":",
"temp",
"=",
"in6_and",
"(",
"b\"\\xff\"",
"*",
"13",
"+",
"b\"\\x00\"",
"*",
"3",
",",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"str",
")",
")",
"temp2",
"=",
"b'\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x... | 41.888889 | 19.888889 |
def from_manifest(app, filename, raw=False, **kwargs):
'''
Get the path to a static file for a given app entry of a given type.
:param str app: The application key to which is tied this manifest
:param str filename: the original filename (without hash)
:param bool raw: if True, doesn't add prefix t... | [
"def",
"from_manifest",
"(",
"app",
",",
"filename",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"current_app",
".",
"config",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'TESTING'",
")",
":",
"return",
"# Do not ... | 39.5 | 22.142857 |
def require_captcha(function, *args, **kwargs):
"""Return a decorator for methods that require captchas."""
raise_captcha_exception = kwargs.pop('raise_captcha_exception', False)
captcha_id = None
# Get a handle to the reddit session
if hasattr(args[0], 'reddit_session'):
reddit_session = a... | [
"def",
"require_captcha",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise_captcha_exception",
"=",
"kwargs",
".",
"pop",
"(",
"'raise_captcha_exception'",
",",
"False",
")",
"captcha_id",
"=",
"None",
"# Get a handle to the reddit sess... | 43.529412 | 19.676471 |
def _set_valid_lifetime(self, v, load=False):
"""
Setter method for valid_lifetime, mapped from YANG variable /interface/fortygigabitethernet/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/prefix/lifetime/valid_lifetime (common-def:time-interval-sec)
If this variable is read-only (config: false) in the
source YANG f... | [
"def",
"_set_valid_lifetime",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | 104.181818 | 51.045455 |
def from_api_repr(cls, resource, client):
"""Factory: construct a project given its API representation.
:type resource: dict
:param resource: project resource representation returned from the API
:type client: :class:`google.cloud.resource_manager.client.Client`
:param client:... | [
"def",
"from_api_repr",
"(",
"cls",
",",
"resource",
",",
"client",
")",
":",
"project",
"=",
"cls",
"(",
"project_id",
"=",
"resource",
"[",
"\"projectId\"",
"]",
",",
"client",
"=",
"client",
")",
"project",
".",
"set_properties_from_api_repr",
"(",
"resou... | 40.866667 | 21.066667 |
def _to_docstring(doc):
"""
format from Markdown to docstring
"""
def format_fn(line, status):
""" format function """
# swap < > to < >
line = re_to_tag.sub(r"<\1>", line)
if re_to_data.match(line):
line = re_to_data.sub(r"@\1 ", line)
stat... | [
"def",
"_to_docstring",
"(",
"doc",
")",
":",
"def",
"format_fn",
"(",
"line",
",",
"status",
")",
":",
"\"\"\" format function \"\"\"",
"# swap < > to < >",
"line",
"=",
"re_to_tag",
".",
"sub",
"(",
"r\"<\\1>\"",
",",
"line",
")",
"if",
"re_to_data",
"... | 31.931034 | 10.862069 |
def _get_db_refs(term):
"""Extract database references for a TERM."""
db_refs = {}
# Here we extract the text name of the Agent
# There are two relevant tags to consider here.
# The <text> tag typically contains a larger phrase surrounding the
# term but it contains the term in a raw, non-canoni... | [
"def",
"_get_db_refs",
"(",
"term",
")",
":",
"db_refs",
"=",
"{",
"}",
"# Here we extract the text name of the Agent",
"# There are two relevant tags to consider here.",
"# The <text> tag typically contains a larger phrase surrounding the",
"# term but it contains the term in a raw, non-c... | 40.55 | 17.38125 |
def random_mini_batches(X, Y, minibatch_size, seed=None):
"""
Compute a list of minibatches from inputs X and targets Y.
A datapoint is expected to be represented as a column in
the data matrices X and Y.
"""
d = X.shape[1]
size = minibatch_size
minibatches = []
if Y is None:
Y = np.zeros((... | [
"def",
"random_mini_batches",
"(",
"X",
",",
"Y",
",",
"minibatch_size",
",",
"seed",
"=",
"None",
")",
":",
"d",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"size",
"=",
"minibatch_size",
"minibatches",
"=",
"[",
"]",
"if",
"Y",
"is",
"None",
":",
"Y",... | 23.952381 | 19.380952 |
def set_gender(self, gender=None):
"""This model recognizes that sex chromosomes don't always line up with
gender. Assign M, F, or NB according to the probabilities in p_gender.
"""
if gender and gender in genders:
self.gender = gender
else:
if not self.ch... | [
"def",
"set_gender",
"(",
"self",
",",
"gender",
"=",
"None",
")",
":",
"if",
"gender",
"and",
"gender",
"in",
"genders",
":",
"self",
".",
"gender",
"=",
"gender",
"else",
":",
"if",
"not",
"self",
".",
"chromosomes",
":",
"self",
".",
"set_chromosome... | 47.222222 | 15.222222 |
def get_item(self, path):
"""
Get resource item
:param path: string
:return: PIL.Image
"""
if self.source_folder:
item_path = '%s/%s/%s' % (
current_app.static_folder,
self.source_folder,
path.strip('... | [
"def",
"get_item",
"(",
"self",
",",
"path",
")",
":",
"if",
"self",
".",
"source_folder",
":",
"item_path",
"=",
"'%s/%s/%s'",
"%",
"(",
"current_app",
".",
"static_folder",
",",
"self",
".",
"source_folder",
",",
"path",
".",
"strip",
"(",
"'/'",
")",
... | 29.692308 | 13.923077 |
def check_namespace_availability(self, name):
'''
Checks to see if the specified service bus namespace is available, or
if it has already been taken.
name:
Name of the service bus namespace to validate.
'''
_validate_not_none('name', name)
response =... | [
"def",
"check_namespace_availability",
"(",
"self",
",",
"name",
")",
":",
"_validate_not_none",
"(",
"'name'",
",",
"name",
")",
"response",
"=",
"self",
".",
"_perform_get",
"(",
"self",
".",
"_get_path",
"(",
"'services/serviceBus/CheckNamespaceAvailability'",
",... | 36.25 | 24.375 |
def load(cls, path):
"""
load DictTree from json files.
"""
try:
with open(path, "rb") as f:
return cls(__data__=json.loads(f.read().decode("utf-8")))
except:
pass
with open(path, "rb") as f:
return cls(__data__=pickle.... | [
"def",
"load",
"(",
"cls",
",",
"path",
")",
":",
"try",
":",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"return",
"cls",
"(",
"__data__",
"=",
"json",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
".",
"decode",
"(",
"... | 26.416667 | 15.416667 |
def example_lab_to_xyz():
"""
This function shows a simple conversion of an Lab color to an XYZ color.
"""
print("=== Simple Example: Lab->XYZ ===")
# Instantiate an Lab color object with the given values.
lab = LabColor(0.903, 16.296, -2.22)
# Show a string representation.
print(lab)
... | [
"def",
"example_lab_to_xyz",
"(",
")",
":",
"print",
"(",
"\"=== Simple Example: Lab->XYZ ===\"",
")",
"# Instantiate an Lab color object with the given values.",
"lab",
"=",
"LabColor",
"(",
"0.903",
",",
"16.296",
",",
"-",
"2.22",
")",
"# Show a string representation.",
... | 29.714286 | 14.285714 |
def setContext(self, value = .5):
"""
Clears the context layer by setting context layer to (default) value 0.5.
"""
for context in list(self.contextLayers.values()):
context.resetFlags() # hidden activations have already been copied in
context.setActivations(valu... | [
"def",
"setContext",
"(",
"self",
",",
"value",
"=",
".5",
")",
":",
"for",
"context",
"in",
"list",
"(",
"self",
".",
"contextLayers",
".",
"values",
"(",
")",
")",
":",
"context",
".",
"resetFlags",
"(",
")",
"# hidden activations have already been copied ... | 45.142857 | 15.428571 |
def filter_list_by_indices(lst, indices):
"""Return a modified list containing only the indices indicated.
Args:
lst: Original list of values
indices: List of indices to keep from the original list
Returns:
list: Filtered list of values
"""
return [x for i, x in enumerate(... | [
"def",
"filter_list_by_indices",
"(",
"lst",
",",
"indices",
")",
":",
"return",
"[",
"x",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"lst",
")",
"if",
"i",
"in",
"indices",
"]"
] | 27.5 | 18.916667 |
def set_pkg_supplier(self, doc, entity):
"""Sets the package supplier, if not already set.
entity - Organization, Person or NoAssert.
Raises CardinalityError if already has a supplier.
Raises OrderError if no package previously defined.
"""
self.assert_package_exists()
... | [
"def",
"set_pkg_supplier",
"(",
"self",
",",
"doc",
",",
"entity",
")",
":",
"self",
".",
"assert_package_exists",
"(",
")",
"if",
"not",
"self",
".",
"package_supplier_set",
":",
"self",
".",
"package_supplier_set",
"=",
"True",
"if",
"validations",
".",
"v... | 41.6875 | 10.8125 |
def make_request(self, data, is_json=True):
"""
Makes a HTTP request to GCM servers with the constructed payload
:param data: return value from construct_payload method
:raises GCMMalformedJsonException: if malformed JSON request found
:raises GCMAuthenticationException: if ther... | [
"def",
"make_request",
"(",
"self",
",",
"data",
",",
"is_json",
"=",
"True",
")",
":",
"# Default Content-Type is",
"# application/x-www-form-urlencoded;charset=UTF-8",
"if",
"is_json",
":",
"self",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'... | 37.309524 | 18.166667 |
def stop(host=None, port=None):
"""stop of web server"""
app.config['HOST'] = first_value(host, app.config.get('HOST',None), '0.0.0.0')
app.config['PORT'] = int(first_value(port, app.config.get('PORT',None), 5001))
if app.config['HOST'] == "0.0.0.0":
host="127.0.0.1"
else:
ho... | [
"def",
"stop",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"app",
".",
"config",
"[",
"'HOST'",
"]",
"=",
"first_value",
"(",
"host",
",",
"app",
".",
"config",
".",
"get",
"(",
"'HOST'",
",",
"None",
")",
",",
"'0.0.0.0'",
")",... | 44.764706 | 23.058824 |
def _create_driver(self, **kwargs):
"""
Create webdriver, assign it to ``self.driver``, and run webdriver
initiation process, which is usually used for manual login.
"""
if self.driver is None:
self.driver = self.create_driver(**kwargs)
self.init_driver_fu... | [
"def",
"_create_driver",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"driver",
"is",
"None",
":",
"self",
".",
"driver",
"=",
"self",
".",
"create_driver",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"init_driver_func",
"(",
"se... | 41 | 11.75 |
def decode(self, bytes):
"""Decodes the given bytes according to this AIT Command
Definition.
"""
opcode = struct.unpack(">H", bytes[0:2])[0]
nbytes = struct.unpack("B", bytes[2:3])[0]
name = None
args = []
if opcode in self.opcodes:
de... | [
"def",
"decode",
"(",
"self",
",",
"bytes",
")",
":",
"opcode",
"=",
"struct",
".",
"unpack",
"(",
"\">H\"",
",",
"bytes",
"[",
"0",
":",
"2",
"]",
")",
"[",
"0",
"]",
"nbytes",
"=",
"struct",
".",
"unpack",
"(",
"\"B\"",
",",
"bytes",
"[",
"2"... | 30.956522 | 15.695652 |
def deepcopy(self):
"""
Create a deep copy of the Heatmaps object.
Returns
-------
imgaug.HeatmapsOnImage
Deep copy.
"""
return HeatmapsOnImage(self.get_arr(), shape=self.shape, min_value=self.min_value, max_value=self.max_value) | [
"def",
"deepcopy",
"(",
"self",
")",
":",
"return",
"HeatmapsOnImage",
"(",
"self",
".",
"get_arr",
"(",
")",
",",
"shape",
"=",
"self",
".",
"shape",
",",
"min_value",
"=",
"self",
".",
"min_value",
",",
"max_value",
"=",
"self",
".",
"max_value",
")"... | 26.272727 | 24.090909 |
def register_bootstrap_functions():
'''Discover and register all post import hooks named in the
'AUTOWRAPT_BOOTSTRAP' environment variable. The value of the
environment variable must be a comma separated list.
'''
# This can be called twice if '.pth' file bootstrapping works and
# the 'autowra... | [
"def",
"register_bootstrap_functions",
"(",
")",
":",
"# This can be called twice if '.pth' file bootstrapping works and",
"# the 'autowrapt' wrapper script is still also used. We therefore",
"# protect ourselves just in case it is called a second time as we",
"# only want to force registration once... | 32.925926 | 25.666667 |
def run(self, data, max_epochs=1):
"""Runs the process_function over the passed data.
Args:
data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`).
max_epochs (int, optional): max epochs to run for (default: 1).
Returns:
... | [
"def",
"run",
"(",
"self",
",",
"data",
",",
"max_epochs",
"=",
"1",
")",
":",
"self",
".",
"state",
"=",
"State",
"(",
"dataloader",
"=",
"data",
",",
"epoch",
"=",
"0",
",",
"max_epochs",
"=",
"max_epochs",
",",
"metrics",
"=",
"{",
"}",
")",
"... | 42.638889 | 26.222222 |
def _create_file_racefree(self, file):
"""
Creates a file, but fails if the file already exists.
This function will thus only succeed if this process actually creates
the file; if the file already exists, it will cause an OSError,
solving race conditions.
:par... | [
"def",
"_create_file_racefree",
"(",
"self",
",",
"file",
")",
":",
"write_lock_flags",
"=",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_EXCL",
"|",
"os",
".",
"O_WRONLY",
"os",
".",
"open",
"(",
"file",
",",
"write_lock_flags",
")"
] | 37.75 | 16.416667 |
def get_registration_id_info(self, registration_id):
"""
Returns details related to a registration id if it exists otherwise return None
Args:
registration_id: id to be checked
Returns:
dict: info about registration id
None: if id doesn't exist
... | [
"def",
"get_registration_id_info",
"(",
"self",
",",
"registration_id",
")",
":",
"response",
"=",
"self",
".",
"registration_info_request",
"(",
"registration_id",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"response",
".",
"json",
"... | 31.6 | 17.066667 |
def inventory(self, all=False, ssid=None):
"""
Returns a node inventory. If an API key is specified, only the nodes
provisioned by this key will be returned.
:return: { inventory }
"""
if all or self.api_key is None:
if ssid is not None:
retu... | [
"def",
"inventory",
"(",
"self",
",",
"all",
"=",
"False",
",",
"ssid",
"=",
"None",
")",
":",
"if",
"all",
"or",
"self",
".",
"api_key",
"is",
"None",
":",
"if",
"ssid",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_ssid_inventory",
"(",
"sel... | 34.941176 | 14.823529 |
def off_datastream(self, datastream):
"""
To turn off datastream
:param datastream: string
"""
url = '/datastream/' + str(datastream) + '/off'
response = self.http.post(url,"")
return response | [
"def",
"off_datastream",
"(",
"self",
",",
"datastream",
")",
":",
"url",
"=",
"'/datastream/'",
"+",
"str",
"(",
"datastream",
")",
"+",
"'/off'",
"response",
"=",
"self",
".",
"http",
".",
"post",
"(",
"url",
",",
"\"\"",
")",
"return",
"response"
] | 30.125 | 6.625 |
def setOptimizedForIPTV(self, status, wifiInterfaceId=1, timeout=1):
"""Set if the Wifi interface is optimized for IP TV
:param bool status: set if Wifi interface should be optimized
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for t... | [
"def",
"setOptimizedForIPTV",
"(",
"self",
",",
"status",
",",
"wifiInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Fritz",
".",
"getServiceType",
"(",
"\"setOptimizedForIPTV\"",
")",
"+",
"str",
"(",
"wifiInterfaceId",
")",
"u... | 39.5 | 27.9 |
async def dispatch(self, request, view=None, **kwargs):
"""Dispatch request."""
if view is None and request.method not in self.methods:
raise HTTPMethodNotAllowed(request.method, self.methods)
method = getattr(self, view or request.method.lower())
response = await method(req... | [
"async",
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"view",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"view",
"is",
"None",
"and",
"request",
".",
"method",
"not",
"in",
"self",
".",
"methods",
":",
"raise",
"HTTPMethodNotAllowed"... | 48.375 | 19.5 |
def src_file(self):
"""
Get the latest src_uri for a stage 3 tarball.
Returns (str):
Latest src_uri from gentoo's distfiles mirror.
"""
try:
src_uri = (curl[Gentoo._LATEST_TXT] | tail["-n", "+3"]
| cut["-f1", "-d "])().strip()
... | [
"def",
"src_file",
"(",
"self",
")",
":",
"try",
":",
"src_uri",
"=",
"(",
"curl",
"[",
"Gentoo",
".",
"_LATEST_TXT",
"]",
"|",
"tail",
"[",
"\"-n\"",
",",
"\"+3\"",
"]",
"|",
"cut",
"[",
"\"-f1\"",
",",
"\"-d \"",
"]",
")",
"(",
")",
".",
"strip... | 34.2 | 16.333333 |
def to_add_link(self, ):
'''
To add link
'''
if self.check_post_role()['ADD']:
pass
else:
return False
kwd = {
'pager': '',
'uid': '',
}
self.render('misc/link/link_add.html',
topmenu='',
... | [
"def",
"to_add_link",
"(",
"self",
",",
")",
":",
"if",
"self",
".",
"check_post_role",
"(",
")",
"[",
"'ADD'",
"]",
":",
"pass",
"else",
":",
"return",
"False",
"kwd",
"=",
"{",
"'pager'",
":",
"''",
",",
"'uid'",
":",
"''",
",",
"}",
"self",
".... | 23.6875 | 17.8125 |
def complete(self, match, subject_graph):
"""Check the completeness of the ring match"""
if not CustomPattern.complete(self, match, subject_graph):
return False
if self.strong:
# If the ring is not strong, return False
if self.size % 2 == 0:
# ... | [
"def",
"complete",
"(",
"self",
",",
"match",
",",
"subject_graph",
")",
":",
"if",
"not",
"CustomPattern",
".",
"complete",
"(",
"self",
",",
"match",
",",
"subject_graph",
")",
":",
"return",
"False",
"if",
"self",
".",
"strong",
":",
"# If the ring is n... | 50.694444 | 17.916667 |
def _closure_createlink(self):
"""Create a link in the closure tree."""
linkparents = self._closure_model.objects.filter(
child__pk=self._closure_parent_pk
).values("parent", "depth")
linkchildren = self._closure_model.objects.filter(
parent__pk=self.pk
).... | [
"def",
"_closure_createlink",
"(",
"self",
")",
":",
"linkparents",
"=",
"self",
".",
"_closure_model",
".",
"objects",
".",
"filter",
"(",
"child__pk",
"=",
"self",
".",
"_closure_parent_pk",
")",
".",
"values",
"(",
"\"parent\"",
",",
"\"depth\"",
")",
"li... | 42.428571 | 8.285714 |
def get_absolute_path(some_path):
"""
This function will return an appropriate absolute path for the path it is
given. If the input is absolute, it will return unmodified; if the input is
relative, it will be rendered as relative to the current working directory.
"""
if os.path.isabs(some_path):... | [
"def",
"get_absolute_path",
"(",
"some_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"some_path",
")",
":",
"return",
"some_path",
"else",
":",
"return",
"evaluate_relative_path",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"some_path",
")"
] | 40.8 | 19.8 |
def _add_thread(self, aThread):
"""
Private method to add a thread object to the snapshot.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
## if not isinstance(aThread, Thread):
## if hasattr(aThread, '__class__'):
## typename = aThr... | [
"def",
"_add_thread",
"(",
"self",
",",
"aThread",
")",
":",
"## if not isinstance(aThread, Thread):",
"## if hasattr(aThread, '__class__'):",
"## typename = aThread.__class__.__name__",
"## else:",
"## typename = str(type(aThread))"... | 38.4 | 11.3 |
def log_rmtree_error(func, arg, exc_info):
"""Suited as onerror handler for (sh)util.rmtree() that logs a warning."""
logging.warning("Failure during '%s(%s)': %s", func.__name__, arg, exc_info[1]) | [
"def",
"log_rmtree_error",
"(",
"func",
",",
"arg",
",",
"exc_info",
")",
":",
"logging",
".",
"warning",
"(",
"\"Failure during '%s(%s)': %s\"",
",",
"func",
".",
"__name__",
",",
"arg",
",",
"exc_info",
"[",
"1",
"]",
")"
] | 67.666667 | 15 |
def monthly_wind_conditions(self):
"""A list of 12 monthly wind conditions that are used on the design days."""
return [WindCondition(x, y) for x, y in zip(
self._monthly_wind, self.monthly_wind_dirs)] | [
"def",
"monthly_wind_conditions",
"(",
"self",
")",
":",
"return",
"[",
"WindCondition",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"self",
".",
"_monthly_wind",
",",
"self",
".",
"monthly_wind_dirs",
")",
"]"
] | 56.5 | 8.5 |
def get_keysym(conn, keycode, col=0, kbmap=None):
"""
Get the keysym associated with a particular keycode in the current X
environment. Although we get a list of keysyms from X in
'get_keyboard_mapping', this list is really a table with
'keysys_per_keycode' columns and ``mx - mn`` rows (where ``mx``... | [
"def",
"get_keysym",
"(",
"conn",
",",
"keycode",
",",
"col",
"=",
"0",
",",
"kbmap",
"=",
"None",
")",
":",
"if",
"kbmap",
"is",
"None",
":",
"kbmap",
"=",
"__kbmap",
"mn",
",",
"mx",
"=",
"get_min_max_keycode",
"(",
"conn",
")",
"per",
"=",
"kbma... | 35.916667 | 20.138889 |
def __read_and_render_yaml_file(source,
template,
saltenv):
'''
Read a yaml file and, if needed, renders that using the specifieds
templating. Returns the python objects defined inside of the file.
'''
sfn = __salt__['cp.cache_file'](so... | [
"def",
"__read_and_render_yaml_file",
"(",
"source",
",",
"template",
",",
"saltenv",
")",
":",
"sfn",
"=",
"__salt__",
"[",
"'cp.cache_file'",
"]",
"(",
"source",
",",
"saltenv",
")",
"if",
"not",
"sfn",
":",
"raise",
"CommandExecutionError",
"(",
"'Source fi... | 37.5 | 17.045455 |
def eval(self, expr, n, extra_constraints=(), solver=None, model_callback=None):
"""
This function returns up to `n` possible solutions for expression `expr`.
:param expr: expression (an AST) to evaluate
:param n: number of results to return
:param solver: a solver object, nativ... | [
"def",
"eval",
"(",
"self",
",",
"expr",
",",
"n",
",",
"extra_constraints",
"=",
"(",
")",
",",
"solver",
"=",
"None",
",",
"model_callback",
"=",
"None",
")",
":",
"if",
"self",
".",
"_solver_required",
"and",
"solver",
"is",
"None",
":",
"raise",
... | 41.78125 | 26.21875 |
def tokenize(self, s):
"""Return a list of token strings from the given sentence.
:param string s: The sentence string to tokenize.
:rtype: iter(str)
"""
return [s[start:end] for start, end in self.span_tokenize(s)] | [
"def",
"tokenize",
"(",
"self",
",",
"s",
")",
":",
"return",
"[",
"s",
"[",
"start",
":",
"end",
"]",
"for",
"start",
",",
"end",
"in",
"self",
".",
"span_tokenize",
"(",
"s",
")",
"]"
] | 35.714286 | 17 |
def get_contents_as_string(self, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
response_headers=None, callback=None):
"""
Retrieve an object from S3 using the n... | [
"def",
"get_contents_as_string",
"(",
"self",
",",
"headers",
"=",
"None",
",",
"cb",
"=",
"None",
",",
"num_cb",
"=",
"10",
",",
"torrent",
"=",
"False",
",",
"version_id",
"=",
"None",
",",
"response_headers",
"=",
"None",
",",
"callback",
"=",
"None",... | 46.44898 | 22.367347 |
def plotConvergenceByColumnTopology(results, columnRange, featureRange, networkType, numTrials):
"""
Plots the convergence graph: iterations vs number of columns.
Each curve shows the convergence for a given number of unique features.
"""
#######################################################################... | [
"def",
"plotConvergenceByColumnTopology",
"(",
"results",
",",
"columnRange",
",",
"featureRange",
",",
"networkType",
",",
"numTrials",
")",
":",
"########################################################################",
"#",
"# Accumulate all the results per column in a convergenc... | 34.738462 | 22.676923 |
def read(fn, **kwargs):
"""
Convenience function: Detect file extension and read via Atomistica or ASE.
If reading a NetCDF files, frame numbers can be appended via '@'.
e.g., a = read('traj.nc@5')
"""
ext = fn[fn.rfind('.'):].split('@')
if len(ext) == 1:
if ext[0] == '.out' or ext[0... | [
"def",
"read",
"(",
"fn",
",",
"*",
"*",
"kwargs",
")",
":",
"ext",
"=",
"fn",
"[",
"fn",
".",
"rfind",
"(",
"'.'",
")",
":",
"]",
".",
"split",
"(",
"'@'",
")",
"if",
"len",
"(",
"ext",
")",
"==",
"1",
":",
"if",
"ext",
"[",
"0",
"]",
... | 33.483871 | 11.096774 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.