text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def center_bonds(self):
""" get list of bonds of reaction center (bonds with dynamic orders).
"""
return [(n, m) for n, m, bond in self.bonds() if bond._reactant != bond._product] | [
"def",
"center_bonds",
"(",
"self",
")",
":",
"return",
"[",
"(",
"n",
",",
"m",
")",
"for",
"n",
",",
"m",
",",
"bond",
"in",
"self",
".",
"bonds",
"(",
")",
"if",
"bond",
".",
"_reactant",
"!=",
"bond",
".",
"_product",
"]"
] | 50 | 0.014778 |
def chunker(iterable, size=5, fill=''):
"""Chunk the iterable.
Parameters
----------
iterable
A list.
size
The size of the chunks.
fill
Fill value if the chunk is not of length 'size'.
Yields
-------
chunk
A chunk of length 'size'.
Examples
... | [
"def",
"chunker",
"(",
"iterable",
",",
"size",
"=",
"5",
",",
"fill",
"=",
"''",
")",
":",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"iterable",
")",
"//",
"size",
"+",
"1",
")",
":",
"to_yield",
"=",
"iterable",
"[",
"index",
... | 20.634146 | 0.001129 |
def _update(self):
"""compute/update all derived data
Can be called without harm and is idem-potent.
Updates these attributes and methods:
:attr:`origin`
the center of the cell with index 0,0,0
:attr:`midpoints`
centre coordinate of each grid c... | [
"def",
"_update",
"(",
"self",
")",
":",
"self",
".",
"delta",
"=",
"numpy",
".",
"array",
"(",
"list",
"(",
"map",
"(",
"lambda",
"e",
":",
"(",
"e",
"[",
"-",
"1",
"]",
"-",
"e",
"[",
"0",
"]",
")",
"/",
"(",
"len",
"(",
"e",
")",
"-",
... | 40.333333 | 0.002307 |
def url(self, **params):
"""Build a URL path for image or info request.
An IIIF Image request with parameterized form is assumed unless
the info parameter is specified, in which case an Image Information
request URI is constructred.
"""
self._setattrs(**params)
p... | [
"def",
"url",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"self",
".",
"_setattrs",
"(",
"*",
"*",
"params",
")",
"path",
"=",
"self",
".",
"baseurl",
"+",
"self",
".",
"quote",
"(",
"self",
".",
"identifier",
")",
"+",
"\"/\"",
"if",
"(",
... | 37.191489 | 0.001115 |
def lookup(*args, **kwargs):
"""
Use arguments to route constructor.
Applies a series of checks on arguments to identify constructor,
starting with known keyword arguments, and then applying
constructor-specific checks
"""
if 'mode' in kwargs:
mode = kwargs['mode']
if mode n... | [
"def",
"lookup",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mode'",
"in",
"kwargs",
":",
"mode",
"=",
"kwargs",
"[",
"'mode'",
"]",
"if",
"mode",
"not",
"in",
"constructors",
":",
"raise",
"ValueError",
"(",
"'Mode %s not supported'",
... | 32.421053 | 0.001577 |
def apply_plugin_settings(self, options):
"""Apply configuration file's plugin settings"""
color_scheme_n = 'color_scheme_name'
color_scheme_o = self.get_color_scheme()
font_n = 'plugin_font'
font_o = self.get_plugin_font()
wrap_n = 'wrap'
wrap_o = self.get... | [
"def",
"apply_plugin_settings",
"(",
"self",
",",
"options",
")",
":",
"color_scheme_n",
"=",
"'color_scheme_name'",
"color_scheme_o",
"=",
"self",
".",
"get_color_scheme",
"(",
")",
"font_n",
"=",
"'plugin_font'",
"font_o",
"=",
"self",
".",
"get_plugin_font",
"(... | 44.761905 | 0.002083 |
def function(
name,
tgt,
ssh=False,
tgt_type='glob',
ret='',
ret_config=None,
ret_kwargs=None,
expect_minions=False,
fail_minions=None,
fail_function=None,
arg=None,
kwarg=None,
timeout=None,
batch=None,
... | [
"def",
"function",
"(",
"name",
",",
"tgt",
",",
"ssh",
"=",
"False",
",",
"tgt_type",
"=",
"'glob'",
",",
"ret",
"=",
"''",
",",
"ret_config",
"=",
"None",
",",
"ret_kwargs",
"=",
"None",
",",
"expect_minions",
"=",
"False",
",",
"fail_minions",
"=",
... | 29.346369 | 0.001105 |
def _ncc_c(x, y):
"""
>>> _ncc_c([1,2,3,4], [1,2,3,4])
array([ 0.13333333, 0.36666667, 0.66666667, 1. , 0.66666667,
0.36666667, 0.13333333])
>>> _ncc_c([1,1,1], [1,1,1])
array([ 0.33333333, 0.66666667, 1. , 0.66666667, 0.33333333])
>>> _ncc_c([1,2,3], [-1,-1,-1... | [
"def",
"_ncc_c",
"(",
"x",
",",
"y",
")",
":",
"den",
"=",
"np",
".",
"array",
"(",
"norm",
"(",
"x",
")",
"*",
"norm",
"(",
"y",
")",
")",
"den",
"[",
"den",
"==",
"0",
"]",
"=",
"np",
".",
"Inf",
"x_len",
"=",
"len",
"(",
"x",
")",
"f... | 36.888889 | 0.001468 |
def Jacobi(self,*args,**kwargs):
"""
NAME:
Jacobi
PURPOSE:
calculate the Jacobi integral of the motion
INPUT:
Omega - pattern speed of rotating frame
t= time
pot= potential instance or list of such instances
OUTPUT:
... | [
"def",
"Jacobi",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"'OmegaP'",
"in",
"kwargs",
"or",
"kwargs",
"[",
"'OmegaP'",
"]",
"is",
"None",
":",
"OmegaP",
"=",
"1.",
"if",
"not",
"'pot'",
"in",
"kwargs",
"or",
... | 36.36 | 0.019818 |
def read_hatlc(hatlc):
'''
This reads a consolidated HAT LC written by the functions above.
Returns a dict.
'''
lcfname = os.path.basename(hatlc)
# unzip the files first
if '.gz' in lcfname:
lcf = gzip.open(hatlc,'rb')
elif '.bz2' in lcfname:
lcf = bz2.BZ2File(hatlc, ... | [
"def",
"read_hatlc",
"(",
"hatlc",
")",
":",
"lcfname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"hatlc",
")",
"# unzip the files first",
"if",
"'.gz'",
"in",
"lcfname",
":",
"lcf",
"=",
"gzip",
".",
"open",
"(",
"hatlc",
",",
"'rb'",
")",
"elif",... | 31.580645 | 0.001981 |
def configure_logger(name, log_stream=sys.stdout, log_file=None,
log_level=logging.INFO, keep_old_handlers=False,
propagate=False):
"""Configures and returns a logger.
This function serves to simplify the configuration of a logger that
writes to a file and/or to a ... | [
"def",
"configure_logger",
"(",
"name",
",",
"log_stream",
"=",
"sys",
".",
"stdout",
",",
"log_file",
"=",
"None",
",",
"log_level",
"=",
"logging",
".",
"INFO",
",",
"keep_old_handlers",
"=",
"False",
",",
"propagate",
"=",
"False",
")",
":",
"# create a... | 31.95 | 0.000759 |
def load(cls, stream, contentType=None, version=None):
'''
Reverses the effects of the :meth:`dump` method, creating a FileItem
from the specified file-like `stream` object.
'''
if contentType is None:
contentType = constants.TYPE_OMADS_FILE
if ctype.getBaseType(contentType) == constants.T... | [
"def",
"load",
"(",
"cls",
",",
"stream",
",",
"contentType",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"if",
"contentType",
"is",
"None",
":",
"contentType",
"=",
"constants",
".",
"TYPE_OMADS_FILE",
"if",
"ctype",
".",
"getBaseType",
"(",
"co... | 41.595238 | 0.009508 |
def get_records_for_package(self, package_name):
"""
Get all records identified by package.
"""
result = []
result.extend(self.package_module_map.get(package_name))
return result | [
"def",
"get_records_for_package",
"(",
"self",
",",
"package_name",
")",
":",
"result",
"=",
"[",
"]",
"result",
".",
"extend",
"(",
"self",
".",
"package_module_map",
".",
"get",
"(",
"package_name",
")",
")",
"return",
"result"
] | 27.5 | 0.008811 |
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '{first_name} {last_name}'.format(first_name=self.first_name, last_name=self.last_name)
return full_name.strip() | [
"def",
"get_full_name",
"(",
"self",
")",
":",
"full_name",
"=",
"'{first_name} {last_name}'",
".",
"format",
"(",
"first_name",
"=",
"self",
".",
"first_name",
",",
"last_name",
"=",
"self",
".",
"last_name",
")",
"return",
"full_name",
".",
"strip",
"(",
"... | 43.333333 | 0.011321 |
def group(__decorated__, **Config):
r"""A decorator to make groups out of classes.
Config:
* name (str): The name of the group. Defaults to __decorated__.__name__.
* desc (str): The description of the group (optional).
* alias (str): The alias for the group (optional).
"""
_Group = Group(__decorate... | [
"def",
"group",
"(",
"__decorated__",
",",
"*",
"*",
"Config",
")",
":",
"_Group",
"=",
"Group",
"(",
"__decorated__",
",",
"Config",
")",
"if",
"isclass",
"(",
"__decorated__",
")",
":",
"# convert the method of the class to static methods so that they could be acces... | 35.5 | 0.013722 |
def setup(self):
"""Setup main window"""
logger.info("*** Start of MainWindow setup ***")
logger.info("Applying theme configuration...")
ui_theme = CONF.get('appearance', 'ui_theme')
color_scheme = CONF.get('appearance', 'selected')
if ui_theme == 'dark':
... | [
"def",
"setup",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"*** Start of MainWindow setup ***\"",
")",
"logger",
".",
"info",
"(",
"\"Applying theme configuration...\"",
")",
"ui_theme",
"=",
"CONF",
".",
"get",
"(",
"'appearance'",
",",
"'ui_theme'",
... | 47.736215 | 0.001927 |
def save(self, chunk_size=DEFAULT_DATA_CHUNK_SIZE, named=False):
"""
Get a tarball of an image. Similar to the ``docker save`` command.
Args:
chunk_size (int): The generator will return up to that much data
per iteration, but may return less. If ``None``, data will b... | [
"def",
"save",
"(",
"self",
",",
"chunk_size",
"=",
"DEFAULT_DATA_CHUNK_SIZE",
",",
"named",
"=",
"False",
")",
":",
"img",
"=",
"self",
".",
"id",
"if",
"named",
":",
"img",
"=",
"self",
".",
"tags",
"[",
"0",
"]",
"if",
"self",
".",
"tags",
"else... | 39.634146 | 0.001201 |
def convert_raw_html(text: str, format: Optional[str] = None) -> "applyJSONFilters":
"""Apply the `raw_html_filter` action to the text."""
return applyJSONFilters([raw_html_filter], text, format=format) | [
"def",
"convert_raw_html",
"(",
"text",
":",
"str",
",",
"format",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"\"applyJSONFilters\"",
":",
"return",
"applyJSONFilters",
"(",
"[",
"raw_html_filter",
"]",
",",
"text",
",",
"format",
"=",
"form... | 69.333333 | 0.009524 |
def rectwv_coeff_add_longslit_model(rectwv_coeff, geometry, debugplot=0):
"""Compute longslit_model coefficients for RectWaveCoeff object.
Parameters
----------
rectwv_coeff : RectWaveCoeff instance
Rectification and wavelength calibration coefficients for a
particular CSU configuration... | [
"def",
"rectwv_coeff_add_longslit_model",
"(",
"rectwv_coeff",
",",
"geometry",
",",
"debugplot",
"=",
"0",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# check grism and filter",
"grism_name",
"=",
"rectwv_coeff",
".",
"tags",
"[",... | 36.520179 | 0.00012 |
def _xy2hash(x, y, dim):
"""Convert (x, y) to hashcode.
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
x: int x value of point [0, dim) in dim x dim coord system
y: int ... | [
"def",
"_xy2hash",
"(",
"x",
",",
"y",
",",
"dim",
")",
":",
"d",
"=",
"0",
"lvl",
"=",
"dim",
">>",
"1",
"while",
"(",
"lvl",
">",
"0",
")",
":",
"rx",
"=",
"int",
"(",
"(",
"x",
"&",
"lvl",
")",
">",
"0",
")",
"ry",
"=",
"int",
"(",
... | 29.923077 | 0.001245 |
def apply(self, cls, originalMemberNameList, memberName, classNamingConvention, getter, setter):
"""
:type cls: type
:type originalMemberNameList: list(str)
:type memberName: str
:type classNamingConvention: INamingConvention|None
"""
# The new property.
originalProperty = None
... | [
"def",
"apply",
"(",
"self",
",",
"cls",
",",
"originalMemberNameList",
",",
"memberName",
",",
"classNamingConvention",
",",
"getter",
",",
"setter",
")",
":",
"# The new property.",
"originalProperty",
"=",
"None",
"if",
"memberName",
"in",
"originalMemberNameList... | 50.75 | 0.008058 |
def defaulted_property(self, target, option_name):
"""Computes a language property setting for the given JvmTarget.
:param selector A function that takes a target or platform and returns the boolean value of the
property for that target or platform, or None if that target or platform does
... | [
"def",
"defaulted_property",
"(",
"self",
",",
"target",
",",
"option_name",
")",
":",
"if",
"target",
".",
"has_sources",
"(",
"'.java'",
")",
":",
"matching_subsystem",
"=",
"Java",
".",
"global_instance",
"(",
")",
"elif",
"target",
".",
"has_sources",
"(... | 46.444444 | 0.009379 |
def lunch(rest):
"Pick where to go to lunch"
rs = rest.strip()
if not rs:
return "Give me an area and I'll pick a place: (%s)" % (
', '.join(list(pmxbot.config.lunch_choices)))
if rs not in pmxbot.config.lunch_choices:
return "I didn't recognize that area; here's what i have: (%s)" % (
', '.join(list(pmxb... | [
"def",
"lunch",
"(",
"rest",
")",
":",
"rs",
"=",
"rest",
".",
"strip",
"(",
")",
"if",
"not",
"rs",
":",
"return",
"\"Give me an area and I'll pick a place: (%s)\"",
"%",
"(",
"', '",
".",
"join",
"(",
"list",
"(",
"pmxbot",
".",
"config",
".",
"lunch_c... | 37.272727 | 0.02619 |
def deleteMapping(self, name, vpName, verbose=None):
"""
Deletes the Visual Property mapping specified by the `vpName` and `name` parameters.
:param name: Name of the Visual Style containing the Visual Mapping
:param vpName: Name of the Visual Property that the Visual Mapping controls
... | [
"def",
"deleteMapping",
"(",
"self",
",",
"name",
",",
"vpName",
",",
"verbose",
"=",
"None",
")",
":",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'styles/'",
"+",
"str",
"(",
"name",
")",
"+",
"'/mappings/'",
"+",
"str",
... | 42.076923 | 0.010733 |
def get_weather_name(self, ip):
''' Get weather_name '''
rec = self.get_all(ip)
return rec and rec.weather_name | [
"def",
"get_weather_name",
"(",
"self",
",",
"ip",
")",
":",
"rec",
"=",
"self",
".",
"get_all",
"(",
"ip",
")",
"return",
"rec",
"and",
"rec",
".",
"weather_name"
] | 33 | 0.014815 |
def matching_files(self):
"""
Find files.
Returns:
list: the list of matching files.
"""
matching = []
matcher = self.file_path_regex
pieces = self.file_path_regex.pattern.split(sep)
partial_matchers = list(map(re.compile, (
sep.jo... | [
"def",
"matching_files",
"(",
"self",
")",
":",
"matching",
"=",
"[",
"]",
"matcher",
"=",
"self",
".",
"file_path_regex",
"pieces",
"=",
"self",
".",
"file_path_regex",
".",
"pattern",
".",
"split",
"(",
"sep",
")",
"partial_matchers",
"=",
"list",
"(",
... | 33.88 | 0.002296 |
def compose_ants_transforms(transform_list):
"""
Compose multiple ANTsTransform's together
ANTsR function: `composeAntsrTransforms`
Arguments
---------
transform_list : list/tuple of ANTsTransform object
list of transforms to compose together
Returns
-------
ANTsTransform
... | [
"def",
"compose_ants_transforms",
"(",
"transform_list",
")",
":",
"precision",
"=",
"transform_list",
"[",
"0",
"]",
".",
"precision",
"dimension",
"=",
"transform_list",
"[",
"0",
"]",
".",
"dimension",
"for",
"tx",
"in",
"transform_list",
":",
"if",
"precis... | 38.021739 | 0.00223 |
def _validate_sample_rates(input_filepath_list, combine_type):
''' Check if files in input file list have the same sample rate
'''
sample_rates = [
file_info.sample_rate(f) for f in input_filepath_list
]
if not core.all_equal(sample_rates):
raise IOError(
"Input files do ... | [
"def",
"_validate_sample_rates",
"(",
"input_filepath_list",
",",
"combine_type",
")",
":",
"sample_rates",
"=",
"[",
"file_info",
".",
"sample_rate",
"(",
"f",
")",
"for",
"f",
"in",
"input_filepath_list",
"]",
"if",
"not",
"core",
".",
"all_equal",
"(",
"sam... | 39.083333 | 0.002083 |
def set_static_ip_address(self, payload):
"""Set static ip address for a VM."""
# This request is received from CLI for setting ip address of an
# instance.
macaddr = payload.get('mac')
ipaddr = payload.get('ip')
# Find the entry associated with the mac in the database.... | [
"def",
"set_static_ip_address",
"(",
"self",
",",
"payload",
")",
":",
"# This request is received from CLI for setting ip address of an",
"# instance.",
"macaddr",
"=",
"payload",
".",
"get",
"(",
"'mac'",
")",
"ipaddr",
"=",
"payload",
".",
"get",
"(",
"'ip'",
")"... | 46.73913 | 0.000911 |
def clear(self):
"""
Clears all the options in a Combo
"""
self._options = []
self._combo_menu.tk.delete(0, END)
self._selected.set("") | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_options",
"=",
"[",
"]",
"self",
".",
"_combo_menu",
".",
"tk",
".",
"delete",
"(",
"0",
",",
"END",
")",
"self",
".",
"_selected",
".",
"set",
"(",
"\"\"",
")"
] | 25.285714 | 0.010929 |
def handle_api_error(resp):
"""Stolen straight from the Stripe Python source."""
content = yield resp.json()
headers = HeaderWrapper(resp.headers)
try:
err = content['error']
except (KeyError, TypeError):
raise error.APIError(
"Invalid response object from API: %r (HTTP... | [
"def",
"handle_api_error",
"(",
"resp",
")",
":",
"content",
"=",
"yield",
"resp",
".",
"json",
"(",
")",
"headers",
"=",
"HeaderWrapper",
"(",
"resp",
".",
"headers",
")",
"try",
":",
"err",
"=",
"content",
"[",
"'error'",
"]",
"except",
"(",
"KeyErro... | 34.413793 | 0.000975 |
def Print(x, data, message, **kwargs): # pylint: disable=invalid-name
"""Call tf.Print.
Args:
x: a Tensor.
data: a list of Tensor
message: a string
**kwargs: keyword arguments to tf.Print
Returns:
a Tensor which is identical in value to x
"""
return PrintOperation(x, data, message, **kwa... | [
"def",
"Print",
"(",
"x",
",",
"data",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"return",
"PrintOperation",
"(",
"x",
",",
"data",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
".",
"outputs",
"[",
"0",
"]"
] | 27 | 0.008955 |
def biquad(self, b, a):
'''Apply a biquad IIR filter with the given coefficients.
Parameters
----------
b : list of floats
Numerator coefficients. Must be length 3
a : list of floats
Denominator coefficients. Must be length 3
See Also
---... | [
"def",
"biquad",
"(",
"self",
",",
"b",
",",
"a",
")",
":",
"if",
"not",
"isinstance",
"(",
"b",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'b must be a list.'",
")",
"if",
"not",
"isinstance",
"(",
"a",
",",
"list",
")",
":",
"raise",
"Va... | 29.309524 | 0.001572 |
def _load_raster_text(self, raster_path):
"""
Loads grass ASCII to object
"""
# Open file and read plain text into text field
with open(raster_path, 'r') as f:
self.rasterText = f.read()
# Retrieve metadata from header
lines = self.rasterText.split('\... | [
"def",
"_load_raster_text",
"(",
"self",
",",
"raster_path",
")",
":",
"# Open file and read plain text into text field",
"with",
"open",
"(",
"raster_path",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"rasterText",
"=",
"f",
".",
"read",
"(",
")",
"# Retrie... | 36.52 | 0.002134 |
def get_form(self, form_class=None):
"""If the task was only saved, treat all form fields as not required."""
form = super().get_form(form_class)
if self._save:
make_form_or_formset_fields_not_required(form)
return form | [
"def",
"get_form",
"(",
"self",
",",
"form_class",
"=",
"None",
")",
":",
"form",
"=",
"super",
"(",
")",
".",
"get_form",
"(",
"form_class",
")",
"if",
"self",
".",
"_save",
":",
"make_form_or_formset_fields_not_required",
"(",
"form",
")",
"return",
"for... | 43 | 0.011407 |
def from_func(cls, func, variables, vartype, name=None):
"""Construct a constraint from a validation function.
Args:
func (function):
Function that evaluates True when the variables satisfy the constraint.
variables (iterable):
Iterable of variab... | [
"def",
"from_func",
"(",
"cls",
",",
"func",
",",
"variables",
",",
"vartype",
",",
"name",
"=",
"None",
")",
":",
"variables",
"=",
"tuple",
"(",
"variables",
")",
"configurations",
"=",
"frozenset",
"(",
"config",
"for",
"config",
"in",
"itertools",
".... | 35.553571 | 0.002444 |
def get_qtls_from_rqtl_data(matrix, lod_threshold):
""" Retrieve the list of significants QTLs for the given input
matrix and using the specified LOD threshold.
This assumes one QTL per linkage group.
:arg matrix, the MapQTL file read in memory
:arg threshold, threshold used to determine if a given... | [
"def",
"get_qtls_from_rqtl_data",
"(",
"matrix",
",",
"lod_threshold",
")",
":",
"t_matrix",
"=",
"list",
"(",
"zip",
"(",
"*",
"matrix",
")",
")",
"qtls",
"=",
"[",
"[",
"'Trait'",
",",
"'Linkage Group'",
",",
"'Position'",
",",
"'Exact marker'",
",",
"'L... | 34.608696 | 0.000611 |
def setActions( self, actions ):
"""
Sets the list of actions that will be used for this shortcut dialog \
when editing.
:param actions | [<QAction>, ..]
"""
self.uiActionTREE.blockSignals(True)
self.uiActionTREE.setUpdatesEnabled(False)
... | [
"def",
"setActions",
"(",
"self",
",",
"actions",
")",
":",
"self",
".",
"uiActionTREE",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"uiActionTREE",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"self",
".",
"uiActionTREE",
".",
"clear",
"(",
")",
... | 35.117647 | 0.011419 |
def get_collection_class(resource):
"""
Returns the registered collection resource class for the given marker
interface or member resource class or instance.
:param rc: registered resource
:type rc: class implementing or instance providing or subclass of
a registered resource interface.
... | [
"def",
"get_collection_class",
"(",
"resource",
")",
":",
"reg",
"=",
"get_current_registry",
"(",
")",
"if",
"IInterface",
"in",
"provided_by",
"(",
"resource",
")",
":",
"coll_class",
"=",
"reg",
".",
"getUtility",
"(",
"resource",
",",
"name",
"=",
"'coll... | 38.5625 | 0.001582 |
def spread(self, X):
"""
Calculate the average spread for each node.
The average spread is a measure of how far each neuron is from the
data points which cluster to it.
Parameters
----------
X : numpy array
The input data.
Returns
--... | [
"def",
"spread",
"(",
"self",
",",
"X",
")",
":",
"distance",
",",
"_",
"=",
"self",
".",
"distance_function",
"(",
"X",
",",
"self",
".",
"weights",
")",
"dists_per_neuron",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"x",
",",
"y",
"in",
"zip",
... | 28.4 | 0.00227 |
def kick_chat_member(self, *args, **kwargs):
"""See :func:`kick_chat_member`"""
return kick_chat_member(*args, **self._merge_overrides(**kwargs)).run() | [
"def",
"kick_chat_member",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"kick_chat_member",
"(",
"*",
"args",
",",
"*",
"*",
"self",
".",
"_merge_overrides",
"(",
"*",
"*",
"kwargs",
")",
")",
".",
"run",
"(",
")"
] | 55 | 0.011976 |
def merge(id, card, cardscript=None):
"""
Find the xmlcard and the card definition of \a id
Then return a merged class of the two
"""
if card is None:
card = cardxml.CardXML(id)
if cardscript is None:
cardscript = get_script_definition(id)
if cardscript:
card.scripts = type(id, (cardscript, ), ... | [
"def",
"merge",
"(",
"id",
",",
"card",
",",
"cardscript",
"=",
"None",
")",
":",
"if",
"card",
"is",
"None",
":",
"card",
"=",
"cardxml",
".",
"CardXML",
"(",
"id",
")",
"if",
"cardscript",
"is",
"None",
":",
"cardscript",
"=",
"get_script_definition"... | 27.619718 | 0.028065 |
def _to_power_basis12(nodes1, nodes2):
r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that the first curve is
degree one and the second is degree two. In this case, B |eacute|
zout's `theorem`_ tells us that the **intersection polynomial** ... | [
"def",
"_to_power_basis12",
"(",
"nodes1",
",",
"nodes2",
")",
":",
"# We manually invert the Vandermonde matrix:",
"# [1 0 0 ][c0] = [n0]",
"# [1 1/2 1/4][c1] [n1]",
"# [1 1 1 ][c2] [n2]",
"val0",
"=",
"eval_intersection_polynomial",
"(",
"nodes1",
",",
"nodes2",
","... | 35.5625 | 0.000855 |
def CookieAuthSourceInitializer(
secret,
cookie_name='auth',
secure=False,
max_age=None,
httponly=False,
path="/",
domains=None,
debug=False,
hashalg='sha512',
):
""" An authentication source that uses a unique cookie. """
@implementer(IAuthSourceService)
class CookieAut... | [
"def",
"CookieAuthSourceInitializer",
"(",
"secret",
",",
"cookie_name",
"=",
"'auth'",
",",
"secure",
"=",
"False",
",",
"max_age",
"=",
"None",
",",
"httponly",
"=",
"False",
",",
"path",
"=",
"\"/\"",
",",
"domains",
"=",
"None",
",",
"debug",
"=",
"F... | 25.716981 | 0.000707 |
def __get_tags(vm_):
'''
Get configured tags.
'''
t = config.get_cloud_config_value(
'tags', vm_, __opts__,
default='[]', search_global=False)
# Consider warning the user that the tags in the cloud profile
# could not be interpreted, bad formatting?
try:
tags = litera... | [
"def",
"__get_tags",
"(",
"vm_",
")",
":",
"t",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'tags'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"'[]'",
",",
"search_global",
"=",
"False",
")",
"# Consider warning the user that the tags in the cloud ... | 29 | 0.002088 |
def opener(mode='r'):
"""Factory for creating file objects
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the b... | [
"def",
"opener",
"(",
"mode",
"=",
"'r'",
")",
":",
"def",
"open_file",
"(",
"f",
")",
":",
"if",
"f",
"is",
"sys",
".",
"stdout",
"or",
"f",
"is",
"sys",
".",
"stdin",
":",
"return",
"f",
"elif",
"f",
"==",
"'-'",
":",
"return",
"sys",
".",
... | 31.043478 | 0.001359 |
def compare_sym_bands(bands_obj, bands_ref_obj, nb=None):
"""
Compute the mean of correlation between bzt and vasp bandstructure on
sym line, for all bands and locally (for each branches) the difference
squared (%) if nb is specified.
"""
nkpt = len(bands_obj.kpoints)
if bands_ref_obj.is_sp... | [
"def",
"compare_sym_bands",
"(",
"bands_obj",
",",
"bands_ref_obj",
",",
"nb",
"=",
"None",
")",
":",
"nkpt",
"=",
"len",
"(",
"bands_obj",
".",
"kpoints",
")",
"if",
"bands_ref_obj",
".",
"is_spin_polarized",
":",
"nbands",
"=",
"min",
"(",
"bands_obj",
"... | 39.506849 | 0.000677 |
def send(vm, target, key='uuid'):
'''
Send a vm to a directory
vm : string
vm to be sent
target : string
target directory
key : string [uuid|alias|hostname]
value type of 'vm' parameter
CLI Example:
.. code-block:: bash
salt '*' vmadm.send 186da9ab-7392-4f... | [
"def",
"send",
"(",
"vm",
",",
"target",
",",
"key",
"=",
"'uuid'",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"key",
"not",
"in",
"[",
"'uuid'",
",",
"'alias'",
",",
"'hostname'",
"]",
":",
"ret",
"[",
"'Error'",
"]",
"=",
"'Key must be either uuid, alia... | 32.267857 | 0.001611 |
def send(reg_id, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/web/updates/2016/03/web-push-encryption
Desc: Web Push notifications for Chrome and FireFox
Installation:
pip install 'pywebpush>=0.4.0'
"""
subscription_info = kwargs.pop('s... | [
"def",
"send",
"(",
"reg_id",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"subscription_info",
"=",
"kwargs",
".",
"pop",
"(",
"'subscription_info'",
")",
"payload",
"=",
"{",
"\"title\"",
":",
"kwargs",
".",
"pop",
"(",
"\"event\"",
")",
",",
"... | 27.535714 | 0.001253 |
def season_id(x):
"""takes in 4-digit years and returns API formatted seasonID
Input Values: YYYY
Used in:
"""
if len(str(x)) == 4:
try:
return "".join(["2", str(x)])
except ValueError:
raise ValueError("Enter the four digit year for the first half of the ... | [
"def",
"season_id",
"(",
"x",
")",
":",
"if",
"len",
"(",
"str",
"(",
"x",
")",
")",
"==",
"4",
":",
"try",
":",
"return",
"\"\"",
".",
"join",
"(",
"[",
"\"2\"",
",",
"str",
"(",
"x",
")",
"]",
")",
"except",
"ValueError",
":",
"raise",
"Val... | 28.466667 | 0.00907 |
def setup_parser(sub_parsers):
"""
Sets up the command line parser for the *index* subprogram and adds it to *sub_parsers*.
"""
parser = sub_parsers.add_parser("index", prog="law index", description="Create or update the"
" (human-readable) law task index file ({}). This is only required for the... | [
"def",
"setup_parser",
"(",
"sub_parsers",
")",
":",
"parser",
"=",
"sub_parsers",
".",
"add_parser",
"(",
"\"index\"",
",",
"prog",
"=",
"\"law index\"",
",",
"description",
"=",
"\"Create or update the\"",
"\" (human-readable) law task index file ({}). This is only requir... | 61 | 0.01507 |
def load_class(module_name, class_name):
"""Return class object specified by module name and class name.
Return None if module failed to be imported.
:param module_name: string module name
:param class_name: string class name
"""
try:
plugmod = import_module(module_name)
except Exc... | [
"def",
"load_class",
"(",
"module_name",
",",
"class_name",
")",
":",
"try",
":",
"plugmod",
"=",
"import_module",
"(",
"module_name",
")",
"except",
"Exception",
"as",
"exc",
":",
"warn",
"(",
"\"Importing built-in plugin %s.%s raised an exception: %r\"",
"%",
"(",... | 33.25 | 0.001828 |
def download(directory, filename):
"""Downloads a file."""
filepath = os.path.join(directory, filename)
if tf.io.gfile.exists(filepath):
return filepath
if not tf.io.gfile.exists(directory):
tf.io.gfile.makedirs(directory)
url = os.path.join(ROOT_PATH, filename)
print("Downloading %s to %s" % (url, ... | [
"def",
"download",
"(",
"directory",
",",
"filename",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"if",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"(",
"filepath",
")",
":",
"return",
"filepat... | 34.727273 | 0.022959 |
def as_posix(self):
"""Return the string representation of the path with forward (/)
slashes."""
f = self._flavour
return str(self).replace(f.sep, '/') | [
"def",
"as_posix",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"_flavour",
"return",
"str",
"(",
"self",
")",
".",
"replace",
"(",
"f",
".",
"sep",
",",
"'/'",
")"
] | 35.8 | 0.010929 |
def list_returner_functions(*args, **kwargs): # pylint: disable=unused-argument
'''
List the functions for all returner modules. Optionally, specify a returner
module or modules from which to list.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' sys.list_return... | [
"def",
"list_returner_functions",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"# NOTE: **kwargs is used here to prevent a traceback when garbage",
"# arguments are tacked on to the end.",
"returners_",
"=",
"salt",
".",
"loader"... | 29.204545 | 0.001506 |
def detail(device='/dev/md0'):
'''
Show detail for a specified RAID device
CLI Example:
.. code-block:: bash
salt '*' raid.detail '/dev/md0'
'''
ret = {}
ret['members'] = {}
# Lets make sure the device exists before running mdadm
if not os.path.exists(device):
msg... | [
"def",
"detail",
"(",
"device",
"=",
"'/dev/md0'",
")",
":",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'members'",
"]",
"=",
"{",
"}",
"# Lets make sure the device exists before running mdadm",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"device",
")",
":... | 29.465116 | 0.001528 |
def z(self,*args,**kwargs):
"""
NAME:
z
PURPOSE:
return vertical height
INPUT:
t - (optional) time at which to get the vertical height
ro= (Object-wide default) physical scale for distances to use to convert
use_physical= use to over... | [
"def",
"z",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"self",
".",
"vxvv",
")",
"<",
"5",
":",
"raise",
"AttributeError",
"(",
"\"linear and planar orbits do not have z()\"",
")",
"thiso",
"=",
"self",
"(",
"*"... | 34.047619 | 0.016327 |
def _pre_emphasis(self):
"""
Pre-emphasize the entire signal at once by self.emphasis_factor,
overwriting ``self.data``.
"""
self.data = numpy.append(self.data[0], self.data[1:] - self.emphasis_factor * self.data[:-1]) | [
"def",
"_pre_emphasis",
"(",
"self",
")",
":",
"self",
".",
"data",
"=",
"numpy",
".",
"append",
"(",
"self",
".",
"data",
"[",
"0",
"]",
",",
"self",
".",
"data",
"[",
"1",
":",
"]",
"-",
"self",
".",
"emphasis_factor",
"*",
"self",
".",
"data",... | 42.166667 | 0.011628 |
def update_metadata(self, **kwargs):
"""
::
POST /:login/machines/:id/metadata
:Returns: current metadata
:rtype: :py:class:`dict`
Send an metadata dict update for the machine (following dict.update()
semantics) using the keys and v... | [
"def",
"update_metadata",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"j",
",",
"_",
"=",
"self",
".",
"datacenter",
".",
"request",
"(",
"'POST'",
",",
"self",
".",
"path",
"+",
"'/metadata'",
",",
"data",
"=",
"kwargs",
")",
"self",
".",
"met... | 35.777778 | 0.015129 |
def get_section(self, *key):
"""
The recommended way of retrieving a section by key when extending configmanager's behaviour.
"""
section = self._get_item_or_section(key)
if not section.is_section:
raise RuntimeError('{} is an item, not a section'.format(key))
... | [
"def",
"get_section",
"(",
"self",
",",
"*",
"key",
")",
":",
"section",
"=",
"self",
".",
"_get_item_or_section",
"(",
"key",
")",
"if",
"not",
"section",
".",
"is_section",
":",
"raise",
"RuntimeError",
"(",
"'{} is an item, not a section'",
".",
"format",
... | 41 | 0.008955 |
def _init_field(self, setting, field_class, name, code=None):
"""
Initialize a field whether it is built with a custom name for a
specific translation language or not.
"""
kwargs = {
"label": setting["label"] + ":",
"required": setting["type"] in (int, flo... | [
"def",
"_init_field",
"(",
"self",
",",
"setting",
",",
"field_class",
",",
"name",
",",
"code",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"\"label\"",
":",
"setting",
"[",
"\"label\"",
"]",
"+",
"\":\"",
",",
"\"required\"",
":",
"setting",
"[",
"\"t... | 43.714286 | 0.002132 |
def ParseCellSpec (spec):
"""convert cell spec to row,col. Eg. ParseCellSpec("B5") = [2, 5]"""
m = __specRe.match(spec)
(column, row) = m.groups()
return (int(row), ColumnToIndex(column)) | [
"def",
"ParseCellSpec",
"(",
"spec",
")",
":",
"m",
"=",
"__specRe",
".",
"match",
"(",
"spec",
")",
"(",
"column",
",",
"row",
")",
"=",
"m",
".",
"groups",
"(",
")",
"return",
"(",
"int",
"(",
"row",
")",
",",
"ColumnToIndex",
"(",
"column",
")... | 43.8 | 0.013453 |
def get_export_allowable_types(cursor, exports_dirs, id, version):
"""Return export types."""
request = get_current_request()
type_settings = request.registry.settings['_type_info']
type_names = [k for k, v in type_settings]
type_infos = [v for k, v in type_settings]
# We took the type_names dir... | [
"def",
"get_export_allowable_types",
"(",
"cursor",
",",
"exports_dirs",
",",
"id",
",",
"version",
")",
":",
"request",
"=",
"get_current_request",
"(",
")",
"type_settings",
"=",
"request",
".",
"registry",
".",
"settings",
"[",
"'_type_info'",
"]",
"type_name... | 48.269231 | 0.000781 |
def with_onsets(fft_feature):
"""
Produce a mixin class that extracts onsets
:param fft_feature: The short-time fourier transform feature
:return: A mixin class that extracts onsets
"""
class Onsets(BaseModel):
onset_prep = ArrayWithUnitsFeature(
SlidingWindow,
n... | [
"def",
"with_onsets",
"(",
"fft_feature",
")",
":",
"class",
"Onsets",
"(",
"BaseModel",
")",
":",
"onset_prep",
"=",
"ArrayWithUnitsFeature",
"(",
"SlidingWindow",
",",
"needs",
"=",
"fft_feature",
",",
"wscheme",
"=",
"HalfLapped",
"(",
")",
"*",
"Stride",
... | 28.636364 | 0.001024 |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = TextClock(self.get_context(), None, d.style) | [
"def",
"create_widget",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"self",
".",
"widget",
"=",
"TextClock",
"(",
"self",
".",
"get_context",
"(",
")",
",",
"None",
",",
"d",
".",
"style",
")"
] | 28.333333 | 0.011429 |
def _init_metadata(self):
"""stub"""
super(BaseMultiChoiceTextQuestionFormRecord, self)._init_metadata()
self._choice_text_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
... | [
"def",
"_init_metadata",
"(",
"self",
")",
":",
"super",
"(",
"BaseMultiChoiceTextQuestionFormRecord",
",",
"self",
")",
".",
"_init_metadata",
"(",
")",
"self",
".",
"_choice_text_metadata",
"=",
"{",
"'element_id'",
":",
"Id",
"(",
"self",
".",
"my_osid_object... | 39.75 | 0.002047 |
def _pfp__pack_data(self):
"""Pack the nested field
"""
if self._pfp__pack_type is None:
return
tmp_stream = six.BytesIO()
self._._pfp__build(bitwrap.BitwrappedStream(tmp_stream))
raw_data = tmp_stream.getvalue()
unpack_func = self._pfp__packer
... | [
"def",
"_pfp__pack_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pfp__pack_type",
"is",
"None",
":",
"return",
"tmp_stream",
"=",
"six",
".",
"BytesIO",
"(",
")",
"self",
".",
"_",
".",
"_pfp__build",
"(",
"bitwrap",
".",
"BitwrappedStream",
"(",
"t... | 35 | 0.002453 |
def key_description(self):
"Return a description of the key"
vk, scan, flags = self._get_key_info()
desc = ''
if vk:
if vk in CODE_NAMES:
desc = CODE_NAMES[vk]
else:
desc = "VK %d"% vk
else:
desc = "%s"% self.key... | [
"def",
"key_description",
"(",
"self",
")",
":",
"vk",
",",
"scan",
",",
"flags",
"=",
"self",
".",
"_get_key_info",
"(",
")",
"desc",
"=",
"''",
"if",
"vk",
":",
"if",
"vk",
"in",
"CODE_NAMES",
":",
"desc",
"=",
"CODE_NAMES",
"[",
"vk",
"]",
"else... | 25.307692 | 0.01173 |
def inject(self, request, response):
"""
Inject the debug toolbar iframe into an HTML response.
"""
# called in host app
if not isinstance(response, Response):
return
settings = request.app[APP_KEY]['settings']
response_html = response.body
rou... | [
"def",
"inject",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"# called in host app",
"if",
"not",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"return",
"settings",
"=",
"request",
".",
"app",
"[",
"APP_KEY",
"]",
"[",
"'settings'"... | 39.1 | 0.001664 |
def build_packet(packet_type, gateway, bulb, payload_fmt, *payload_args,
**kwargs):
"""
Constructs a Lifx packet, returning a bytestring. The arguments are as
follows:
- `packet_type`, an integer
- `gateway`, a 6-byte string containing the mac address of the gateway bulb
- `bul... | [
"def",
"build_packet",
"(",
"packet_type",
",",
"gateway",
",",
"bulb",
",",
"payload_fmt",
",",
"*",
"payload_args",
",",
"*",
"*",
"kwargs",
")",
":",
"protocol",
"=",
"kwargs",
".",
"get",
"(",
"'protocol'",
",",
"COMMAND_PROTOCOL",
")",
"packet_fmt",
"... | 38.827586 | 0.000867 |
def getResultsRange(self):
"""Returns the valid result range for this reference analysis based on
the results ranges defined in the Reference Sample from which this
analysis has been created.
A Reference Analysis (control or blank) will be considered out of range
if its results ... | [
"def",
"getResultsRange",
"(",
"self",
")",
":",
"specs",
"=",
"ResultsRangeDict",
"(",
"result",
"=",
"\"\"",
")",
"sample",
"=",
"self",
".",
"getSample",
"(",
")",
"if",
"not",
"sample",
":",
"return",
"specs",
"service_uid",
"=",
"self",
".",
"getSer... | 42.35 | 0.002309 |
def users(self):
"""
Gets the Users API client.
Returns:
Users:
"""
if not self.__users:
self.__users = Users(self.__connection)
return self.__users | [
"def",
"users",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__users",
":",
"self",
".",
"__users",
"=",
"Users",
"(",
"self",
".",
"__connection",
")",
"return",
"self",
".",
"__users"
] | 21.2 | 0.00905 |
def flake(self, message):
"""Print an error message to stdout."""
self.stdout.write(str(message))
self.stdout.write('\n') | [
"def",
"flake",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"str",
"(",
"message",
")",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")"
] | 35.5 | 0.013793 |
async def get_frozen(self, *args, **kwargs):
"""
Get frozen users balance
Accepts:
- uid [integer] (users id)
- types [list | string] (array with needed types or "all")
Returns:
{
type [string] (blockchain type): amount
}
"""
super().validate(*args, **kwargs)
if kwargs.get("message"):
... | [
"async",
"def",
"get_frozen",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"validate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"kwargs",
".",
"get",
"(",
"\"message\"",
")",
":",
"kwargs"... | 26.134328 | 0.034673 |
def netstat(name):
'''
Retrieve the netstat information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.netstat apache2
'''
sanitize_name = six.text_type(name)
netstat_infos = __salt__['cmd.run']("netstat -nap")
found_infos = []
ret = []
for in... | [
"def",
"netstat",
"(",
"name",
")",
":",
"sanitize_name",
"=",
"six",
".",
"text_type",
"(",
"name",
")",
"netstat_infos",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"\"netstat -nap\"",
")",
"found_infos",
"=",
"[",
"]",
"ret",
"=",
"[",
"]",
"for",
... | 25 | 0.002028 |
def sort_like(l, col1, col2):
'''
Sorts the list :py:obj:`l` by comparing :py:obj:`col2` to :py:obj:`col1`.
Specifically, finds the indices :py:obj:`i` such that ``col2[i] = col1``
and returns ``l[i]``. This is useful when comparing the CDPP values of
catalogs generated by different pipelines. The
... | [
"def",
"sort_like",
"(",
"l",
",",
"col1",
",",
"col2",
")",
":",
"s",
"=",
"np",
".",
"zeros_like",
"(",
"col1",
")",
"*",
"np",
".",
"nan",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"col1",
")",
":",
"j",
"=",
"np",
".",
"argmax",
"(",
... | 37.6 | 0.002075 |
def solve(self, S, dimK=None):
"""Compute sparse coding and dictionary update for training
data `S`."""
# Use dimK specified in __init__ as default
if dimK is None and self.dimK is not None:
dimK = self.dimK
# Start solve timer
self.timer.start(['solve', 'so... | [
"def",
"solve",
"(",
"self",
",",
"S",
",",
"dimK",
"=",
"None",
")",
":",
"# Use dimK specified in __init__ as default",
"if",
"dimK",
"is",
"None",
"and",
"self",
".",
"dimK",
"is",
"not",
"None",
":",
"dimK",
"=",
"self",
".",
"dimK",
"# Start solve tim... | 26.133333 | 0.00246 |
def get_command_line(self):
"""Returns the command line for the job."""
# In python 2, the command line is unicode, which needs to be converted to string before pickling;
# In python 3, the command line is bytes, which can be pickled directly
return loads(self.command_line) if isinstance(self.command_li... | [
"def",
"get_command_line",
"(",
"self",
")",
":",
"# In python 2, the command line is unicode, which needs to be converted to string before pickling;",
"# In python 3, the command line is bytes, which can be pickled directly",
"return",
"loads",
"(",
"self",
".",
"command_line",
")",
"... | 73 | 0.00813 |
def try_binding(self):
"""
Searches for the required service if needed
:raise BundleException: Invalid ServiceReference found
"""
with self._lock:
if self.reference is not None:
# Already bound
return
if self._pending_ref ... | [
"def",
"try_binding",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"reference",
"is",
"not",
"None",
":",
"# Already bound",
"return",
"if",
"self",
".",
"_pending_ref",
"is",
"not",
"None",
":",
"# Get the reference we chose ... | 33.166667 | 0.002442 |
def calculateSignature(privateSigningKey, message):
"""
:type privateSigningKey: ECPrivateKey
:type message: bytearray
"""
if privateSigningKey.getType() == Curve.DJB_TYPE:
rand = os.urandom(64)
res = _curve.calculateSignature(rand, privateSigningKey.getP... | [
"def",
"calculateSignature",
"(",
"privateSigningKey",
",",
"message",
")",
":",
"if",
"privateSigningKey",
".",
"getType",
"(",
")",
"==",
"Curve",
".",
"DJB_TYPE",
":",
"rand",
"=",
"os",
".",
"urandom",
"(",
"64",
")",
"res",
"=",
"_curve",
".",
"calc... | 41.454545 | 0.008584 |
def _write_file_iface(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
... | [
"def",
"_write_file_iface",
"(",
"iface",
",",
"data",
",",
"folder",
",",
"pattern",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"pattern",
".",
"format",
"(",
"iface",
")",
")",
"if",
"not",
"os",
".",
"path",
"... | 37.083333 | 0.002193 |
def main(host='localhost', port=8086, nb_day=15):
"""Instantiate a connection to the backend."""
nb_day = 15 # number of day to generate time series
timeinterval_min = 5 # create an event every x minutes
total_minutes = 1440 * nb_day
total_records = int(total_minutes / timeinterval_min)
now = ... | [
"def",
"main",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"8086",
",",
"nb_day",
"=",
"15",
")",
":",
"nb_day",
"=",
"15",
"# number of day to generate time series",
"timeinterval_min",
"=",
"5",
"# create an event every x minutes",
"total_minutes",
"=",
"... | 32.660714 | 0.000531 |
def _refresh_url(self):
"""刷新获取 url,失败的时候返回空而不是 None"""
songs = self._api.weapi_songs_url([int(self.identifier)])
if songs and songs[0]['url']:
self.url = songs[0]['url']
else:
self.url = '' | [
"def",
"_refresh_url",
"(",
"self",
")",
":",
"songs",
"=",
"self",
".",
"_api",
".",
"weapi_songs_url",
"(",
"[",
"int",
"(",
"self",
".",
"identifier",
")",
"]",
")",
"if",
"songs",
"and",
"songs",
"[",
"0",
"]",
"[",
"'url'",
"]",
":",
"self",
... | 34.285714 | 0.00813 |
def denoise_image(image, mask=None, shrink_factor=1, p=1, r=3, noise_model='Rician', v=0 ):
"""
Denoise an image using a spatially adaptive filter originally described in
J. V. Manjon, P. Coupe, Luis Marti-Bonmati, D. L. Collins, and M. Robles.
Adaptive Non-Local Means Denoising of MR Images With Spatia... | [
"def",
"denoise_image",
"(",
"image",
",",
"mask",
"=",
"None",
",",
"shrink_factor",
"=",
"1",
",",
"p",
"=",
"1",
",",
"r",
"=",
"3",
",",
"noise_model",
"=",
"'Rician'",
",",
"v",
"=",
"0",
")",
":",
"inpixeltype",
"=",
"image",
".",
"pixeltype"... | 26.52 | 0.001939 |
def model(UserModel):
"""
Post Model
:param UserModel:
"""
db = UserModel.db
class SlugNameMixin(object):
name = db.Column(db.String(255), index=True)
slug = db.Column(db.String(255), index=True, unique=True)
description = db.Column(db.String(255))
image_url = d... | [
"def",
"model",
"(",
"UserModel",
")",
":",
"db",
"=",
"UserModel",
".",
"db",
"class",
"SlugNameMixin",
"(",
"object",
")",
":",
"name",
"=",
"db",
".",
"Column",
"(",
"db",
".",
"String",
"(",
"255",
")",
",",
"index",
"=",
"True",
")",
"slug",
... | 35.701493 | 0.001423 |
def response_data_to_model_instance(self, response_data):
"""Convert response data to a task instance model.
Args:
response_data (dict): The data from the request's response.
Returns:
:class:`saltant.models.base_task_instance.BaseTaskInstance`:
A task in... | [
"def",
"response_data_to_model_instance",
"(",
"self",
",",
"response_data",
")",
":",
"# Coerce datetime strings into datetime objects",
"response_data",
"[",
"\"datetime_created\"",
"]",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"response_data",
"[",
"\"datetim... | 37.48 | 0.002081 |
def Parse(self):
"""Parse the file."""
if not self._file:
logging.error("Couldn't open file")
return
# Limit read size to 5MB.
self.input_dat = self._file.read(1024 * 1024 * 5)
if not self.input_dat.startswith(self.FILE_HEADER):
logging.error("Invalid index.dat file %s", self._fil... | [
"def",
"Parse",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_file",
":",
"logging",
".",
"error",
"(",
"\"Couldn't open file\"",
")",
"return",
"# Limit read size to 5MB.",
"self",
".",
"input_dat",
"=",
"self",
".",
"_file",
".",
"read",
"(",
"1024"... | 28.7 | 0.011804 |
def _platform(self) -> Optional[str]:
"""Extract platform."""
try:
return str(self.journey.MainStop.BasicStop.Dep.Platform.text)
except AttributeError:
return None | [
"def",
"_platform",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"try",
":",
"return",
"str",
"(",
"self",
".",
"journey",
".",
"MainStop",
".",
"BasicStop",
".",
"Dep",
".",
"Platform",
".",
"text",
")",
"except",
"AttributeError",
":",
... | 34.333333 | 0.009479 |
def check_file_for_tabs(filename, verbose=True):
"""identifies if the file contains tabs and returns True if it
does. It also prints the location of the lines and columns. If
verbose is set to False, the location is not printed.
:param verbose: if true prints information about issues
:param filenam... | [
"def",
"check_file_for_tabs",
"(",
"filename",
",",
"verbose",
"=",
"True",
")",
":",
"file_contains_tabs",
"=",
"False",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",... | 38.259259 | 0.000944 |
def get_value(prompt, default=None, hidden=False):
'''Displays the provided prompt and returns the input from the user. If the
user hits Enter and there is a default value provided, the default is
returned.
'''
_prompt = '%s : ' % prompt
if default:
_prompt = '%s [%s]: ' % (prompt, defau... | [
"def",
"get_value",
"(",
"prompt",
",",
"default",
"=",
"None",
",",
"hidden",
"=",
"False",
")",
":",
"_prompt",
"=",
"'%s : '",
"%",
"prompt",
"if",
"default",
":",
"_prompt",
"=",
"'%s [%s]: '",
"%",
"(",
"prompt",
",",
"default",
")",
"if",
"hidden... | 28.611111 | 0.00188 |
def process_catalog(self, limit=None):
"""
:param limit:
:return:
"""
raw = '/'.join((self.rawdir, self.files['catalog']['file']))
LOG.info("Processing Data from %s", raw)
efo_ontology = RDFGraph(False, "EFO")
LOG.info("Loading EFO ontology in separate rd... | [
"def",
"process_catalog",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"raw",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"rawdir",
",",
"self",
".",
"files",
"[",
"'catalog'",
"]",
"[",
"'file'",
"]",
")",
")",
"LOG",
".",
"info",
"(",
... | 40.437956 | 0.002114 |
def _send_stanza(self, xmlstream, token):
"""
Send a stanza token `token` over the given `xmlstream`.
Only sends if the `token` has not been aborted (see
:meth:`StanzaToken.abort`). Sends the state of the token acoording to
:attr:`sm_enabled`.
"""
if token.state ... | [
"def",
"_send_stanza",
"(",
"self",
",",
"xmlstream",
",",
"token",
")",
":",
"if",
"token",
".",
"state",
"==",
"StanzaState",
".",
"ABORTED",
":",
"return",
"stanza_obj",
"=",
"token",
".",
"stanza",
"if",
"isinstance",
"(",
"stanza_obj",
",",
"stanza",
... | 34.392157 | 0.001109 |
def get_conn(filename):
"""Returns new sqlite3.Connection object with _dict_factory() as row factory"""
conn = sqlite3.connect(filename)
conn.row_factory = _dict_factory
return conn | [
"def",
"get_conn",
"(",
"filename",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"filename",
")",
"conn",
".",
"row_factory",
"=",
"_dict_factory",
"return",
"conn"
] | 39.4 | 0.00995 |
def get_pdos(dos, lm_orbitals=None, atoms=None, elements=None):
"""Extract the projected density of states from a CompleteDos object.
Args:
dos (:obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The
density of states.
elements (:obj:`dict`, optional): The elements and orbitals... | [
"def",
"get_pdos",
"(",
"dos",
",",
"lm_orbitals",
"=",
"None",
",",
"atoms",
"=",
"None",
",",
"elements",
"=",
"None",
")",
":",
"if",
"not",
"elements",
":",
"symbols",
"=",
"dos",
".",
"structure",
".",
"symbol_set",
"elements",
"=",
"dict",
"(",
... | 47.635135 | 0.000278 |
def external(self, external_id, include=None):
"""
Locate an Organization by it's external_id attribute.
:param include: list of objects to sideload. `Side-loading API Docs
<https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.
:param external_id: external id o... | [
"def",
"external",
"(",
"self",
",",
"external_id",
",",
"include",
"=",
"None",
")",
":",
"return",
"self",
".",
"_query_zendesk",
"(",
"self",
".",
"endpoint",
".",
"external",
",",
"'organization'",
",",
"id",
"=",
"external_id",
",",
"include",
"=",
... | 49.555556 | 0.008811 |
def _remote_setup_engine(engine_id, nengines):
"""(Executed on remote engine) creates an ObjectEngine instance """
if distob.engine is None:
distob.engine = distob.ObjectEngine(engine_id, nengines)
# TODO these imports should be unnecessary with improved deserialization
import numpy as np
fr... | [
"def",
"_remote_setup_engine",
"(",
"engine_id",
",",
"nengines",
")",
":",
"if",
"distob",
".",
"engine",
"is",
"None",
":",
"distob",
".",
"engine",
"=",
"distob",
".",
"ObjectEngine",
"(",
"engine_id",
",",
"nengines",
")",
"# TODO these imports should be unn... | 45 | 0.001815 |
def send_msg(self, msg):
"""
Sends Zebra message.
:param msg: Instance of py:class: `ryu.lib.packet.zebra.ZebraMessage`.
:return: Serialized msg if succeeded, otherwise None.
"""
if not self.is_active:
self.logger.debug(
'Cannot send message: ... | [
"def",
"send_msg",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"self",
".",
"is_active",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Cannot send message: Already deactivated: msg=%s'",
",",
"msg",
")",
"return",
"elif",
"not",
"self",
".",
"send_q",... | 35.913043 | 0.002358 |
def parse_file_provider(uri):
"""Find the file provider for a URI."""
providers = {'gs': job_model.P_GCS, 'file': job_model.P_LOCAL}
# URI scheme detector uses a range up to 30 since none of the IANA
# registered schemes are longer than this.
provider_found = re.match(r'^([A-Za-z][A-Za-z0-9+.-]{0,29... | [
"def",
"parse_file_provider",
"(",
"uri",
")",
":",
"providers",
"=",
"{",
"'gs'",
":",
"job_model",
".",
"P_GCS",
",",
"'file'",
":",
"job_model",
".",
"P_LOCAL",
"}",
"# URI scheme detector uses a range up to 30 since none of the IANA",
"# registered schemes are longer ... | 43.764706 | 0.010526 |
def session_list(consul_url=None, token=None, return_list=False, **kwargs):
'''
Used to list sessions.
:param consul_url: The Consul server URL.
:param dc: By default, the datacenter of the agent is queried;
however, the dc can be provided using the "dc" parameter.
:param return_list... | [
"def",
"session_list",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"return_list",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"... | 27.911111 | 0.000769 |
def _initURL(self, org_url=None,
token_url=None,
referer_url=None):
""" sets proper URLs for AGOL """
if org_url is not None and org_url != '':
if not org_url.startswith('http://') and not org_url.startswith('https://'):
org_url = 'http://' +... | [
"def",
"_initURL",
"(",
"self",
",",
"org_url",
"=",
"None",
",",
"token_url",
"=",
"None",
",",
"referer_url",
"=",
"None",
")",
":",
"if",
"org_url",
"is",
"not",
"None",
"and",
"org_url",
"!=",
"''",
":",
"if",
"not",
"org_url",
".",
"startswith",
... | 39.875 | 0.012852 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.