text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _do_layout(self, data):
"""
Lays the text out into separate lines and calculates their
total height.
"""
c = data['output']
word_space = c.text_width(
' ',
font_name=self.font_name,
font_size=self.font_size)
# Arrange the t... | [
"def",
"_do_layout",
"(",
"self",
",",
"data",
")",
":",
"c",
"=",
"data",
"[",
"'output'",
"]",
"word_space",
"=",
"c",
".",
"text_width",
"(",
"' '",
",",
"font_name",
"=",
"self",
".",
"font_name",
",",
"font_size",
"=",
"self",
".",
"font_size",
... | 31.0625 | 0.001951 |
def _timed(_logger=None, level="info"):
"""
Output execution time of a function to the given logger level
level : str
On which level to log the performance measurement
Returns
-------
fun_wrapper : Callable
"""
def fun_wrapper(f):
@functools.wraps(f)
def wraps(*... | [
"def",
"_timed",
"(",
"_logger",
"=",
"None",
",",
"level",
"=",
"\"info\"",
")",
":",
"def",
"fun_wrapper",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wraps",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | 23.809524 | 0.001923 |
def find_git_repository(self, path):
"""
Tries to find a directory with a .git repository
"""
while path is not None:
git_path = os.path.join(path,'.git')
if os.path.exists(git_path) and os.path.isdir(git_path):
return path
path = os.pa... | [
"def",
"find_git_repository",
"(",
"self",
",",
"path",
")",
":",
"while",
"path",
"is",
"not",
"None",
":",
"git_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'.git'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"git_path",
... | 34.7 | 0.008427 |
def _logistic_cost_loss(w, X, y, cost_mat, alpha):
"""Computes the logistic loss.
Parameters
----------
w : array-like, shape (n_w, n_features,) or (n_w, n_features + 1,)
Coefficient vector or matrix of coefficient.
X : array-like, shape (n_samples, n_features)
Training data.
... | [
"def",
"_logistic_cost_loss",
"(",
"w",
",",
"X",
",",
"y",
",",
"cost_mat",
",",
"alpha",
")",
":",
"if",
"w",
".",
"shape",
"[",
"0",
"]",
"==",
"w",
".",
"size",
":",
"# Only evaluating one w",
"return",
"_logistic_cost_loss_i",
"(",
"w",
",",
"X",
... | 26.292683 | 0.001789 |
def compute_trip_activity(feed: "Feed", dates: List[str]) -> DataFrame:
"""
Mark trip as active or inactive on the given dates as computed
by :func:`is_active_trip`.
Parameters
----------
feed : Feed
dates : string or list
A YYYYMMDD date string or list thereof indicating the date(s... | [
"def",
"compute_trip_activity",
"(",
"feed",
":",
"\"Feed\"",
",",
"dates",
":",
"List",
"[",
"str",
"]",
")",
"->",
"DataFrame",
":",
"dates",
"=",
"feed",
".",
"restrict_dates",
"(",
"dates",
")",
"if",
"not",
"dates",
":",
"return",
"pd",
".",
"Data... | 25.808511 | 0.000794 |
def motor_primitive(self, m):
""" Prepare the movement from a command m. To be overridded in order to generate more complex movement (tutorial to come). This version simply bounds the command.
"""
return bounds_min_max(m, self.conf.m_mins, self.conf.m_maxs) | [
"def",
"motor_primitive",
"(",
"self",
",",
"m",
")",
":",
"return",
"bounds_min_max",
"(",
"m",
",",
"self",
".",
"conf",
".",
"m_mins",
",",
"self",
".",
"conf",
".",
"m_maxs",
")"
] | 69.5 | 0.010676 |
def _cellrepr(value, allow_formulas):
"""
Get a string representation of dataframe value.
:param :value: the value to represent
:param :allow_formulas: if True, allow values starting with '='
to be interpreted as formulas; otherwise, escape
them with an apostrophe to avoid formu... | [
"def",
"_cellrepr",
"(",
"value",
",",
"allow_formulas",
")",
":",
"if",
"pd",
".",
"isnull",
"(",
"value",
")",
"is",
"True",
":",
"return",
"\"\"",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"value",
"=",
"repr",
"(",
"value",
")",
... | 32.222222 | 0.001675 |
def pad_dialogues(self, dialogues):
"""
Pad the entire dataset.
This involves adding padding at the end of each sentence, and in the case of
a hierarchical model, it also involves adding padding at the end of each dialogue,
so that every training sample (dialogue) has the same di... | [
"def",
"pad_dialogues",
"(",
"self",
",",
"dialogues",
")",
":",
"self",
".",
"log",
"(",
"'info'",
",",
"'Padding the dialogues ...'",
")",
"return",
"[",
"self",
".",
"pad_dialogue",
"(",
"d",
")",
"for",
"d",
"in",
"dialogues",
"]"
] | 45.9 | 0.012821 |
def set_style(self):
"""
Set font style with the following attributes:
'foreground_color', 'background_color', 'italic',
'bold' and 'underline'
"""
if self.current_format is None:
assert self.base_format is not None
self.current_format = QTextCharF... | [
"def",
"set_style",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_format",
"is",
"None",
":",
"assert",
"self",
".",
"base_format",
"is",
"not",
"None",
"self",
".",
"current_format",
"=",
"QTextCharFormat",
"(",
"self",
".",
"base_format",
")",
"# Fo... | 34.659091 | 0.001276 |
def split(self, text):
'''
Splits the text with function arguments into the array with first
class citizens separated. See the unit tests for clarificatin.
'''
# nesting character -> count
counters = {"'": False, '(': 0}
def reverse(char):
def wrappe... | [
"def",
"split",
"(",
"self",
",",
"text",
")",
":",
"# nesting character -> count",
"counters",
"=",
"{",
"\"'\"",
":",
"False",
",",
"'('",
":",
"0",
"}",
"def",
"reverse",
"(",
"char",
")",
":",
"def",
"wrapped",
"(",
")",
":",
"counters",
"[",
"ch... | 26.392405 | 0.001849 |
def expand_user(path):
"""Expands ~/path to /home/<current_user>/path
On POSIX systems does it by getting the home directory for the
current effective user from the passwd database. On other systems
do it by using :func:`os.path.expanduser`
Args:
path (str): A path to expand to a user's ho... | [
"def",
"expand_user",
"(",
"path",
")",
":",
"if",
"not",
"path",
".",
"startswith",
"(",
"'~'",
")",
":",
"return",
"path",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"user",
"=",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"geteuid",
"(",
")",
... | 27.619048 | 0.001667 |
def parseGameTree(self):
""" Called when "(" encountered, ends when a matching ")" encountered.
Parses and returns one 'GameTree' from 'self.data'. Raises
'GameTreeParseError' if a problem is encountered."""
g = GameTree()
while self.index < self.datalen:
match = self.reGameTreeNext.match(self.data, self... | [
"def",
"parseGameTree",
"(",
"self",
")",
":",
"g",
"=",
"GameTree",
"(",
")",
"while",
"self",
".",
"index",
"<",
"self",
".",
"datalen",
":",
"match",
"=",
"self",
".",
"reGameTreeNext",
".",
"match",
"(",
"self",
".",
"data",
",",
"self",
".",
"... | 37.47619 | 0.027261 |
def git_clean(ctx):
"""
Delete all files untracked by git.
:param ctx: Context object.
:return: None.
"""
# Get command parts
cmd_part_s = [
# Program path
'git',
# Clean untracked files
'clean',
# Remove all untracked files
'-x',
... | [
"def",
"git_clean",
"(",
"ctx",
")",
":",
"# Get command parts",
"cmd_part_s",
"=",
"[",
"# Program path",
"'git'",
",",
"# Clean untracked files",
"'clean'",
",",
"# Remove all untracked files",
"'-x'",
",",
"# Remove untracked directories too",
"'-d'",
",",
"# Force to ... | 19.395349 | 0.001142 |
def get_posts_with_limits(self, include_draft=False, **limits):
"""
Get all posts and filter them as needed.
:param include_draft: return draft posts or not
:param limits: other limits to the attrs of the result,
should be a dict with string or list values
... | [
"def",
"get_posts_with_limits",
"(",
"self",
",",
"include_draft",
"=",
"False",
",",
"*",
"*",
"limits",
")",
":",
"filter_funcs",
"=",
"[",
"]",
"for",
"attr",
"in",
"(",
"'title'",
",",
"'layout'",
",",
"'author'",
",",
"'email'",
",",
"'tags'",
",",
... | 42.434783 | 0.001502 |
def get_readonly_fields(self, request, obj=None):
"""Set all fields readonly."""
return list(self.readonly_fields) + [field.name for field in obj._meta.fields] | [
"def",
"get_readonly_fields",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"return",
"list",
"(",
"self",
".",
"readonly_fields",
")",
"+",
"[",
"field",
".",
"name",
"for",
"field",
"in",
"obj",
".",
"_meta",
".",
"fields",
"]"
] | 57.666667 | 0.017143 |
def checkpoint(self):
"""
Update the database to reflect in-memory changes made to this item; for
example, to make it show up in store.query() calls where it is now
valid, but was not the last time it was persisted to the database.
This is called automatically when in 'autocommi... | [
"def",
"checkpoint",
"(",
"self",
")",
":",
"if",
"self",
".",
"store",
"is",
"None",
":",
"raise",
"NotInStore",
"(",
"\"You can't checkpoint %r: not in a store\"",
"%",
"(",
"self",
",",
")",
")",
"if",
"self",
".",
"__deleting",
":",
"if",
"not",
"self"... | 43.364865 | 0.002133 |
def _to_json_like(self, include_defaults):
''' Returns a dictionary of the attributes of this object, in
a layout corresponding to what BokehJS expects at unmarshalling time.
This method does not convert "Bokeh types" into "plain JSON types,"
for example each child Model will still be a... | [
"def",
"_to_json_like",
"(",
"self",
",",
"include_defaults",
")",
":",
"all_attrs",
"=",
"self",
".",
"properties_with_values",
"(",
"include_defaults",
"=",
"include_defaults",
")",
"# If __subtype__ is defined, then this model may introduce properties",
"# that don't exist o... | 41.704545 | 0.001597 |
def new_addon():
'''Create a repository for a new fabsetup-task addon.
The repo will contain the fabsetup addon boilerplate.
Running this task you have to enter:
* your github user account (your pypi account should be the same or similar)
* addon name
* task name
* headline, short descript... | [
"def",
"new_addon",
"(",
")",
":",
"author",
",",
"author_email",
"=",
"git_name_and_email_or_die",
"(",
")",
"username",
"=",
"query_input",
"(",
"'github username:'",
")",
"git_ssh_or_die",
"(",
"username",
")",
"addonname",
"=",
"query_input",
"(",
"'\\naddon n... | 41.630435 | 0.00102 |
def aggregate(self, opTable, group_by_cols, meas):
"""
Create an aggregate table grouped by col showing meas
The meas is something like "sum(in)" or "count(*)"
RETURNS:
DROP TABLE C_AGG_PRODUCT;
CREATE TABLE C_AGG_PRODUCT AS (
SELECT PRODUCT, sum(... | [
"def",
"aggregate",
"(",
"self",
",",
"opTable",
",",
"group_by_cols",
",",
"meas",
")",
":",
"self",
".",
"sql_text",
"+=",
"\"DROP TABLE \"",
"+",
"opTable",
"+",
"\";\\n\"",
"self",
".",
"sql_text",
"+=",
"\"CREATE TABLE \"",
"+",
"opTable",
"+",
"\" AS (... | 42.823529 | 0.008065 |
def get_sys_path(rcpath, app_name, section_name=None):
"""Return a folder path if it exists.
First will check if it is an existing system path, if it is, will return it
expanded and absoluted.
If this fails will look for the rcpath variable in the app_name rcfiles or
exclusively within the given s... | [
"def",
"get_sys_path",
"(",
"rcpath",
",",
"app_name",
",",
"section_name",
"=",
"None",
")",
":",
"# first check if it is an existing path",
"if",
"op",
".",
"exists",
"(",
"rcpath",
")",
":",
"return",
"op",
".",
"realpath",
"(",
"op",
".",
"expanduser",
"... | 34.35 | 0.000943 |
def isHereDoc(self, line, column):
"""Check if text at given position is a here document.
If language is not known, or text is not parsed yet, ``False`` is returned
"""
return self._highlighter is not None and \
self._highlighter.isHereDoc(self.document().findBlockByNumbe... | [
"def",
"isHereDoc",
"(",
"self",
",",
"line",
",",
"column",
")",
":",
"return",
"self",
".",
"_highlighter",
"is",
"not",
"None",
"and",
"self",
".",
"_highlighter",
".",
"isHereDoc",
"(",
"self",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"("... | 47.142857 | 0.014881 |
def adev(data, rate=1.0, data_type="phase", taus=None):
""" Allan deviation.
Classic - use only if required - relatively poor confidence.
.. math::
\\sigma^2_{ADEV}(\\tau) = { 1 \\over 2 \\tau^2 }
\\langle ( {x}_{n+2} - 2x_{n+1} + x_{n} )^2 \\rangle
= { 1 \\over 2 (N-2) \\tau^2... | [
"def",
"adev",
"(",
"data",
",",
"rate",
"=",
"1.0",
",",
"data_type",
"=",
"\"phase\"",
",",
"taus",
"=",
"None",
")",
":",
"phase",
"=",
"input_to_phase",
"(",
"data",
",",
"rate",
",",
"data_type",
")",
"(",
"phase",
",",
"m",
",",
"taus_used",
... | 31.753846 | 0.00047 |
def plot_generated_images(images, fname):
"""Save a synthetic image as a PNG file.
Args:
images: samples of synthetic images generated by the generative network.
fname: Python `str`, filename to save the plot to.
"""
fig = plt.figure(figsize=(4, 4))
canvas = backend_agg.FigureCanvasAgg(fig)
for i,... | [
"def",
"plot_generated_images",
"(",
"images",
",",
"fname",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"4",
",",
"4",
")",
")",
"canvas",
"=",
"backend_agg",
".",
"FigureCanvasAgg",
"(",
"fig",
")",
"for",
"i",
",",
"image... | 30.85 | 0.012579 |
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
... | [
"def",
"_read_txt",
"(",
"self",
",",
"stream",
")",
":",
"self",
".",
"_data",
"=",
"_np",
".",
"empty",
"(",
"self",
".",
"count",
",",
"dtype",
"=",
"self",
".",
"dtype",
"(",
")",
")",
"k",
"=",
"0",
"for",
"line",
"in",
"_islice",
"(",
"it... | 36.625 | 0.001663 |
def transform(self, fn, lazy=True):
"""Returns a new dataset with each sample transformed by the
transformer function `fn`.
Parameters
----------
fn : callable
A transformer function that takes a sample as input and
returns the transformed sample.
... | [
"def",
"transform",
"(",
"self",
",",
"fn",
",",
"lazy",
"=",
"True",
")",
":",
"trans",
"=",
"_LazyTransformDataset",
"(",
"self",
",",
"fn",
")",
"if",
"lazy",
":",
"return",
"trans",
"return",
"SimpleDataset",
"(",
"[",
"i",
"for",
"i",
"in",
"tra... | 33.375 | 0.002427 |
def convert_datetext_to_dategui(datetext, ln=None, secs=False):
"""Convert: '2005-11-16 15:11:57' => '16 nov 2005, 15:11'
Or optionally with seconds:
'2005-11-16 15:11:57' => '16 nov 2005, 15:11:57'
Month is internationalized
"""
assert ln is None, 'setting language is not supported'
try:
... | [
"def",
"convert_datetext_to_dategui",
"(",
"datetext",
",",
"ln",
"=",
"None",
",",
"secs",
"=",
"False",
")",
":",
"assert",
"ln",
"is",
"None",
",",
"'setting language is not supported'",
"try",
":",
"datestruct",
"=",
"convert_datetext_to_datestruct",
"(",
"dat... | 34.333333 | 0.00135 |
def supports_spatial_unit_record_type(self, spatial_unit_record_type):
"""Tests if the given spatial unit record type is supported.
arg: spatial_unit_record_type (osid.type.Type): a spatial
unit record Type
return: (boolean) - ``true`` if the type is supported, ``false``
... | [
"def",
"supports_spatial_unit_record_type",
"(",
"self",
",",
"spatial_unit_record_type",
")",
":",
"# Implemented from template for osid.Metadata.supports_coordinate_type",
"if",
"self",
".",
"_kwargs",
"[",
"'syntax'",
"]",
"not",
"in",
"[",
"'``SPATIALUNIT``'",
"]",
":",... | 50.125 | 0.002448 |
def plot(what, calc_id=-1, other_id=None, webapi=False):
"""
Generic plotter for local and remote calculations.
"""
if '?' not in what:
raise SystemExit('Missing ? in %r' % what)
prefix, rest = what.split('?', 1)
assert prefix in 'source_geom hcurves hmaps uhs', prefix
if prefix in '... | [
"def",
"plot",
"(",
"what",
",",
"calc_id",
"=",
"-",
"1",
",",
"other_id",
"=",
"None",
",",
"webapi",
"=",
"False",
")",
":",
"if",
"'?'",
"not",
"in",
"what",
":",
"raise",
"SystemExit",
"(",
"'Missing ? in %r'",
"%",
"what",
")",
"prefix",
",",
... | 36.12 | 0.001079 |
def show_output_dynamic(pcnn_output_dynamic, separate_representation = False):
"""!
@brief Shows output dynamic (output of each oscillator) during simulation.
@param[in] pcnn_output_dynamic (pcnn_dynamic): Output dynamic of the pulse-coupled neural network.
@param[in] separ... | [
"def",
"show_output_dynamic",
"(",
"pcnn_output_dynamic",
",",
"separate_representation",
"=",
"False",
")",
":",
"draw_dynamics",
"(",
"pcnn_output_dynamic",
".",
"time",
",",
"pcnn_output_dynamic",
".",
"output",
",",
"x_title",
"=",
"\"t\"",
",",
"y_title",
"=",
... | 64 | 0.026194 |
def to_foreign(self, obj, name, value): # pylint:disable=unused-argument
"""Transform to a MongoDB-safe value."""
if self.cache:
return self._populate_cache(value)
identifier = value
# First, we handle the typcial Document object case.
if isinstance(value, Document):
identifier = value.__data_... | [
"def",
"to_foreign",
"(",
"self",
",",
"obj",
",",
"name",
",",
"value",
")",
":",
"# pylint:disable=unused-argument",
"if",
"self",
".",
"cache",
":",
"return",
"self",
".",
"_populate_cache",
"(",
"value",
")",
"identifier",
"=",
"value",
"# First, we handle... | 28.78125 | 0.045168 |
def serialize(value, field):
"""
Form values serialization
:param object value: A value to be serialized\
for saving it into the database and later\
loading it into the form as initial value
"""
assert isinstance(field, forms.Field)
if isinstance(field, forms.ModelMultipleChoiceField):
... | [
"def",
"serialize",
"(",
"value",
",",
"field",
")",
":",
"assert",
"isinstance",
"(",
"field",
",",
"forms",
".",
"Field",
")",
"if",
"isinstance",
"(",
"field",
",",
"forms",
".",
"ModelMultipleChoiceField",
")",
":",
"return",
"json",
".",
"dumps",
"(... | 30.266667 | 0.002137 |
def delete_namespace(self, namespace):
"""
Delete the specified CIM namespace in the WBEM server and
update this WBEMServer object to reflect the removed namespace
there.
The specified namespace must be empty (i.e. must not contain any
classes, instances, or qualifier ty... | [
"def",
"delete_namespace",
"(",
"self",
",",
"namespace",
")",
":",
"std_namespace",
"=",
"_ensure_unicode",
"(",
"namespace",
".",
"strip",
"(",
"'/'",
")",
")",
"# Use approach 1: DeleteInstance of CIM class for namespaces",
"# Refresh the list of namespaces in this object ... | 40.851064 | 0.000509 |
def get_image(self, title, group):
'''
Retrieve image @title from group @group.
'''
return self.images[group.lower()][title.lower()] | [
"def",
"get_image",
"(",
"self",
",",
"title",
",",
"group",
")",
":",
"return",
"self",
".",
"images",
"[",
"group",
".",
"lower",
"(",
")",
"]",
"[",
"title",
".",
"lower",
"(",
")",
"]"
] | 32 | 0.012195 |
def K(self, X, X2=None):
"""Compute the covariance matrix between X and X2."""
if X2 is None:
X2 = X
base = np.pi * (X[:, None, :] - X2[None, :, :]) / self.period
exp_dist = np.exp( -0.5* np.sum( np.square( np.sin( base ) / self.lengthscale ), axis = -1 ) )
return ... | [
"def",
"K",
"(",
"self",
",",
"X",
",",
"X2",
"=",
"None",
")",
":",
"if",
"X2",
"is",
"None",
":",
"X2",
"=",
"X",
"base",
"=",
"np",
".",
"pi",
"*",
"(",
"X",
"[",
":",
",",
"None",
",",
":",
"]",
"-",
"X2",
"[",
"None",
",",
":",
"... | 37.333333 | 0.040698 |
def copy_store(source, dest, source_path='', dest_path='', excludes=None,
includes=None, flags=0, if_exists='raise', dry_run=False,
log=None):
"""Copy data directly from the `source` store to the `dest` store. Use this
function when you want to copy a group or array in the most eff... | [
"def",
"copy_store",
"(",
"source",
",",
"dest",
",",
"source_path",
"=",
"''",
",",
"dest_path",
"=",
"''",
",",
"excludes",
"=",
"None",
",",
"includes",
"=",
"None",
",",
"flags",
"=",
"0",
",",
"if_exists",
"=",
"'raise'",
",",
"dry_run",
"=",
"F... | 35.744444 | 0.000756 |
def is_simplicial(G, n):
"""Determines whether a node n in G is simplicial.
Parameters
----------
G : NetworkX graph
The graph on which to check whether node n is simplicial.
n : node
A node in graph G.
Returns
-------
is_simplicial : bool
True if its neighbors ... | [
"def",
"is_simplicial",
"(",
"G",
",",
"n",
")",
":",
"return",
"all",
"(",
"u",
"in",
"G",
"[",
"v",
"]",
"for",
"u",
",",
"v",
"in",
"itertools",
".",
"combinations",
"(",
"G",
"[",
"n",
"]",
",",
"2",
")",
")"
] | 25.15625 | 0.001196 |
def write_message(self, data, binary=False):
""" Write a message to the active client
"""
self.client.write_message(data, binary=binary) | [
"def",
"write_message",
"(",
"self",
",",
"data",
",",
"binary",
"=",
"False",
")",
":",
"self",
".",
"client",
".",
"write_message",
"(",
"data",
",",
"binary",
"=",
"binary",
")"
] | 33 | 0.017751 |
def from_object(orm_class, engine, limit=None):
"""
Select data from the table defined by a ORM class, and put into prettytable
:param orm_class: an orm class inherit from
``sqlalchemy.ext.declarative.declarative_base()``
:param engine: an ``sqlalchemy.engine.base.Engine`` object.
:param li... | [
"def",
"from_object",
"(",
"orm_class",
",",
"engine",
",",
"limit",
"=",
"None",
")",
":",
"Session",
"=",
"sessionmaker",
"(",
"bind",
"=",
"engine",
")",
"ses",
"=",
"Session",
"(",
")",
"query",
"=",
"ses",
".",
"query",
"(",
"orm_class",
")",
"i... | 31.380952 | 0.001473 |
def double_relaxation_run(cls, vasp_cmd, auto_npar=True, ediffg=-0.05,
half_kpts_first_relax=False, auto_continue=False):
"""
Returns a list of two jobs corresponding to an AFLOW style double
relaxation run.
Args:
vasp_cmd (str): Command to run ... | [
"def",
"double_relaxation_run",
"(",
"cls",
",",
"vasp_cmd",
",",
"auto_npar",
"=",
"True",
",",
"ediffg",
"=",
"-",
"0.05",
",",
"half_kpts_first_relax",
"=",
"False",
",",
"auto_continue",
"=",
"False",
")",
":",
"incar_update",
"=",
"{",
"\"ISTART\"",
":"... | 47.436364 | 0.001502 |
def vinet_dPdV(v, v0, k0, k0p, precision=1.e-5):
"""
calculate dP/dV for numerical calculation of bulk modulus
according to test this differs from analytical result by 1.e-5
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference condit... | [
"def",
"vinet_dPdV",
"(",
"v",
",",
"v0",
",",
"k0",
",",
"k0p",
",",
"precision",
"=",
"1.e-5",
")",
":",
"def",
"f_scalar",
"(",
"v",
",",
"v0",
",",
"k0",
",",
"k0p",
",",
"precision",
"=",
"1.e-5",
")",
":",
"return",
"derivative",
"(",
"vine... | 45.125 | 0.001357 |
def allow_ajax(request):
"""
Default function to determine whether to show the toolbar on a given page.
"""
if request.META.get('REMOTE_ADDR', None) not in settings.INTERNAL_IPS:
return False
if toolbar_version < LooseVersion('1.8') \
and request.get_full_path().startswith(DEBUG_... | [
"def",
"allow_ajax",
"(",
"request",
")",
":",
"if",
"request",
".",
"META",
".",
"get",
"(",
"'REMOTE_ADDR'",
",",
"None",
")",
"not",
"in",
"settings",
".",
"INTERNAL_IPS",
":",
"return",
"False",
"if",
"toolbar_version",
"<",
"LooseVersion",
"(",
"'1.8'... | 41.818182 | 0.002128 |
def raw_decode(self, s, idx=0, _w=WHITESPACE.match, _PY3=PY3):
"""Decode a JSON document from ``s`` (a ``str`` or ``unicode``
beginning with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
Optionally, ``idx`` can be used... | [
"def",
"raw_decode",
"(",
"self",
",",
"s",
",",
"idx",
"=",
"0",
",",
"_w",
"=",
"WHITESPACE",
".",
"match",
",",
"_PY3",
"=",
"PY3",
")",
":",
"if",
"idx",
"<",
"0",
":",
"# Ensure that raw_decode bails on negative indexes, the regex",
"# would otherwise mas... | 44.32 | 0.001767 |
def roles(self):
"""
Gets the Roles API client.
Returns:
Roles:
"""
if not self.__roles:
self.__roles = Roles(self.__connection)
return self.__roles | [
"def",
"roles",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__roles",
":",
"self",
".",
"__roles",
"=",
"Roles",
"(",
"self",
".",
"__connection",
")",
"return",
"self",
".",
"__roles"
] | 21.2 | 0.00905 |
def save(self, filename, format=None):
"""
Save the SFrame to a file system for later use.
Parameters
----------
filename : string
The location to save the SFrame. Either a local directory or a
remote URL. If the format is 'binary', a directory will be cr... | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"format",
"=",
"None",
")",
":",
"if",
"format",
"is",
"None",
":",
"if",
"filename",
".",
"endswith",
"(",
"(",
"'.csv'",
",",
"'.csv.gz'",
")",
")",
":",
"format",
"=",
"'csv'",
"elif",
"filename",
... | 37.101695 | 0.00178 |
def createRootCertificate(self, noPass = False, keyLength = 4096):
"""Create a root certificate
"""
configPath, keyPath, certPath = \
os.path.join(self.basePath, self.FILE_CONFIG), \
os.path.join(self.basePath, self.DIR_PRIVATE, self.FILE_CA_KEY), \
... | [
"def",
"createRootCertificate",
"(",
"self",
",",
"noPass",
"=",
"False",
",",
"keyLength",
"=",
"4096",
")",
":",
"configPath",
",",
"keyPath",
",",
"certPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"basePath",
",",
"self",
".",
"FILE... | 66.235294 | 0.015762 |
def dump_compile(codeobject, filename, timestamp, magic):
"""Write code object as a byte-compiled file
Arguments:
codeobject: code object
filefile: bytecode file to write
timestamp: timestamp to put in file
magic: Pyton bytecode magic
"""
# Atomically write the pyc/pyo file. Issue #131... | [
"def",
"dump_compile",
"(",
"codeobject",
",",
"filename",
",",
"timestamp",
",",
"magic",
")",
":",
"# Atomically write the pyc/pyo file. Issue #13146.",
"# id() is used to generate a pseudo-random filename.",
"path_tmp",
"=",
"'%s.%s'",
"%",
"(",
"filename",
",",
"id",
... | 26.823529 | 0.002116 |
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
oauth_params = ((k, v) for k, v in self.items()
if k.startswith('oauth_'))
stringy_params = ((k, escape(v)) for k, v in oauth_params)
header_params = ('%s="%s"' % (k, v) for k... | [
"def",
"to_header",
"(",
"self",
",",
"realm",
"=",
"''",
")",
":",
"oauth_params",
"=",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"if",
"k",
".",
"startswith",
"(",
"'oauth_'",
")",
")",
"stringy... | 43.846154 | 0.010309 |
def anti_commutator(A, B=None):
"""If ``B != None``, return the anti-commutator :math:`\{A,B\}`, otherwise
return the super-operator :math:`\{A,\cdot\}`. The super-operator
:math:`\{A,\cdot\}` maps any other operator ``B`` to the anti-commutator
:math:`\{A, B\} = A B + B A`.
Args:
A: The f... | [
"def",
"anti_commutator",
"(",
"A",
",",
"B",
"=",
"None",
")",
":",
"if",
"B",
":",
"return",
"A",
"*",
"B",
"+",
"B",
"*",
"A",
"return",
"SPre",
"(",
"A",
")",
"+",
"SPost",
"(",
"A",
")"
] | 34.117647 | 0.020134 |
def delete(self, resource_id, **kwargs):
"""
Deletes a resource by ID.
"""
return self.client._delete(self._url(resource_id), **kwargs) | [
"def",
"delete",
"(",
"self",
",",
"resource_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"_delete",
"(",
"self",
".",
"_url",
"(",
"resource_id",
")",
",",
"*",
"*",
"kwargs",
")"
] | 27.166667 | 0.011905 |
def AddDefaultMergers(self):
"""Adds the default DataSetMergers defined in this module."""
self.AddMerger(AgencyMerger(self))
self.AddMerger(StopMerger(self))
self.AddMerger(RouteMerger(self))
self.AddMerger(ServicePeriodMerger(self))
self.AddMerger(FareMerger(self))
self.AddMerger(ShapeMerg... | [
"def",
"AddDefaultMergers",
"(",
"self",
")",
":",
"self",
".",
"AddMerger",
"(",
"AgencyMerger",
"(",
"self",
")",
")",
"self",
".",
"AddMerger",
"(",
"StopMerger",
"(",
"self",
")",
")",
"self",
".",
"AddMerger",
"(",
"RouteMerger",
"(",
"self",
")",
... | 39.8 | 0.002457 |
def gen_nop():
"""Return a NOP instruction.
"""
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.NOP, empty_reg, empty_reg, empty_reg) | [
"def",
"gen_nop",
"(",
")",
":",
"empty_reg",
"=",
"ReilEmptyOperand",
"(",
")",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"NOP",
",",
"empty_reg",
",",
"empty_reg",
",",
"empty_reg",
")"
] | 30.333333 | 0.016043 |
def modelrepr(instance) -> str:
"""
Default ``repr`` version of a Django model object, for debugging.
"""
elements = []
# noinspection PyProtectedMember
for f in instance._meta.get_fields():
# https://docs.djangoproject.com/en/2.0/ref/models/meta/
if f.auto_created:
c... | [
"def",
"modelrepr",
"(",
"instance",
")",
"->",
"str",
":",
"elements",
"=",
"[",
"]",
"# noinspection PyProtectedMember",
"for",
"f",
"in",
"instance",
".",
"_meta",
".",
"get_fields",
"(",
")",
":",
"# https://docs.djangoproject.com/en/2.0/ref/models/meta/",
"if",... | 36.35 | 0.00134 |
def ListChildren(self, urn, limit=None, age=NEWEST_TIME):
"""Lists bunch of directories efficiently.
Args:
urn: Urn to list children.
limit: Max number of children to list.
age: The age of the items to retrieve. Should be one of ALL_TIMES,
NEWEST_TIME or a range.
Returns:
R... | [
"def",
"ListChildren",
"(",
"self",
",",
"urn",
",",
"limit",
"=",
"None",
",",
"age",
"=",
"NEWEST_TIME",
")",
":",
"_",
",",
"children_urns",
"=",
"list",
"(",
"self",
".",
"MultiListChildren",
"(",
"[",
"urn",
"]",
",",
"limit",
"=",
"limit",
",",... | 30.866667 | 0.002096 |
def _distance(self, x0, y0, x1, y1):
"""Utitlity function to compute distance between points."""
dx = x1-x0
dy = y1-y0
# roll displacements across the borders
if self.pix:
dx[ dx > self.Lx/2 ] -= self.Lx
dx[ dx < -self.Lx/2 ] += self.Lx
if self.piy... | [
"def",
"_distance",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
")",
":",
"dx",
"=",
"x1",
"-",
"x0",
"dy",
"=",
"y1",
"-",
"y0",
"# roll displacements across the borders",
"if",
"self",
".",
"pix",
":",
"dx",
"[",
"dx",
">",
"self",
... | 35.083333 | 0.023148 |
def new_folder(self, basedir):
"""New folder"""
title = _('New folder')
subtitle = _('Folder name:')
self.create_new_folder(basedir, title, subtitle, is_package=False) | [
"def",
"new_folder",
"(",
"self",
",",
"basedir",
")",
":",
"title",
"=",
"_",
"(",
"'New folder'",
")",
"subtitle",
"=",
"_",
"(",
"'Folder name:'",
")",
"self",
".",
"create_new_folder",
"(",
"basedir",
",",
"title",
",",
"subtitle",
",",
"is_package",
... | 39.8 | 0.009852 |
def _re_flatten(p):
''' Turn all capturing groups in a regular expression pattern into
non-capturing groups. '''
if '(' not in p: return p
return re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))',
lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p) | [
"def",
"_re_flatten",
"(",
"p",
")",
":",
"if",
"'('",
"not",
"in",
"p",
":",
"return",
"p",
"return",
"re",
".",
"sub",
"(",
"r'(\\\\*)(\\(\\?P<[^>]*>|\\((?!\\?))'",
",",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"0",
")",
"if",
"len",
"(",
"m",
... | 46.666667 | 0.010526 |
def _dict_from_path(path, val, delimiter=DEFAULT_TARGET_DELIM):
'''
Given a lookup string in the form of 'foo:bar:baz" return a nested
dictionary of the appropriate depth with the final segment as a value.
>>> _dict_from_path('foo:bar:baz', 'somevalue')
{"foo": {"bar": {"baz": "somevalue"}}
'''... | [
"def",
"_dict_from_path",
"(",
"path",
",",
"val",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"nested_dict",
"=",
"_infinitedict",
"(",
")",
"keys",
"=",
"path",
".",
"rsplit",
"(",
"delimiter",
")",
"lastplace",
"=",
"reduce",
"(",
"operator",... | 35.285714 | 0.001972 |
async def delete(self):
"""Delete boot source selection."""
await self._handler.delete(
boot_source_id=self.boot_source.id, id=self.id) | [
"async",
"def",
"delete",
"(",
"self",
")",
":",
"await",
"self",
".",
"_handler",
".",
"delete",
"(",
"boot_source_id",
"=",
"self",
".",
"boot_source",
".",
"id",
",",
"id",
"=",
"self",
".",
"id",
")"
] | 40 | 0.01227 |
def xpath(self, node, path):
"""Wrapper for lxml`s xpath."""
return node.xpath(path, namespaces=self.namespaces) | [
"def",
"xpath",
"(",
"self",
",",
"node",
",",
"path",
")",
":",
"return",
"node",
".",
"xpath",
"(",
"path",
",",
"namespaces",
"=",
"self",
".",
"namespaces",
")"
] | 31.5 | 0.015504 |
def dump_to_store(dataset, store, writer=None, encoder=None,
encoding=None, unlimited_dims=None):
"""Store dataset contents to a backends.*DataStore object."""
if writer is None:
writer = ArrayWriter()
if encoding is None:
encoding = {}
variables, attrs = conventions.... | [
"def",
"dump_to_store",
"(",
"dataset",
",",
"store",
",",
"writer",
"=",
"None",
",",
"encoder",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"unlimited_dims",
"=",
"None",
")",
":",
"if",
"writer",
"is",
"None",
":",
"writer",
"=",
"ArrayWriter",
... | 32.826087 | 0.001287 |
def Tm(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[]):
r'''This function handles the retrieval of a chemical's melting
point. Lookup is based on CASRNs. Will automatically select a data
source to use if no Method is provided; returns None if the data is not
available.
Prefered source... | [
"def",
"Tm",
"(",
"CASRN",
",",
"AvailableMethods",
"=",
"False",
",",
"Method",
"=",
"None",
",",
"IgnoreMethods",
"=",
"[",
"]",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"if",
"CASRN",
"in",
"Tm_ON_data",
".",
"inde... | 37.153846 | 0.001152 |
def command(state, args):
"""Watch an anime."""
if len(args) < 2:
print(f'Usage: {args[0]} {{ID|aid:AID}} [EPISODE]')
return
aid = state.results.parse_aid(args[1], default_key='db')
anime = query.select.lookup(state.db, aid)
if len(args) < 3:
episode = anime.watched_episodes ... | [
"def",
"command",
"(",
"state",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"print",
"(",
"f'Usage: {args[0]} {{ID|aid:AID}} [EPISODE]'",
")",
"return",
"aid",
"=",
"state",
".",
"results",
".",
"parse_aid",
"(",
"args",
"[",
"1"... | 32.296296 | 0.001114 |
def run(self):
"""
Reimplements the :meth:`QThread.run` method.
"""
self.__timer = QTimer()
self.__timer.moveToThread(self)
self.__timer.start(Constants.default_timer_cycle * self.__timer_cycle_multiplier)
self.__timer.timeout.connect(self.__watch_file_system, Q... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"__timer",
"=",
"QTimer",
"(",
")",
"self",
".",
"__timer",
".",
"moveToThread",
"(",
"self",
")",
"self",
".",
"__timer",
".",
"start",
"(",
"Constants",
".",
"default_timer_cycle",
"*",
"self",
".",
... | 29.166667 | 0.01108 |
def build_keras_model():
"""
Define a recurrent convolutional model in Keras 1.2.2
"""
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import LSTM
from keras.layers import Convolution1D, MaxPooli... | [
"def",
"build_keras_model",
"(",
")",
":",
"from",
"keras",
".",
"models",
"import",
"Sequential",
"from",
"keras",
".",
"layers",
"import",
"Dense",
",",
"Dropout",
",",
"Activation",
"from",
"keras",
".",
"layers",
"import",
"Embedding",
"from",
"keras",
"... | 39.409091 | 0.001126 |
def organization_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organizations#show-organization"
api_path = "/api/v2/organizations/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"organization_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/organizations/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"(",
"api_p... | 53.8 | 0.010989 |
def create_element(self, method, args=None):
"""
Evaluate a browser method and CSS selector against the document
(or an optional context DOMNode) and return a single
:class:`zombie.dom.DOMNode` object, e.g.,
browser._node('query', 'body > div')
...roughly translates to ... | [
"def",
"create_element",
"(",
"self",
",",
"method",
",",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"arguments",
"=",
"''",
"else",
":",
"arguments",
"=",
"\"(%s)\"",
"%",
"encode_args",
"(",
"args",
")",
"js",
"=",
"\"\"\"\n ... | 30.727273 | 0.001912 |
def mapVisualProperty(self, visualProperty=None,mappingType=None, mappingColumn=None,
lower=None,center=None,upper=None,\
discrete=None,\
network="current",table="node",\
namespace="default",verbose=False):
""""
... | [
"def",
"mapVisualProperty",
"(",
"self",
",",
"visualProperty",
"=",
"None",
",",
"mappingType",
"=",
"None",
",",
"mappingColumn",
"=",
"None",
",",
"lower",
"=",
"None",
",",
"center",
"=",
"None",
",",
"upper",
"=",
"None",
",",
"discrete",
"=",
"None... | 47.074074 | 0.028256 |
async def power_off(
self, stop_mode: PowerStopMode = PowerStopMode.HARD,
comment: str = None, wait: bool = False, wait_interval: int = 5):
"""
Power off.
:param stop_mode: How to perform the power off.
:type stop_mode: `PowerStopMode`
:param comment: Rea... | [
"async",
"def",
"power_off",
"(",
"self",
",",
"stop_mode",
":",
"PowerStopMode",
"=",
"PowerStopMode",
".",
"HARD",
",",
"comment",
":",
"str",
"=",
"None",
",",
"wait",
":",
"bool",
"=",
"False",
",",
"wait_interval",
":",
"int",
"=",
"5",
")",
":",
... | 42.756098 | 0.001115 |
def remove_autosave_file(self, fileinfo):
"""
Remove autosave file for specified file.
This function also updates `self.autosave_mapping` and clears the
`changed_since_autosave` flag.
"""
filename = fileinfo.filename
if filename not in self.name_mapping:
... | [
"def",
"remove_autosave_file",
"(",
"self",
",",
"fileinfo",
")",
":",
"filename",
"=",
"fileinfo",
".",
"filename",
"if",
"filename",
"not",
"in",
"self",
".",
"name_mapping",
":",
"return",
"autosave_filename",
"=",
"self",
".",
"name_mapping",
"[",
"filenam... | 39.863636 | 0.002227 |
def find_symbol(pid, symbol):
"""Return [(MemMap, value), ...]"""
for mapping in read_proc_maps(pid):
if not mapping.filename or not os.path.exists(mapping.filename):
continue
# We're interested only in the main mapping for each library
# It looks like executable bit and 0 o... | [
"def",
"find_symbol",
"(",
"pid",
",",
"symbol",
")",
":",
"for",
"mapping",
"in",
"read_proc_maps",
"(",
"pid",
")",
":",
"if",
"not",
"mapping",
".",
"filename",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"mapping",
".",
"filename",
")",
"... | 39 | 0.001318 |
def searchtextindex(index_or_dirname, query, limit=10, indexname=None,
docnum_field=None, score_field=None, fieldboosts=None,
search_kwargs=None):
"""
Search a Whoosh index using a query. E.g.::
>>> import petl as etl
>>> import os
>>> # set up an... | [
"def",
"searchtextindex",
"(",
"index_or_dirname",
",",
"query",
",",
"limit",
"=",
"10",
",",
"indexname",
"=",
"None",
",",
"docnum_field",
"=",
"None",
",",
"score_field",
"=",
"None",
",",
"fieldboosts",
"=",
"None",
",",
"search_kwargs",
"=",
"None",
... | 40.5 | 0.001854 |
def set(self, param, value):
"""
Sets a parameter in the embedded param map.
"""
self._shouldOwn(param)
try:
value = param.typeConverter(value)
except ValueError as e:
raise ValueError('Invalid param value given for param "%s". %s' % (param.name, e... | [
"def",
"set",
"(",
"self",
",",
"param",
",",
"value",
")",
":",
"self",
".",
"_shouldOwn",
"(",
"param",
")",
"try",
":",
"value",
"=",
"param",
".",
"typeConverter",
"(",
"value",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"ValueError",
... | 35.1 | 0.008333 |
def _get_attribute_dimension(trait_name, mark_type=None):
"""Returns the dimension for the name of the trait for the specified mark.
If `mark_type` is `None`, then the `trait_name` is returned
as is.
Returns `None` if the `trait_name` is not valid for `mark_type`.
"""
if(mark_type is None):
... | [
"def",
"_get_attribute_dimension",
"(",
"trait_name",
",",
"mark_type",
"=",
"None",
")",
":",
"if",
"(",
"mark_type",
"is",
"None",
")",
":",
"return",
"trait_name",
"scale_metadata",
"=",
"mark_type",
".",
"class_traits",
"(",
")",
"[",
"'scales_metadata'",
... | 40.916667 | 0.001992 |
def copy(self, request, **kwargs):
# pylint: disable=unused-argument
'''
Copy instance with deps.
'''
instance = self.copy_instance(self.get_object())
serializer = self.get_serializer(instance, data=request.data, partial=True)
serializer.is_valid()
seriali... | [
"def",
"copy",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"instance",
"=",
"self",
".",
"copy_instance",
"(",
"self",
".",
"get_object",
"(",
")",
")",
"serializer",
"=",
"self",
".",
"get_serializer"... | 39.2 | 0.009975 |
def plot_objective(ensemble, partition='train', ax=None, jitter=0.1,
scatter_kw=dict(), line_kw=dict()):
"""Plots objective function as a function of model rank.
Parameters
----------
ensemble : Ensemble object
holds optimization results across a range of model ranks
part... | [
"def",
"plot_objective",
"(",
"ensemble",
",",
"partition",
"=",
"'train'",
",",
"ax",
"=",
"None",
",",
"jitter",
"=",
"0.1",
",",
"scatter_kw",
"=",
"dict",
"(",
")",
",",
"line_kw",
"=",
"dict",
"(",
")",
")",
":",
"if",
"ax",
"is",
"None",
":",... | 32 | 0.000595 |
def parse_connection_option(
header: str, pos: int, header_name: str
) -> Tuple[ConnectionOption, int]:
"""
Parse a Connection option from ``header`` at the given position.
Return the protocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
... | [
"def",
"parse_connection_option",
"(",
"header",
":",
"str",
",",
"pos",
":",
"int",
",",
"header_name",
":",
"str",
")",
"->",
"Tuple",
"[",
"ConnectionOption",
",",
"int",
"]",
":",
"item",
",",
"pos",
"=",
"parse_token",
"(",
"header",
",",
"pos",
"... | 31.769231 | 0.002353 |
def gen_mul(src1, src2, dst):
"""Return a MUL instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.MUL, src1, src2, dst) | [
"def",
"gen_mul",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"MUL",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | 30 | 0.010811 |
def parse_temperature_response(
temperature_string: str) -> Mapping[str, Optional[float]]:
'''
Example input: "T:none C:25"
'''
err_msg = 'Unexpected argument to parse_temperature_response: {}'.format(
temperature_string)
if not temperature_string or \
not isinstance(temp... | [
"def",
"parse_temperature_response",
"(",
"temperature_string",
":",
"str",
")",
"->",
"Mapping",
"[",
"str",
",",
"Optional",
"[",
"float",
"]",
"]",
":",
"err_msg",
"=",
"'Unexpected argument to parse_temperature_response: {}'",
".",
"format",
"(",
"temperature_stri... | 30.5 | 0.001222 |
def vals(self, var_type):
"""
Create a dictionary with name/value pairs listing the
variables of a particular type that have a value.
"""
return {x: y for x, y in self.items() if y.has_value_of_type(var_type)} | [
"def",
"vals",
"(",
"self",
",",
"var_type",
")",
":",
"return",
"{",
"x",
":",
"y",
"for",
"x",
",",
"y",
"in",
"self",
".",
"items",
"(",
")",
"if",
"y",
".",
"has_value_of_type",
"(",
"var_type",
")",
"}"
] | 40.666667 | 0.008032 |
def __fetch_crate_owner_user(self, crate_id):
"""Get crate user owners"""
raw_owner_user = self.client.crate_attribute(crate_id, 'owner_user')
owner_user = json.loads(raw_owner_user)
return owner_user | [
"def",
"__fetch_crate_owner_user",
"(",
"self",
",",
"crate_id",
")",
":",
"raw_owner_user",
"=",
"self",
".",
"client",
".",
"crate_attribute",
"(",
"crate_id",
",",
"'owner_user'",
")",
"owner_user",
"=",
"json",
".",
"loads",
"(",
"raw_owner_user",
")",
"re... | 28.5 | 0.008511 |
def unregister(self, cleanup_mode):
"""Unregisters a machine previously registered with
:py:func:`IVirtualBox.register_machine` and optionally do additional
cleanup before the machine is unregistered.
This method does not delete any files. It only changes the machine configurat... | [
"def",
"unregister",
"(",
"self",
",",
"cleanup_mode",
")",
":",
"if",
"not",
"isinstance",
"(",
"cleanup_mode",
",",
"CleanupMode",
")",
":",
"raise",
"TypeError",
"(",
"\"cleanup_mode can only be an instance of type CleanupMode\"",
")",
"media",
"=",
"self",
".",
... | 60.654762 | 0.011394 |
def wrap(self, value):
''' Validate and wrap value using the wrapping function from
``EnumField.item_type``
'''
self.validate_wrap(value)
return self.item_type.wrap(value) | [
"def",
"wrap",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"validate_wrap",
"(",
"value",
")",
"return",
"self",
".",
"item_type",
".",
"wrap",
"(",
"value",
")"
] | 35 | 0.009302 |
def statuses_update(self, status, in_reply_to_status_id=None, lat=None,
long=None, place_id=None, display_coordinates=None,
trim_user=None, media_ids=None):
"""
Posts a tweet.
https://dev.twitter.com/docs/api/1.1/post/statuses/update
:par... | [
"def",
"statuses_update",
"(",
"self",
",",
"status",
",",
"in_reply_to_status_id",
"=",
"None",
",",
"lat",
"=",
"None",
",",
"long",
"=",
"None",
",",
"place_id",
"=",
"None",
",",
"display_coordinates",
"=",
"None",
",",
"trim_user",
"=",
"None",
",",
... | 45.826087 | 0.001238 |
def generate_datafile_old(number_items=1000):
"""
Create the samples.py file
"""
from utils import get_names, generate_dataset
from pprint import pprint
filename = "samples.py"
dataset = generate_dataset(number_items)
fo = open(filename, "wb")
fo.write("#!/usr/bin/env python\n")
... | [
"def",
"generate_datafile_old",
"(",
"number_items",
"=",
"1000",
")",
":",
"from",
"utils",
"import",
"get_names",
",",
"generate_dataset",
"from",
"pprint",
"import",
"pprint",
"filename",
"=",
"\"samples.py\"",
"dataset",
"=",
"generate_dataset",
"(",
"number_ite... | 33.5625 | 0.001812 |
def block_resource_fitnesses(self, block: block.Block):
"""Returns a map of nodename to average fitness value for this block.
Assumes that required resources have been checked on all nodes."""
# Short-circuit! My algorithm is terrible, so it doesn't work well for the edge case where
# t... | [
"def",
"block_resource_fitnesses",
"(",
"self",
",",
"block",
":",
"block",
".",
"Block",
")",
":",
"# Short-circuit! My algorithm is terrible, so it doesn't work well for the edge case where",
"# the block has no requirements",
"if",
"not",
"block",
".",
"resources",
":",
"r... | 35.555556 | 0.002027 |
def count_datasets(taxonKey = None, country = None, **kwargs):
'''
Lists occurrence counts for datasets that cover a given taxon or country
:param taxonKey: [int] Taxon key
:param country: [str] A country, two letter code
:return: dict
Usage::
from pygbif import occurrences
... | [
"def",
"count_datasets",
"(",
"taxonKey",
"=",
"None",
",",
"country",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"gbif_baseurl",
"+",
"'occurrence/counts/datasets'",
"out",
"=",
"gbif_GET",
"(",
"url",
",",
"{",
"'taxonKey'",
":",
"taxonK... | 29.882353 | 0.009542 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'message_type') and self.message_type is not None:
_dict['message_type'] = self.message_type
if hasattr(self, 'text') and self.text is not None:
_dict['text'] =... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'message_type'",
")",
"and",
"self",
".",
"message_type",
"is",
"not",
"None",
":",
"_dict",
"[",
"'message_type'",
"]",
"=",
"self",
".",
"message_ty... | 53.9375 | 0.002278 |
def is_dataset(ds):
"""Whether ds is a Dataset. Compatible across TF versions."""
import tensorflow as tf
from tensorflow_datasets.core.utils import py_utils
dataset_types = [tf.data.Dataset]
v1_ds = py_utils.rgetattr(tf, "compat.v1.data.Dataset", None)
v2_ds = py_utils.rgetattr(tf, "compat.v2.data.Dataset"... | [
"def",
"is_dataset",
"(",
"ds",
")",
":",
"import",
"tensorflow",
"as",
"tf",
"from",
"tensorflow_datasets",
".",
"core",
".",
"utils",
"import",
"py_utils",
"dataset_types",
"=",
"[",
"tf",
".",
"data",
".",
"Dataset",
"]",
"v1_ds",
"=",
"py_utils",
".",
... | 39.5 | 0.020619 |
def mkdir(self, path):
"""Create directory. All part of path must be exists. Raise exception when path already exists."""
resp = self._sendRequest("MKCOL", path)
if resp.status_code != 201:
if resp.status_code == 409:
raise YaDiskException(409, "Part of path {} does ... | [
"def",
"mkdir",
"(",
"self",
",",
"path",
")",
":",
"resp",
"=",
"self",
".",
"_sendRequest",
"(",
"\"MKCOL\"",
",",
"path",
")",
"if",
"resp",
".",
"status_code",
"!=",
"201",
":",
"if",
"resp",
".",
"status_code",
"==",
"409",
":",
"raise",
"YaDisk... | 49.727273 | 0.008977 |
def hash_dir(path):
"""Write directory at path to Git index, return its SHA1 as a string."""
dir_hash = {}
for root, dirs, files in os.walk(path, topdown=False):
f_hash = ((f, hash_file(join(root, f))) for f in files)
d_hash = ((d, dir_hash[join(root, d)]) for d in dirs)
# split+joi... | [
"def",
"hash_dir",
"(",
"path",
")",
":",
"dir_hash",
"=",
"{",
"}",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
",",
"topdown",
"=",
"False",
")",
":",
"f_hash",
"=",
"(",
"(",
"f",
",",
"hash_file",
"(",
"j... | 40.727273 | 0.002183 |
def rst2md(text):
"""Converts the RST text from the examples docstrigs and comments
into markdown text for the Jupyter notebooks"""
top_heading = re.compile(r'^=+$\s^([\w\s-]+)^=+$', flags=re.M)
text = re.sub(top_heading, r'# \1', text)
math_eq = re.compile(r'^\.\. math::((?:.+)?(?:\n+^ .+)*)', f... | [
"def",
"rst2md",
"(",
"text",
")",
":",
"top_heading",
"=",
"re",
".",
"compile",
"(",
"r'^=+$\\s^([\\w\\s-]+)^=+$'",
",",
"flags",
"=",
"re",
".",
"M",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"top_heading",
",",
"r'# \\1'",
",",
"text",
")",
"math_eq... | 36.65 | 0.000664 |
def hr_dp996(self, value=None):
""" Corresponds to IDD Field `hr_dp996`
humidity ratio, calculated at standard atmospheric pressure
at elevation of station, corresponding to
Dew-point temperature corresponding to 99.6% annual cumulative
frequency of occurrence (cold conditions)
... | [
"def",
"hr_dp996",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float... | 38.26087 | 0.002217 |
def decode(model, tokens, start_token, end_token, pad_token, max_len=10000, max_repeat=10, max_repeat_block=10):
"""Decode with the given model and input tokens.
:param model: The trained model.
:param tokens: The input tokens of encoder.
:param start_token: The token that represents the start of a sen... | [
"def",
"decode",
"(",
"model",
",",
"tokens",
",",
"start_token",
",",
"end_token",
",",
"pad_token",
",",
"max_len",
"=",
"10000",
",",
"max_repeat",
"=",
"10",
",",
"max_repeat_block",
"=",
"10",
")",
":",
"is_single",
"=",
"not",
"isinstance",
"(",
"t... | 47.272727 | 0.002355 |
def getRandomWhatIf():
""" Returns a randomly generated :class:`WhatIf` object, using the Python standard library
random number generator to select the object. The object is returned
from the dictionary produced by :func:`getWhatIfArchive`; like the other What If
routines, this function is called first in order ... | [
"def",
"getRandomWhatIf",
"(",
")",
":",
"random",
".",
"seed",
"(",
")",
"archive",
"=",
"getWhatIfArchive",
"(",
")",
"latest",
"=",
"getLatestWhatIfNum",
"(",
"archive",
")",
"number",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"latest",
")",
"retu... | 42.416667 | 0.026923 |
def move(self, dest, isabspath=False):
"""
Recursively move self.workdir to another location. This is similar to the Unix "mv" command.
The destination path must not already exist. If the destination already exists
but is not a directory, it may be overwritten depending on os.rename() se... | [
"def",
"move",
"(",
"self",
",",
"dest",
",",
"isabspath",
"=",
"False",
")",
":",
"if",
"not",
"isabspath",
":",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"workdir",
")",
",",
"dest",
... | 46 | 0.009836 |
def pipe_itembuilder(context=None, _INPUT=None, conf=None, **kwargs):
"""A source that builds an item. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipeforever pipe or an iterable of items
conf : {
'attrs': [
{'key': {'value': <'title'>}, 'value'... | [
"def",
"pipe_itembuilder",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"funcs",
"=",
"get_splits",
"(",
"None",
",",
"conf",
"[",
"'attrs'",
"]",
",",
"*",
"*",
"cdicts",
"("... | 30 | 0.001292 |
def _remap_new_key(self, indices, new_key, axis):
"""
Return a key of type int, slice, or tuple that represents the
combination of new_key with the given indices.
Raises IndexError/TypeError for invalid keys.
"""
size = len(indices)
if _is_scalar(new_key):
... | [
"def",
"_remap_new_key",
"(",
"self",
",",
"indices",
",",
"new_key",
",",
"axis",
")",
":",
"size",
"=",
"len",
"(",
"indices",
")",
"if",
"_is_scalar",
"(",
"new_key",
")",
":",
"if",
"new_key",
">=",
"size",
"or",
"new_key",
"<",
"-",
"size",
":",... | 45.95 | 0.001066 |
def read_word(image, whitelist=None, chars=None, spaces=False):
""" OCR a single word from an image. Useful for captchas.
Image should be pre-processed to remove noise etc. """
from tesserocr import PyTessBaseAPI
api = PyTessBaseAPI()
api.SetPageSegMode(8)
if whitelist is not None:
a... | [
"def",
"read_word",
"(",
"image",
",",
"whitelist",
"=",
"None",
",",
"chars",
"=",
"None",
",",
"spaces",
"=",
"False",
")",
":",
"from",
"tesserocr",
"import",
"PyTessBaseAPI",
"api",
"=",
"PyTessBaseAPI",
"(",
")",
"api",
".",
"SetPageSegMode",
"(",
"... | 32.45 | 0.001497 |
def delete_items_from_dict(d, to_delete):
"""Recursively deletes items from a dict,
if the item's value(s) is in ``to_delete``.
"""
if not isinstance(to_delete, list):
to_delete = [to_delete]
if isinstance(d, dict):
for single_to_delete in set(to_delete):
if single_to_del... | [
"def",
"delete_items_from_dict",
"(",
"d",
",",
"to_delete",
")",
":",
"if",
"not",
"isinstance",
"(",
"to_delete",
",",
"list",
")",
":",
"to_delete",
"=",
"[",
"to_delete",
"]",
"if",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"for",
"single_to_del... | 36.166667 | 0.001497 |
def restart(self):
"""
Restart the game from a new generation 0
"""
self.initGrid()
self.win.clear()
self.current_gen = 1
self.start | [
"def",
"restart",
"(",
"self",
")",
":",
"self",
".",
"initGrid",
"(",
")",
"self",
".",
"win",
".",
"clear",
"(",
")",
"self",
".",
"current_gen",
"=",
"1",
"self",
".",
"start"
] | 22.625 | 0.010638 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.