text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def save_script(save=None): # noqa: E501
"""Save a script
Save a script # noqa: E501
:param Scripts: The data needed to save this script
:type Scripts: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
save = Save.from_dict(connexion.request.get_json()) # noqa: E50... | [
"def",
"save_script",
"(",
"save",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"save",
"=",
"Save",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501",
"if... | 28.684211 | 0.001776 |
def paginate(context, window=DEFAULT_WINDOW):
"""
Renders the ``pagination/pagination.html`` template, resulting in a
Digg-like display of the available pages, given the current page. If there
are too many pages to be displayed before and after the current page, then
elipses will be used to indicat... | [
"def",
"paginate",
"(",
"context",
",",
"window",
"=",
"DEFAULT_WINDOW",
")",
":",
"try",
":",
"paginator",
"=",
"context",
"[",
"'paginator'",
"]",
"page_obj",
"=",
"context",
"[",
"'page_obj'",
"]",
"page_range",
"=",
"paginator",
".",
"page_range",
"# Fir... | 41.720721 | 0.001687 |
def group_update(auth=None, **kwargs):
'''
Update a group
CLI Example:
.. code-block:: bash
salt '*' keystoneng.group_update name=group1 description='new description'
salt '*' keystoneng.group_create name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e new_name=newgroupname
... | [
"def",
"group_update",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"if",
"'new_name'",
"in",
"kwargs",
":",
"kwargs",
"... | 35 | 0.006547 |
def random_uniform(attrs, inputs, proto_obj):
"""Draw random samples from a uniform distribtuion."""
try:
from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
except ImportError:
raise ImportError("Onnx and protobuf need to be installed. "
"Instructions to install - http... | [
"def",
"random_uniform",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"try",
":",
"from",
"onnx",
".",
"mapping",
"import",
"TENSOR_TYPE_TO_NP_TYPE",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"Onnx and protobuf need to be installed. \"",... | 53.4 | 0.003683 |
def join_time_series(serieses, ignore_year=False, T_s=None, aggregator='mean'):
"""Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling
FIXME:
For ignore_year and multi-year data, the index (in seconds) is computed assuming
366 days per year (leap year). So 3 ou... | [
"def",
"join_time_series",
"(",
"serieses",
",",
"ignore_year",
"=",
"False",
",",
"T_s",
"=",
"None",
",",
"aggregator",
"=",
"'mean'",
")",
":",
"if",
"ignore_year",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"for",
"name",
",",
"ts",
"in",
... | 52.317073 | 0.00595 |
def stream_restore_write( obj_name_or_list,
mode='merge', apply_immediately=False, **obj_kws ):
'''Update module-stream-restore db entry for specified name.
Can be passed PulseExtStreamRestoreInfo object or list of them as argument,
or name string there and object init keywords (e.g. volume, mute, channel_l... | [
"def",
"stream_restore_write",
"(",
"obj_name_or_list",
",",
"mode",
"=",
"'merge'",
",",
"apply_immediately",
"=",
"False",
",",
"*",
"*",
"obj_kws",
")",
":",
"mode",
"=",
"PulseUpdateEnum",
"[",
"mode",
"]",
".",
"_c_val",
"if",
"is_str",
"(",
"obj_name_o... | 60.166667 | 0.024545 |
def simulate():
'''instantiate and execute network simulation'''
#separate model execution from parameters for safe import from other files
nest.ResetKernel()
'''
Configuration of the simulation kernel by the previously defined time
resolution used in the simulation. Setting "print_time" to Tru... | [
"def",
"simulate",
"(",
")",
":",
"#separate model execution from parameters for safe import from other files",
"nest",
".",
"ResetKernel",
"(",
")",
"'''\n Configuration of the simulation kernel by the previously defined time\n resolution used in the simulation. Setting \"print_time\" t... | 35.915556 | 0.010114 |
def size(self):
"""Returns the sizes of the groups as series.
Returns:
TYPE: Description
"""
if len(self.grouping_column_types) > 1:
index_type = WeldStruct([self.grouping_column_types])
# Figure out what to use for multi-key index name
# ... | [
"def",
"size",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"grouping_column_types",
")",
">",
"1",
":",
"index_type",
"=",
"WeldStruct",
"(",
"[",
"self",
".",
"grouping_column_types",
"]",
")",
"# Figure out what to use for multi-key index name",
"# i... | 31.958333 | 0.002532 |
def issues(self, kind, email):
""" Filter unique issues for given activity type and email """
return list(set([unicode(activity.issue)
for activity in self.activities()
if kind == activity.kind and activity.user['email'] == email])) | [
"def",
"issues",
"(",
"self",
",",
"kind",
",",
"email",
")",
":",
"return",
"list",
"(",
"set",
"(",
"[",
"unicode",
"(",
"activity",
".",
"issue",
")",
"for",
"activity",
"in",
"self",
".",
"activities",
"(",
")",
"if",
"kind",
"==",
"activity",
... | 53.6 | 0.014706 |
def get_cache_token(self, token):
""" Get token and data from Redis """
if self.conn is None:
raise CacheException('Redis is not connected')
token_data = self.conn.get(token)
token_data = json.loads(token_data) if token_data else None
return token_data | [
"def",
"get_cache_token",
"(",
"self",
",",
"token",
")",
":",
"if",
"self",
".",
"conn",
"is",
"None",
":",
"raise",
"CacheException",
"(",
"'Redis is not connected'",
")",
"token_data",
"=",
"self",
".",
"conn",
".",
"get",
"(",
"token",
")",
"token_data... | 29.8 | 0.006515 |
def create_index(modules):
'''This takes a dict of modules and created the RST index file.'''
for key in modules.keys():
file_path = join(HERE, '%s_modules/_list_of_modules.rst' % key)
list_file = open(file_path, 'w')
# Write the generic header
list_file.write('%s\n' % AUTOGEN)
... | [
"def",
"create_index",
"(",
"modules",
")",
":",
"for",
"key",
"in",
"modules",
".",
"keys",
"(",
")",
":",
"file_path",
"=",
"join",
"(",
"HERE",
",",
"'%s_modules/_list_of_modules.rst'",
"%",
"key",
")",
"list_file",
"=",
"open",
"(",
"file_path",
",",
... | 37.25 | 0.001637 |
def t_power(logu, t, self_normalized=False, name=None):
"""The T-Power Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True` the T-Power Csiszar-function is:
```none
f(u) = s [ u**t - 1 - t(u - 1) ]
s = { -1 0 <... | [
"def",
"t_power",
"(",
"logu",
",",
"t",
",",
"self_normalized",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"t_power\"",
",",
"[",
"logu",
",",
"t",
"]",
")",
"... | 32.095238 | 0.00288 |
def _get_possible_circular_ref_contigs(self, nucmer_hits, log_fh=None, log_outprefix=None):
'''Returns a dict ref name => tuple(hit at start, hit at end) for each ref sequence in the hash nucmer_hits (each value is a list of nucmer hits)'''
writing_log_file = None not in [log_fh, log_outprefix]
... | [
"def",
"_get_possible_circular_ref_contigs",
"(",
"self",
",",
"nucmer_hits",
",",
"log_fh",
"=",
"None",
",",
"log_outprefix",
"=",
"None",
")",
":",
"writing_log_file",
"=",
"None",
"not",
"in",
"[",
"log_fh",
",",
"log_outprefix",
"]",
"maybe_circular",
"=",
... | 60 | 0.006377 |
def stetson_kindex(fmags, ferrs):
'''This calculates the Stetson K index (a robust measure of the kurtosis).
Parameters
----------
fmags,ferrs : np.array
The input mag/flux time-series to process. Must have no non-finite
elems.
Returns
-------
float
The Stetson K ... | [
"def",
"stetson_kindex",
"(",
"fmags",
",",
"ferrs",
")",
":",
"# use a fill in value for the errors if they're none",
"if",
"ferrs",
"is",
"None",
":",
"ferrs",
"=",
"npfull_like",
"(",
"fmags",
",",
"0.005",
")",
"ndet",
"=",
"len",
"(",
"fmags",
")",
"if",
... | 21.6 | 0.000984 |
def update(self, source_id, source_type, name, resources, auth, parameters=None, validate=True):
""" Update a managed source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceupdate
:param source_type: data source name e.g. facebook_page, googleplus, inst... | [
"def",
"update",
"(",
"self",
",",
"source_id",
",",
"source_type",
",",
"name",
",",
"resources",
",",
"auth",
",",
"parameters",
"=",
"None",
",",
"validate",
"=",
"True",
")",
":",
"assert",
"resources",
",",
"\"Need at least one resource\"",
"assert",
"a... | 54.423077 | 0.00625 |
def success(msg, *args, **kwargs):
'''Display a success message'''
echo('{0} {1}'.format(green(OK), white(msg)), *args, **kwargs) | [
"def",
"success",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"echo",
"(",
"'{0} {1}'",
".",
"format",
"(",
"green",
"(",
"OK",
")",
",",
"white",
"(",
"msg",
")",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 45 | 0.007299 |
def render_table(request,
table,
links=None,
context=None,
template='tri_table/list.html',
blank_on_empty=False,
paginate_by=40, # pragma: no mutate
page=None,
paginator=None,
... | [
"def",
"render_table",
"(",
"request",
",",
"table",
",",
"links",
"=",
"None",
",",
"context",
"=",
"None",
",",
"template",
"=",
"'tri_table/list.html'",
",",
"blank_on_empty",
"=",
"False",
",",
"paginate_by",
"=",
"40",
",",
"# pragma: no mutate",
"page",
... | 36.493506 | 0.002772 |
async def remember_ticket(self, request, ticket):
"""Called to store the ticket data for a request.
Ticket data is stored in the aiohttp_session object
Args:
request: aiohttp Request object.
ticket: String like object representing the ticket to be stored.
"""
... | [
"async",
"def",
"remember_ticket",
"(",
"self",
",",
"request",
",",
"ticket",
")",
":",
"session",
"=",
"await",
"get_session",
"(",
"request",
")",
"session",
"[",
"self",
".",
"cookie_name",
"]",
"=",
"ticket"
] | 35.909091 | 0.004938 |
def load_defaults(self):
'''
Loads default extraction rules from the user and system extract.conf files.
Returns None.
'''
# Load the user extract file first to ensure its rules take precedence.
extract_files = [
self.config.settings.user.extract,
... | [
"def",
"load_defaults",
"(",
"self",
")",
":",
"# Load the user extract file first to ensure its rules take precedence.",
"extract_files",
"=",
"[",
"self",
".",
"config",
".",
"settings",
".",
"user",
".",
"extract",
",",
"self",
".",
"config",
".",
"settings",
"."... | 37.142857 | 0.005 |
def add_unique_template_variables(self, options):
"""Update map template variables specific to graduated circle visual"""
options.update(dict(
colorProperty=self.color_property,
colorStops=self.color_stops,
colorType=self.color_function_type,
radiusType=se... | [
"def",
"add_unique_template_variables",
"(",
"self",
",",
"options",
")",
":",
"options",
".",
"update",
"(",
"dict",
"(",
"colorProperty",
"=",
"self",
".",
"color_property",
",",
"colorStops",
"=",
"self",
".",
"color_stops",
",",
"colorType",
"=",
"self",
... | 45.526316 | 0.002265 |
def ping(self, handler='admin/ping', **kwargs):
"""
Sends a ping request.
Usage::
solr.ping()
"""
params = kwargs
params_encoded = safe_urlencode(params, True)
if len(params_encoded) < 1024:
# Typical case.
path = '%s/?%s' %... | [
"def",
"ping",
"(",
"self",
",",
"handler",
"=",
"'admin/ping'",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"kwargs",
"params_encoded",
"=",
"safe_urlencode",
"(",
"params",
",",
"True",
")",
"if",
"len",
"(",
"params_encoded",
")",
"<",
"1024",
... | 30.478261 | 0.005533 |
def show_high_levels_pars(self, mpars):
"""
shows in the high level mean display area in the bottom left of the
GUI the data in mpars.
"""
FONT_WEIGHT = self.GUI_RESOLUTION+(self.GUI_RESOLUTION-1)*5
font2 = wx.Font(12+min(1, FONT_WEIGHT), wx.SWISS,
... | [
"def",
"show_high_levels_pars",
"(",
"self",
",",
"mpars",
")",
":",
"FONT_WEIGHT",
"=",
"self",
".",
"GUI_RESOLUTION",
"+",
"(",
"self",
".",
"GUI_RESOLUTION",
"-",
"1",
")",
"*",
"5",
"font2",
"=",
"wx",
".",
"Font",
"(",
"12",
"+",
"min",
"(",
"1"... | 53 | 0.003806 |
def getSlicesForText(self, retina_name, body, get_fingerprint=None, start_index=0, max_results=10):
"""Get a list of slices of the text
Args:
retina_name, str: The retina name (required)
body, str: The text to be evaluated (required)
get_fingerprint, bool: Configure i... | [
"def",
"getSlicesForText",
"(",
"self",
",",
"retina_name",
",",
"body",
",",
"get_fingerprint",
"=",
"None",
",",
"start_index",
"=",
"0",
",",
"max_results",
"=",
"10",
")",
":",
"resourcePath",
"=",
"'/text/slices'",
"method",
"=",
"'POST'",
"queryParams",
... | 46.32 | 0.005922 |
def _transform_new_data(self, X, subject):
"""Transform new data for a subjects by projecting to the shared subspace and
computing the individual information.
Parameters
----------
X : array, shape=[voxels, timepoints]
The fMRI data of the subject.
subject ... | [
"def",
"_transform_new_data",
"(",
"self",
",",
"X",
",",
"subject",
")",
":",
"S",
"=",
"np",
".",
"zeros_like",
"(",
"X",
")",
"R",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_iter",
")",
":",
"R",
"=",
"self",
".",
"w_",
"["... | 28.785714 | 0.003601 |
def copy(self,**kwargs):
"""
Copies the spikes and optionally converts the spike times.
(when the keyword units is not None)
"""
new_spike_times = LabeledMatrix(self.spike_times.matrix,self.spike_times.labels) # copies the data
return SpikeContainer(new_spike_time... | [
"def",
"copy",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"new_spike_times",
"=",
"LabeledMatrix",
"(",
"self",
".",
"spike_times",
".",
"matrix",
",",
"self",
".",
"spike_times",
".",
"labels",
")",
"# copies the data",
"return",
"SpikeContainer",
"(",... | 48.714286 | 0.020173 |
def fromxml(node):
"""Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
assert node.tag.lower() == '... | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"assert",
"node",
".",
"tag",
".",
"lower",
... | 47.162791 | 0.010145 |
def apply(self, hits, no_copy=False):
"""Add x, y, z, t0 (and du, floor if DataFrame) columns to the hits.
"""
if not no_copy:
hits = hits.copy()
if istype(hits, 'DataFrame'):
# do we ever see McHits here?
hits = Table.from_template(hits, 'Hits')
... | [
"def",
"apply",
"(",
"self",
",",
"hits",
",",
"no_copy",
"=",
"False",
")",
":",
"if",
"not",
"no_copy",
":",
"hits",
"=",
"hits",
".",
"copy",
"(",
")",
"if",
"istype",
"(",
"hits",
",",
"'DataFrame'",
")",
":",
"# do we ever see McHits here?",
"hits... | 35.060241 | 0.001337 |
def table_from_file(source, ifo=None, columns=None, selection=None,
loudest=False, extended_metadata=True):
"""Read a `Table` from a PyCBC live HDF5 file
Parameters
----------
source : `str`, `h5py.File`, `h5py.Group`
the file path of open `h5py` object from which to read th... | [
"def",
"table_from_file",
"(",
"source",
",",
"ifo",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"selection",
"=",
"None",
",",
"loudest",
"=",
"False",
",",
"extended_metadata",
"=",
"True",
")",
":",
"# find group",
"if",
"isinstance",
"(",
"source",
... | 30.126761 | 0.000453 |
def execute(self, fn, *args, **kwargs):
"""Execute an operation and return the result."""
if not self.asynchronous:
return fn(*args, **kwargs)
raise NotImplementedError | [
"def",
"execute",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"asynchronous",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"raise",
"NotImplementedError"
] | 40 | 0.009804 |
def set_as_error(self, color=Qt.red):
"""
Highlights text as a syntax error.
:param color: Underline color
:type color: QtGui.QColor
"""
self.format.setUnderlineStyle(
QTextCharFormat.WaveUnderline)
self.format.setUnderlineColor(color) | [
"def",
"set_as_error",
"(",
"self",
",",
"color",
"=",
"Qt",
".",
"red",
")",
":",
"self",
".",
"format",
".",
"setUnderlineStyle",
"(",
"QTextCharFormat",
".",
"WaveUnderline",
")",
"self",
".",
"format",
".",
"setUnderlineColor",
"(",
"color",
")"
] | 29.5 | 0.006579 |
def check_key(user,
key,
enc,
comment,
options,
config='.ssh/authorized_keys',
cache_keys=None,
fingerprint_hash_type=None):
'''
Check to see if a key needs updating, returns "update", "add" or "exists"
CLI Ex... | [
"def",
"check_key",
"(",
"user",
",",
"key",
",",
"enc",
",",
"comment",
",",
"options",
",",
"config",
"=",
"'.ssh/authorized_keys'",
",",
"cache_keys",
"=",
"None",
",",
"fingerprint_hash_type",
"=",
"None",
")",
":",
"if",
"cache_keys",
"is",
"None",
":... | 30.270833 | 0.000667 |
def delete_empty_children(self):
"""
Walk through the children of this node and delete any that are empty.
"""
for child in self.children:
child.delete_empty_children()
try:
if os.path.exists(child.full_path):
os.rmdir(child.ful... | [
"def",
"delete_empty_children",
"(",
"self",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"delete_empty_children",
"(",
")",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"child",
".",
"full_path",
")",
":",
"o... | 36 | 0.009852 |
def _unsupported_message_type(self):
"""Check if the current message matches the configured message type(s).
:rtype: bool
"""
if isinstance(self._message_type, (tuple, list, set)):
return self.message_type not in self._message_type
return self.message_type != self._... | [
"def",
"_unsupported_message_type",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_message_type",
",",
"(",
"tuple",
",",
"list",
",",
"set",
")",
")",
":",
"return",
"self",
".",
"message_type",
"not",
"in",
"self",
".",
"_message_type",
... | 36 | 0.006024 |
def draw_into_bitmap(self, export_path: ExportPath, stroke_thickness: int, margin: int = 0) -> None:
"""
Draws the symbol in the original size that it has plus an optional margin
:param export_path: The path, where the symbols should be created on disk
:param stroke_thickness: Pen-thick... | [
"def",
"draw_into_bitmap",
"(",
"self",
",",
"export_path",
":",
"ExportPath",
",",
"stroke_thickness",
":",
"int",
",",
"margin",
":",
"int",
"=",
"0",
")",
"->",
"None",
":",
"self",
".",
"draw_onto_canvas",
"(",
"export_path",
",",
"stroke_thickness",
","... | 52.076923 | 0.007257 |
def pairwise(args):
"""
%prog pairwise ids
Convert a list of IDs into all pairs.
"""
from itertools import combinations
p = OptionParser(pairwise.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
idsfile, = args
ids = SetFile(ids... | [
"def",
"pairwise",
"(",
"args",
")",
":",
"from",
"itertools",
"import",
"combinations",
"p",
"=",
"OptionParser",
"(",
"pairwise",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
... | 21.952381 | 0.002079 |
def update(self, status):
"""
Update the VerificationInstance
:param VerificationInstance.Status status: The new status of the resource
:returns: Updated VerificationInstance
:rtype: twilio.rest.verify.v2.service.verification.VerificationInstance
"""
data = valu... | [
"def",
"update",
"(",
"self",
",",
"status",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'Status'",
":",
"status",
",",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"update",
"(",
"'POST'",
",",
"self",
".",
"_uri",
",",
"da... | 27.478261 | 0.004587 |
def _tr_above(self):
"""
The tr element prior in sequence to the tr this cell appears in.
Raises |ValueError| if called on a cell in the top-most row.
"""
tr_lst = self._tbl.tr_lst
tr_idx = tr_lst.index(self._tr)
if tr_idx == 0:
raise ValueError('no tr... | [
"def",
"_tr_above",
"(",
"self",
")",
":",
"tr_lst",
"=",
"self",
".",
"_tbl",
".",
"tr_lst",
"tr_idx",
"=",
"tr_lst",
".",
"index",
"(",
"self",
".",
"_tr",
")",
"if",
"tr_idx",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'no tr above topmost tr'",
"... | 36.2 | 0.005391 |
def _ts_slice(self, Xt, y):
''' takes time series data, and splits each series into temporal folds '''
Ns = len(Xt)
Xt_new = []
for i in range(self.n_splits):
for j in range(Ns):
Njs = int(len(Xt[j]) / self.n_splits)
Xt_new.append(Xt[j][(Njs * ... | [
"def",
"_ts_slice",
"(",
"self",
",",
"Xt",
",",
"y",
")",
":",
"Ns",
"=",
"len",
"(",
"Xt",
")",
"Xt_new",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_splits",
")",
":",
"for",
"j",
"in",
"range",
"(",
"Ns",
")",
":",
"N... | 37.26087 | 0.003413 |
def dispatch_shell(self, stream, msg):
"""dispatch shell requests"""
# flush control requests first
if self.control_stream:
self.control_stream.flush()
idents,msg = self.session.feed_identities(msg, copy=False)
try:
msg = self.session.unserialize(... | [
"def",
"dispatch_shell",
"(",
"self",
",",
"stream",
",",
"msg",
")",
":",
"# flush control requests first",
"if",
"self",
".",
"control_stream",
":",
"self",
".",
"control_stream",
".",
"flush",
"(",
")",
"idents",
",",
"msg",
"=",
"self",
".",
"session",
... | 40.369565 | 0.005258 |
def pot_dict_from_string(pot_data):
"""
Creates atomic symbol/potential number dictionary
forward and reverse
Arg:
pot_data: potential data in string format
Returns:
forward and reverse atom symbol and potential number dictionaries.
"""
... | [
"def",
"pot_dict_from_string",
"(",
"pot_data",
")",
":",
"pot_dict",
"=",
"{",
"}",
"pot_dict_reverse",
"=",
"{",
"}",
"begin",
"=",
"0",
"ln",
"=",
"-",
"1",
"for",
"line",
"in",
"pot_data",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"try",
":",
"if",... | 28.8125 | 0.002099 |
def getModifiers(chart):
""" Returns the factors of the temperament modifiers. """
modifiers = []
# Factors which can be affected
asc = chart.getAngle(const.ASC)
ascRulerID = essential.ruler(asc.sign)
ascRuler = chart.getObject(ascRulerID)
moon = chart.getObject(const.MOON)
fac... | [
"def",
"getModifiers",
"(",
"chart",
")",
":",
"modifiers",
"=",
"[",
"]",
"# Factors which can be affected",
"asc",
"=",
"chart",
".",
"getAngle",
"(",
"const",
".",
"ASC",
")",
"ascRulerID",
"=",
"essential",
".",
"ruler",
"(",
"asc",
".",
"sign",
")",
... | 28.684211 | 0.00976 |
def walk(self):
""" Generate paths in "self.datapath".
"""
# FIFO?
if self._fifo:
if self._fifo > 1:
raise RuntimeError("INTERNAL ERROR: FIFO read twice!")
self._fifo += 1
# Read paths relative to directory containing the FIFO
... | [
"def",
"walk",
"(",
"self",
")",
":",
"# FIFO?",
"if",
"self",
".",
"_fifo",
":",
"if",
"self",
".",
"_fifo",
">",
"1",
":",
"raise",
"RuntimeError",
"(",
"\"INTERNAL ERROR: FIFO read twice!\"",
")",
"self",
".",
"_fifo",
"+=",
"1",
"# Read paths relative to... | 40.717949 | 0.006765 |
def main():
"""Run Chronophore based on the command line arguments."""
args = get_args()
# Make Chronophore's directories and files in $HOME
DATA_DIR = pathlib.Path(appdirs.user_data_dir(__title__))
LOG_FILE = pathlib.Path(appdirs.user_log_dir(__title__), 'debug.log')
os.makedirs(str(DATA_DIR),... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
")",
"# Make Chronophore's directories and files in $HOME",
"DATA_DIR",
"=",
"pathlib",
".",
"Path",
"(",
"appdirs",
".",
"user_data_dir",
"(",
"__title__",
")",
")",
"LOG_FILE",
"=",
"pathlib",
".",
... | 32.955882 | 0.000433 |
def apply_sfr_obs():
"""apply the sfr observation process - pairs with setup_sfr_obs().
requires sfr_obs.config. Writes <sfr_out_file>.processed, where
<sfr_out_file> is defined in "sfr_obs.config"
Parameters
----------
None
Returns
-------
df : pd.DataFrame
a dataframe o... | [
"def",
"apply_sfr_obs",
"(",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"\"sfr_obs.config\"",
")",
"df_key",
"=",
"pd",
".",
"read_csv",
"(",
"\"sfr_obs.config\"",
",",
"index_col",
"=",
"0",
")",
"assert",
"df_key",
".",
"iloc",
"[",
"0"... | 34.85 | 0.01605 |
def update(self, request, *args, **kwargs):
"""
Run **PATCH** request against */api/price-list-items/<uuid>/* to update price list item.
Only item_type, key value and units can be updated.
Only customer owner and staff can update price items.
"""
return super(PriceListIte... | [
"def",
"update",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"PriceListItemViewSet",
",",
"self",
")",
".",
"update",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 51.714286 | 0.01087 |
def _build_request(request):
"""Build message to transfer over the socket from a request."""
msg = bytes([request['cmd']])
if 'dest' in request:
msg += bytes([request['dest']])
else:
msg += b'\0'
if 'sha' in request:
msg += request['sha']
else:
for dummy in range(... | [
"def",
"_build_request",
"(",
"request",
")",
":",
"msg",
"=",
"bytes",
"(",
"[",
"request",
"[",
"'cmd'",
"]",
"]",
")",
"if",
"'dest'",
"in",
"request",
":",
"msg",
"+=",
"bytes",
"(",
"[",
"request",
"[",
"'dest'",
"]",
"]",
")",
"else",
":",
... | 28.785714 | 0.002404 |
def get_bcbio_timings(path):
"""Fetch timing information from a bcbio log file."""
with open(path, 'r') as file_handle:
steps = {}
for line in file_handle:
matches = re.search(r'^\[([^\]]+)\] ([^:]+: .*)', line)
if not matches:
continue
tstamp... | [
"def",
"get_bcbio_timings",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"file_handle",
":",
"steps",
"=",
"{",
"}",
"for",
"line",
"in",
"file_handle",
":",
"matches",
"=",
"re",
".",
"search",
"(",
"r'^\\[([^\\]]+)\\] ([^:... | 30.347826 | 0.002778 |
def get_course_list_name(curriculum_abbr, course_number, section_id,
quarter, year, joint=False):
"""
Return the list address of UW course email list
"""
prefix = "multi_" if (joint is True) else ""
return COURSE_LIST_NAME.format(
prefix=prefix,
curr_abbr=_ge... | [
"def",
"get_course_list_name",
"(",
"curriculum_abbr",
",",
"course_number",
",",
"section_id",
",",
"quarter",
",",
"year",
",",
"joint",
"=",
"False",
")",
":",
"prefix",
"=",
"\"multi_\"",
"if",
"(",
"joint",
"is",
"True",
")",
"else",
"\"\"",
"return",
... | 34.928571 | 0.001992 |
def showHeaderMenu( self, pos):
"""
Displays the header menu for this tree widget.
:param pos | <QtCore.QPoint> || None
"""
header = self.header()
index = header.logicalIndexAt(pos)
self._headerIndex = index
# show a pre-s... | [
"def",
"showHeaderMenu",
"(",
"self",
",",
"pos",
")",
":",
"header",
"=",
"self",
".",
"header",
"(",
")",
"index",
"=",
"header",
".",
"logicalIndexAt",
"(",
"pos",
")",
"self",
".",
"_headerIndex",
"=",
"index",
"# show a pre-set menu\r",
"if",
"self",
... | 29.958333 | 0.010782 |
def set_next_input(self, text):
"""Send the specified text to the frontend to be presented at the next
input cell."""
payload = dict(
source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input',
text=text
)
self.payload_manager.write_payload(payload) | [
"def",
"set_next_input",
"(",
"self",
",",
"text",
")",
":",
"payload",
"=",
"dict",
"(",
"source",
"=",
"'IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input'",
",",
"text",
"=",
"text",
")",
"self",
".",
"payload_manager",
".",
"write_payload",
"(",
"payload... | 39 | 0.00627 |
def remove_tenant_user_role(request, project=None, user=None, role=None,
group=None, domain=None):
"""Removes a given single role for a user from a tenant."""
manager = keystoneclient(request, admin=True).roles
if VERSIONS.active < 3:
return manager.remove_user_role(user,... | [
"def",
"remove_tenant_user_role",
"(",
"request",
",",
"project",
"=",
"None",
",",
"user",
"=",
"None",
",",
"role",
"=",
"None",
",",
"group",
"=",
"None",
",",
"domain",
"=",
"None",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"... | 51 | 0.002141 |
def list_pages_ajax(request, invalid_move=False):
"""Render pages table for ajax function."""
language = get_language_from_request(request)
pages = Page.objects.root()
context = {
'can_publish': request.user.has_perm('pages.can_publish'),
'invalid_move': invalid_move,
'language':... | [
"def",
"list_pages_ajax",
"(",
"request",
",",
"invalid_move",
"=",
"False",
")",
":",
"language",
"=",
"get_language_from_request",
"(",
"request",
")",
"pages",
"=",
"Page",
".",
"objects",
".",
"root",
"(",
")",
"context",
"=",
"{",
"'can_publish'",
":",
... | 34.153846 | 0.002193 |
def uavionix_adsb_out_dynamic_send(self, utcTime, gpsLat, gpsLon, gpsAlt, gpsFix, numSats, baroAltMSL, accuracyHor, accuracyVert, accuracyVel, velVert, velNS, VelEW, emergencyStatus, state, squawk, force_mavlink1=False):
'''
Dynamic data used to generate ADS-B out transponder data (send ... | [
"def",
"uavionix_adsb_out_dynamic_send",
"(",
"self",
",",
"utcTime",
",",
"gpsLat",
",",
"gpsLon",
",",
"gpsAlt",
",",
"gpsFix",
",",
"numSats",
",",
"baroAltMSL",
",",
"accuracyHor",
",",
"accuracyVert",
",",
"accuracyVel",
",",
"velVert",
",",
"velNS",
",",... | 108.869565 | 0.007918 |
def delete_attributes(self, request_envelope):
# type: (RequestEnvelope) -> None
"""Deletes attributes from table in Dynamodb resource.
Deletes the attributes from Dynamodb table. Raises
PersistenceException if table doesn't exist or ``delete_item`` fails
on the table.
... | [
"def",
"delete_attributes",
"(",
"self",
",",
"request_envelope",
")",
":",
"# type: (RequestEnvelope) -> None",
"try",
":",
"table",
"=",
"self",
".",
"dynamodb",
".",
"Table",
"(",
"self",
".",
"table_name",
")",
"partition_key_val",
"=",
"self",
".",
"partiti... | 43.862069 | 0.002308 |
def IsAcceptedKey(self, evt):
"""
Return True to allow the given key to start editing: the base class
version only checks that the event has no modifiers. F2 is special
and will always start the editor.
"""
## We can ask the base class to do it
#return super(My... | [
"def",
"IsAcceptedKey",
"(",
"self",
",",
"evt",
")",
":",
"## We can ask the base class to do it",
"#return super(MyCellEditor, self).IsAcceptedKey(evt)",
"# or do it ourselves",
"accepted",
"=",
"super",
"(",
"GridCellEditor",
",",
"self",
")",
".",
"IsAcceptedKey",
"(",
... | 33.210526 | 0.006163 |
def run(itf):
"""
Run preprocess functions
"""
if not itf:
return 1
# access command-line arguments
options = SplitInput(itf)
# read input
infile = os.path.abspath(options.input)
molList = read_csv(infile, options)
# split molList into actives and decoys
activeList, dec... | [
"def",
"run",
"(",
"itf",
")",
":",
"if",
"not",
"itf",
":",
"return",
"1",
"# access command-line arguments",
"options",
"=",
"SplitInput",
"(",
"itf",
")",
"# read input",
"infile",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"options",
".",
"input",
... | 25.333333 | 0.007924 |
def pick_four_unique_nodes_quickly(n, seed=None):
'''
This is equivalent to np.random.choice(n, 4, replace=False)
Another fellow suggested np.random.random_sample(n).argpartition(4) which is
clever but still substantially slower.
'''
rng = get_rng(seed)
k = rng.randint(n**4)
a = k % n
... | [
"def",
"pick_four_unique_nodes_quickly",
"(",
"n",
",",
"seed",
"=",
"None",
")",
":",
"rng",
"=",
"get_rng",
"(",
"seed",
")",
"k",
"=",
"rng",
".",
"randint",
"(",
"n",
"**",
"4",
")",
"a",
"=",
"k",
"%",
"n",
"b",
"=",
"k",
"//",
"n",
"%",
... | 37.826087 | 0.002242 |
def version_str(self):
"""
The version string for the currently-running awslimitchecker;
includes git branch and tag information.
:rtype: str
"""
vs = str(self.release)
if self.tag is not None:
vs += '@{t}'.format(t=self.tag)
elif self.commit ... | [
"def",
"version_str",
"(",
"self",
")",
":",
"vs",
"=",
"str",
"(",
"self",
".",
"release",
")",
"if",
"self",
".",
"tag",
"is",
"not",
"None",
":",
"vs",
"+=",
"'@{t}'",
".",
"format",
"(",
"t",
"=",
"self",
".",
"tag",
")",
"elif",
"self",
".... | 29.615385 | 0.005038 |
def kill(self, exc_info=None):
""" Kill the container in a semi-graceful way.
Entrypoints are killed, followed by any active worker threads.
Next, dependencies are killed. Finally, any remaining managed threads
are killed.
If ``exc_info`` is provided, the exception will be rais... | [
"def",
"kill",
"(",
"self",
",",
"exc_info",
"=",
"None",
")",
":",
"if",
"self",
".",
"_being_killed",
":",
"# this happens if a managed thread exits with an exception",
"# while the container is being killed or if multiple errors",
"# happen simultaneously",
"_log",
".",
"d... | 34.96 | 0.001669 |
def readStoredSms(self, index, memory=None):
""" Reads and returns the SMS message at the specified index
:param index: The index of the SMS message in the specified memory
:type index: int
:param memory: The memory type to read from. If None, use the current default SMS read me... | [
"def",
"readStoredSms",
"(",
"self",
",",
"index",
",",
"memory",
"=",
"None",
")",
":",
"# Switch to the correct memory type if required",
"self",
".",
"_setSmsMemory",
"(",
"readDelete",
"=",
"memory",
")",
"msgData",
"=",
"self",
".",
"write",
"(",
"'AT+CMGR=... | 56.169811 | 0.005612 |
def tz(self):
"""Return the timezone. If none is set use system timezone"""
if not self._tz:
self._tz = tzlocal.get_localzone().zone
return self._tz | [
"def",
"tz",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_tz",
":",
"self",
".",
"_tz",
"=",
"tzlocal",
".",
"get_localzone",
"(",
")",
".",
"zone",
"return",
"self",
".",
"_tz"
] | 36 | 0.01087 |
def copy(self, graph):
""" Returns a copy of the styleguide for the given graph.
"""
g = styleguide(graph)
g.order = self.order
dict.__init__(g, [(k, v) for k, v in self.iteritems()])
return g | [
"def",
"copy",
"(",
"self",
",",
"graph",
")",
":",
"g",
"=",
"styleguide",
"(",
"graph",
")",
"g",
".",
"order",
"=",
"self",
".",
"order",
"dict",
".",
"__init__",
"(",
"g",
",",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"... | 33.428571 | 0.008333 |
def variable_device(device, name):
"""Fix the variable device to colocate its ops."""
if callable(device):
var_name = tf.get_variable_scope().name + '/' + name
var_def = tf.NodeDef(name=var_name, op='Variable')
device = device(var_def)
if device is None:
device = ''
return device | [
"def",
"variable_device",
"(",
"device",
",",
"name",
")",
":",
"if",
"callable",
"(",
"device",
")",
":",
"var_name",
"=",
"tf",
".",
"get_variable_scope",
"(",
")",
".",
"name",
"+",
"'/'",
"+",
"name",
"var_def",
"=",
"tf",
".",
"NodeDef",
"(",
"n... | 32.888889 | 0.016447 |
def ReadPreprocessingInformation(self, knowledge_base):
"""Reads preprocessing information.
The preprocessing information contains the system configuration which
contains information about various system specific configuration data,
for example the user accounts.
Args:
knowledge_base (Knowle... | [
"def",
"ReadPreprocessingInformation",
"(",
"self",
",",
"knowledge_base",
")",
":",
"self",
".",
"_RaiseIfNotWritable",
"(",
")",
"if",
"self",
".",
"_storage_type",
"!=",
"definitions",
".",
"STORAGE_TYPE_SESSION",
":",
"raise",
"IOError",
"(",
"'Preprocessing inf... | 39.571429 | 0.00235 |
def trace(args):
"""
%prog trace unitig{version}.{partID}.{unitigID}
Call `grep` to get the erroneous fragment placement.
"""
p = OptionParser(trace.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
s, = args
version, partID, unitigID = g... | [
"def",
"trace",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"trace",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"p",... | 26.454545 | 0.00221 |
def get_log_entry_form_for_create(self, log_entry_record_types):
"""Gets the log entry form for creating new log entries.
A new form should be requested for each create transaction.
arg: log_entry_record_types (osid.type.Type[]): array of log
entry record types
retur... | [
"def",
"get_log_entry_form_for_create",
"(",
"self",
",",
"log_entry_record_types",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.get_resource_form_for_create_template",
"for",
"arg",
"in",
"log_entry_record_types",
":",
"if",
"not",
"isinstance... | 46.416667 | 0.001758 |
def validate_owner_repo_distro(ctx, param, value):
"""Ensure that owner/repo/distro/version is formatted correctly."""
# pylint: disable=unused-argument
form = "OWNER/REPO/DISTRO[/RELEASE]"
return validate_slashes(param, value, minimum=3, maximum=4, form=form) | [
"def",
"validate_owner_repo_distro",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"# pylint: disable=unused-argument",
"form",
"=",
"\"OWNER/REPO/DISTRO[/RELEASE]\"",
"return",
"validate_slashes",
"(",
"param",
",",
"value",
",",
"minimum",
"=",
"3",
",",
"maxi... | 54.4 | 0.003623 |
def _update_job(job_id, job_dict):
"""Update the database row for the given job_id with the given job_dict.
All functions that update rows in the jobs table do it by calling this
helper function.
job_dict is a dict with values corresponding to the database columns that
should be updated, e.g.:
... | [
"def",
"_update_job",
"(",
"job_id",
",",
"job_dict",
")",
":",
"# Avoid SQLAlchemy \"Unicode type received non-unicode bind param value\"",
"# warnings.",
"if",
"job_id",
":",
"job_id",
"=",
"unicode",
"(",
"job_id",
")",
"if",
"\"error\"",
"in",
"job_dict",
":",
"jo... | 32.666667 | 0.000901 |
def _get_or_open_file(filename):
'''If ``filename`` is a string or bytes object, open the
``filename`` and return the file object. If ``filename`` is
file-like (i.e., it has 'read' and 'write' attributes, return
``filename``.
Parameters
----------
filename : str,... | [
"def",
"_get_or_open_file",
"(",
"filename",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"f",
"=",
"open",
"(",
"filename",
")",
"elif",
"hasattr",
"(",
"filename",
",",
"'read'",
")",
"and",
"hasattr",
... | 31.923077 | 0.002339 |
def trilaterate_v(self, P1, P2, P3, r1, r2, r3):
r'''
Find whether 3 spheres intersect
'''
temp1 = P2-P1
e_x = temp1/np.linalg.norm(temp1, axis=1)[:, np.newaxis]
temp2 = P3-P1
i = self._my_dot(e_x, temp2)[:, np.newaxis]
temp3 = temp2 - i*e_x
e_y = ... | [
"def",
"trilaterate_v",
"(",
"self",
",",
"P1",
",",
"P2",
",",
"P3",
",",
"r1",
",",
"r2",
",",
"r3",
")",
":",
"temp1",
"=",
"P2",
"-",
"P1",
"e_x",
"=",
"temp1",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"temp1",
",",
"axis",
"=",
"1",
... | 39.125 | 0.00312 |
def sort(polylines):
"""
sort points within polyline
p0-p1-p2...
"""
for n, c in enumerate(polylines):
l = len(c)
if l > 2:
# DEFINE FIRST AND LAST INDEX A THOSE TWO POINTS THAT
# HAVE THE BIGGEST DIFFERENCE FROM A MIDDLE:
mid = c.mean(axis=0)
... | [
"def",
"sort",
"(",
"polylines",
")",
":",
"for",
"n",
",",
"c",
"in",
"enumerate",
"(",
"polylines",
")",
":",
"l",
"=",
"len",
"(",
"c",
")",
"if",
"l",
">",
"2",
":",
"# DEFINE FIRST AND LAST INDEX A THOSE TWO POINTS THAT",
"# HAVE THE BIGGEST DIFFERENCE FR... | 27.074074 | 0.002642 |
def serveMonth(self, request, year=None, month=None):
"""Monthly calendar view."""
myurl = self.get_url(request)
def myUrl(urlYear, urlMonth):
if 1900 <= urlYear <= 2099:
return myurl + self.reverse_subpage('serveMonth',
... | [
"def",
"serveMonth",
"(",
"self",
",",
"request",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
")",
":",
"myurl",
"=",
"self",
".",
"get_url",
"(",
"request",
")",
"def",
"myUrl",
"(",
"urlYear",
",",
"urlMonth",
")",
":",
"if",
"1900",
"<=... | 44 | 0.00247 |
def _busy_wait_ms(self, ms):
"""Busy wait for the specified number of milliseconds."""
start = time.time()
delta = ms/1000.0
while (time.time() - start) <= delta:
pass | [
"def",
"_busy_wait_ms",
"(",
"self",
",",
"ms",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"delta",
"=",
"ms",
"/",
"1000.0",
"while",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start",
")",
"<=",
"delta",
":",
"pass"
] | 34.333333 | 0.009479 |
def write_api_docs(self, outdir):
"""Generate API reST files.
Parameters
----------
outdir : string
Directory name in which to store files
We create automatic filenames for each module
Returns
-------
None
Notes
... | [
"def",
"write_api_docs",
"(",
"self",
",",
"outdir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"outdir",
")",
":",
"os",
".",
"mkdir",
"(",
"outdir",
")",
"# compose list of modules",
"modules",
"=",
"self",
".",
"discover_modules",
"... | 25.954545 | 0.006757 |
async def edit_message_media(self,
media: types.InputMedia,
chat_id: typing.Union[typing.Union[base.Integer, base.String], None] = None,
message_id: typing.Union[base.Integer, None] = None,
... | [
"async",
"def",
"edit_message_media",
"(",
"self",
",",
"media",
":",
"types",
".",
"InputMedia",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
",",
"None",
"]",
... | 56.888889 | 0.008065 |
def _RunActions(self, rule, client_id):
"""Run all the actions specified in the rule.
Args:
rule: Rule which actions are to be executed.
client_id: Id of a client where rule's actions are to be executed.
Returns:
Number of actions started.
"""
actions_count = 0
for action in... | [
"def",
"_RunActions",
"(",
"self",
",",
"rule",
",",
"client_id",
")",
":",
"actions_count",
"=",
"0",
"for",
"action",
"in",
"rule",
".",
"actions",
":",
"try",
":",
"# Say this flow came from the foreman.",
"token",
"=",
"self",
".",
"token",
".",
"Copy",
... | 34.866667 | 0.0062 |
def _next_of_kin(self, pos):
"""
looks up the next sibling of the closest ancestor with not-None next
siblings.
"""
candidate = None
parent = self.parent_position(pos)
if parent is not None:
candidate = self.next_sibling_position(parent)
if... | [
"def",
"_next_of_kin",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"parent",
"=",
"self",
".",
"parent_position",
"(",
"pos",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"candidate",
"=",
"self",
".",
"next_sibling_position",
"(",
"pa... | 33.916667 | 0.004785 |
def timeit_grid(stmt_list, setup='', iterations=10000, input_sizes=None,
verbose=True, show=False):
"""
Timeit::
import utool as ut
setup = ut.codeblock(
'''
import utool as ut
from six.moves import range, zip
import time
... | [
"def",
"timeit_grid",
"(",
"stmt_list",
",",
"setup",
"=",
"''",
",",
"iterations",
"=",
"10000",
",",
"input_sizes",
"=",
"None",
",",
"verbose",
"=",
"True",
",",
"show",
"=",
"False",
")",
":",
"import",
"timeit",
"#iterations = timeit.default_number",
"i... | 35.6 | 0.001458 |
def delete_model(self, name):
"""
Delete a model from the registry
:param name: name for the model
"""
try:
ret = self.es.delete(index=self.index_name,
doc_type=self.DOC_TYPE, id=name)
except NotFoundError:
return F... | [
"def",
"delete_model",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"ret",
"=",
"self",
".",
"es",
".",
"delete",
"(",
"index",
"=",
"self",
".",
"index_name",
",",
"doc_type",
"=",
"self",
".",
"DOC_TYPE",
",",
"id",
"=",
"name",
")",
"except",... | 33.076923 | 0.004525 |
def load_keras(json_path=None, hdf5_path=None, by_name=False):
"""
Load a pre-trained Keras model.
:param json_path: The json path containing the keras model definition.
:param hdf5_path: The HDF5 path containing the pre-trained keras model weights with or without the model architecture... | [
"def",
"load_keras",
"(",
"json_path",
"=",
"None",
",",
"hdf5_path",
"=",
"None",
",",
"by_name",
"=",
"False",
")",
":",
"import",
"os",
"try",
":",
"import",
"tensorflow",
"except",
"ImportError",
":",
"os",
".",
"environ",
"[",
"'KERAS_BACKEND'",
"]",
... | 46.214286 | 0.003028 |
def deltas(self):
"""
Dictionary of relative offsets. The keys in the result are
pairs of keys from the offset vector, (a, b), and the
values are the relative offsets, (offset[b] - offset[a]).
Raises ValueError if the offsetvector is empty (WARNING:
this behaviour might change in the future).
Example:
... | [
"def",
"deltas",
"(",
"self",
")",
":",
"# FIXME: instead of raising ValueError when the",
"# offsetvector is empty this should return an empty",
"# dictionary. the inverse, .fromdeltas() accepts",
"# empty dictionaries",
"# NOTE: the arithmetic used to construct the offsets",
"# *must* mat... | 35.948718 | 0.024306 |
def convert_to_units(self, units, equivalence=None, **kwargs):
"""
Convert the array to the given units in-place.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
units : ... | [
"def",
"convert_to_units",
"(",
"self",
",",
"units",
",",
"equivalence",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"units",
"=",
"_sanitize_units_convert",
"(",
"units",
",",
"self",
".",
"units",
".",
"registry",
")",
"if",
"equivalence",
"is",
"... | 39.0875 | 0.000624 |
def DEFINE_float( # pylint: disable=invalid-name,redefined-builtin
name, default, help, lower_bound=None, upper_bound=None,
flag_values=_flagvalues.FLAGS, **args): # pylint: disable=invalid-name
"""Registers a flag whose value must be a float.
If lower_bound or upper_bound are set, then this flag must b... | [
"def",
"DEFINE_float",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"help",
",",
"lower_bound",
"=",
"None",
",",
"upper_bound",
"=",
"None",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"*",
"*",
"args",
")... | 47.409091 | 0.006579 |
def longTouch(self, duration=2000):
'''
Long touches this C{View}
@param duration: duration in ms
'''
(x, y) = self.getCenter()
if self.uiAutomatorHelper:
self.uiAutomatorHelper.swipe(startX=x, startY=y, endX=x, endY=y, steps=200)
else:
#... | [
"def",
"longTouch",
"(",
"self",
",",
"duration",
"=",
"2000",
")",
":",
"(",
"x",
",",
"y",
")",
"=",
"self",
".",
"getCenter",
"(",
")",
"if",
"self",
".",
"uiAutomatorHelper",
":",
"self",
".",
"uiAutomatorHelper",
".",
"swipe",
"(",
"startX",
"="... | 30.538462 | 0.007335 |
def version(self):
"""Fetch version information from all plugins and store in the report
version file"""
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
... | [
"def",
"version",
"(",
"self",
")",
":",
"versions",
"=",
"[",
"]",
"versions",
".",
"append",
"(",
"\"sosreport: %s\"",
"%",
"__version__",
")",
"for",
"plugname",
",",
"plug",
"in",
"self",
".",
"loaded_plugins",
":",
"versions",
".",
"append",
"(",
"\... | 34.833333 | 0.004662 |
def _get_prelim_dependencies(command_template, all_templates):
""" Given a command_template determine which other templates it
depends on. This should not be used as the be-all end-all of
dependencies and before calling each command, ensure that it's
requirements are met.
"""
deps = []
for ... | [
"def",
"_get_prelim_dependencies",
"(",
"command_template",
",",
"all_templates",
")",
":",
"deps",
"=",
"[",
"]",
"for",
"input",
"in",
"command_template",
".",
"input_parts",
":",
"if",
"'.'",
"not",
"in",
"input",
".",
"alias",
":",
"continue",
"for",
"te... | 39.25 | 0.001555 |
def convert_ints_to_bytes(in_ints, num):
"""Convert an integer array into a byte arrays. The number of bytes forming an integer
is defined by num
:param in_ints: the input integers
:param num: the number of bytes per int
:return the integer array"""
out_bytes= b""
for val in in_ints:
... | [
"def",
"convert_ints_to_bytes",
"(",
"in_ints",
",",
"num",
")",
":",
"out_bytes",
"=",
"b\"\"",
"for",
"val",
"in",
"in_ints",
":",
"out_bytes",
"+=",
"struct",
".",
"pack",
"(",
"mmtf",
".",
"utils",
".",
"constants",
".",
"NUM_DICT",
"[",
"num",
"]",
... | 36 | 0.009852 |
def close(self):
"""
Closes this VPCS VM.
"""
if not (yield from super().close()):
return False
nio = self._ethernet_adapter.get_nio(0)
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
if s... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"(",
"yield",
"from",
"super",
"(",
")",
".",
"close",
"(",
")",
")",
":",
"return",
"False",
"nio",
"=",
"self",
".",
"_ethernet_adapter",
".",
"get_nio",
"(",
"0",
")",
"if",
"isinstance",
"(",
... | 30.391304 | 0.006935 |
def annotate(self, *args, **kwargs):
"""
Return a query set in which the returned objects have been annotated
with data aggregated from related fields.
"""
obj = self._clone()
if args:
for arg in args:
if isinstance(arg, Facet):
... | [
"def",
"annotate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"args",
":",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Facet",
")",
":",
"obj",... | 48.472222 | 0.009551 |
def make_inference_acceptance_rate_plot(workflow, inference_file, output_dir,
name="inference_rate", analysis_seg=None, tags=None):
""" Sets up the acceptance rate plot in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are... | [
"def",
"make_inference_acceptance_rate_plot",
"(",
"workflow",
",",
"inference_file",
",",
"output_dir",
",",
"name",
"=",
"\"inference_rate\"",
",",
"analysis_seg",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# default values",
"tags",
"=",
"[",
"]",
"if"... | 33.085106 | 0.002498 |
def add_list(self, bl):
"""
note that this pushes the cur_element, but doesn't pop it.
You'll need to do that
"""
# text:list doesn't like being a child of text:p
if self.cur_element is None:
self.add_text_frame()
self.push_element()
self.cur_e... | [
"def",
"add_list",
"(",
"self",
",",
"bl",
")",
":",
"# text:list doesn't like being a child of text:p",
"if",
"self",
".",
"cur_element",
"is",
"None",
":",
"self",
".",
"add_text_frame",
"(",
")",
"self",
".",
"push_element",
"(",
")",
"self",
".",
"cur_elem... | 37.5 | 0.003252 |
def iterprogress( sized_iterable ):
"""
Iterate something printing progress bar to stdout
"""
pb = ProgressBar( 0, len( sized_iterable ) )
for i, value in enumerate( sized_iterable ):
yield value
pb.update_and_print( i, sys.stderr ) | [
"def",
"iterprogress",
"(",
"sized_iterable",
")",
":",
"pb",
"=",
"ProgressBar",
"(",
"0",
",",
"len",
"(",
"sized_iterable",
")",
")",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"sized_iterable",
")",
":",
"yield",
"value",
"pb",
".",
"update_an... | 32.625 | 0.041045 |
def insert_ref_annotation(self, id_tier, tier2, time, value='',
prev=None, svg=None):
""".. deprecated:: 1.2
Use :func:`add_ref_annotation` instead.
"""
return self.add_ref_annotation(id_tier, tier2, time, value, prev, svg) | [
"def",
"insert_ref_annotation",
"(",
"self",
",",
"id_tier",
",",
"tier2",
",",
"time",
",",
"value",
"=",
"''",
",",
"prev",
"=",
"None",
",",
"svg",
"=",
"None",
")",
":",
"return",
"self",
".",
"add_ref_annotation",
"(",
"id_tier",
",",
"tier2",
","... | 40 | 0.01049 |
def _sbase_annotations(sbase, annotation):
"""Set SBase annotations based on cobra annotations.
Parameters
----------
sbase : libsbml.SBase
SBML object to annotate
annotation : cobra annotation structure
cobra object with annotation information
FIXME: annotation format must be ... | [
"def",
"_sbase_annotations",
"(",
"sbase",
",",
"annotation",
")",
":",
"if",
"not",
"annotation",
"or",
"len",
"(",
"annotation",
")",
"==",
"0",
":",
"return",
"# standardize annotations",
"annotation_data",
"=",
"deepcopy",
"(",
"annotation",
")",
"for",
"k... | 36.263158 | 0.000353 |
def _find_usage_instances(self):
"""find usage for DB Instances and related limits"""
paginator = self.conn.get_paginator('describe_db_instances')
for page in paginator.paginate():
for instance in page['DBInstances']:
self.limits['Read replicas per master']._add_curre... | [
"def",
"_find_usage_instances",
"(",
"self",
")",
":",
"paginator",
"=",
"self",
".",
"conn",
".",
"get_paginator",
"(",
"'describe_db_instances'",
")",
"for",
"page",
"in",
"paginator",
".",
"paginate",
"(",
")",
":",
"for",
"instance",
"in",
"page",
"[",
... | 52.7 | 0.003731 |
def CreateRecord(record_type, host, results):
"""
Create a record of type (record_type) and fill it with the given
dict of results
"""
record_class = dns_tag_lookup[record_type]
record = etree.Element("a")
record.set("host", host)
for params in results:
... | [
"def",
"CreateRecord",
"(",
"record_type",
",",
"host",
",",
"results",
")",
":",
"record_class",
"=",
"dns_tag_lookup",
"[",
"record_type",
"]",
"record",
"=",
"etree",
".",
"Element",
"(",
"\"a\"",
")",
"record",
".",
"set",
"(",
"\"host\"",
",",
"host",... | 33 | 0.005894 |
def _parse_include_section(cfg, parser, section):
'''
Example of include section:
[include]
flt: /etc/feat/flt.ini
ducksboard: /etc/feat/ducksboard.ini
'''
for _name, pattern in cfg.items(section):
if not os.path.isabs(pattern):
pattern = os.path.join(configure.confdir, p... | [
"def",
"_parse_include_section",
"(",
"cfg",
",",
"parser",
",",
"section",
")",
":",
"for",
"_name",
",",
"pattern",
"in",
"cfg",
".",
"items",
"(",
"section",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"pattern",
")",
":",
"patter... | 31.733333 | 0.002041 |
def reserve(self, location=None, force=False, wait_for_up=True, timeout=80):
""" Reserve port and optionally wait for port to come up.
:param location: port location as 'ip/module/port'. If None, the location will be taken from the configuration.
:param force: whether to revoke existing reserva... | [
"def",
"reserve",
"(",
"self",
",",
"location",
"=",
"None",
",",
"force",
"=",
"False",
",",
"wait_for_up",
"=",
"True",
",",
"timeout",
"=",
"80",
")",
":",
"if",
"not",
"location",
"or",
"is_local_host",
"(",
"location",
")",
":",
"return",
"hostnam... | 40.666667 | 0.004003 |
def submit_tag_batch(self, batch):
"""Submit a tag batch"""
url = '%s/api/v5/batch/tags' % self.base_url
self._submit_batch(url, batch) | [
"def",
"submit_tag_batch",
"(",
"self",
",",
"batch",
")",
":",
"url",
"=",
"'%s/api/v5/batch/tags'",
"%",
"self",
".",
"base_url",
"self",
".",
"_submit_batch",
"(",
"url",
",",
"batch",
")"
] | 39 | 0.012579 |
def get_commands(mod):
"""
Find commands from a module
"""
import inspect
import types
commands = {}
def check(c):
return (inspect.isclass(c) and
issubclass(c, Command) and c is not Command and not issubclass(c, CommandManager))
for name in dir(mod):
... | [
"def",
"get_commands",
"(",
"mod",
")",
":",
"import",
"inspect",
"import",
"types",
"commands",
"=",
"{",
"}",
"def",
"check",
"(",
"c",
")",
":",
"return",
"(",
"inspect",
".",
"isclass",
"(",
"c",
")",
"and",
"issubclass",
"(",
"c",
",",
"Command"... | 21.631579 | 0.006993 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.