text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def rasterToPolygon(raster_file, polygon_file):
"""
Converts watershed raster to polygon and then dissolves it.
It dissolves features based on the LINKNO attribute.
"""
log("Process: Raster to Polygon ...")
time_start = datetime.utcnow()
temp_polygon_file = \
... | [
"def",
"rasterToPolygon",
"(",
"raster_file",
",",
"polygon_file",
")",
":",
"log",
"(",
"\"Process: Raster to Polygon ...\"",
")",
"time_start",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"temp_polygon_file",
"=",
"\"{0}_temp.shp\"",
".",
"format",
"(",
"os",
".",... | 45.410959 | 0.00059 |
def to_snake_case(s):
"""Converts camel-case identifiers to snake-case."""
return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s) | [
"def",
"to_snake_case",
"(",
"s",
")",
":",
"return",
"re",
".",
"sub",
"(",
"'([^_A-Z])([A-Z])'",
",",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"1",
")",
"+",
"'_'",
"+",
"m",
".",
"group",
"(",
"2",
")",
".",
"lower",
"(",
")",
",",
"s",
... | 55.333333 | 0.011905 |
def remove_entry(self, entry):
"""
Remove specified entry.
:param entry: The Entry object to remove.
:type entry: :class:`keepassdb.model.Entry`
"""
if not isinstance(entry, Entry):
raise TypeError("entry param must be of type Entry.")
if not ... | [
"def",
"remove_entry",
"(",
"self",
",",
"entry",
")",
":",
"if",
"not",
"isinstance",
"(",
"entry",
",",
"Entry",
")",
":",
"raise",
"TypeError",
"(",
"\"entry param must be of type Entry.\"",
")",
"if",
"not",
"entry",
"in",
"self",
".",
"entries",
":",
... | 35.428571 | 0.011788 |
def do_sort(environment, value, reverse=False, case_sensitive=False,
attribute=None):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the ca... | [
"def",
"do_sort",
"(",
"environment",
",",
"value",
",",
"reverse",
"=",
"False",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"if",
"not",
"case_sensitive",
":",
"def",
"sort_func",
"(",
"item",
")",
":",
"if",
"isinstan... | 32.102564 | 0.00155 |
def get_residuals_update_tile(st, padded_tile):
"""
Translates a tile in the padded image to the unpadded image.
Given a state and a tile that corresponds to the padded image, returns
a tile that corresponds to the the corresponding pixels of the difference
image
Parameters
----------
... | [
"def",
"get_residuals_update_tile",
"(",
"st",
",",
"padded_tile",
")",
":",
"inner_tile",
"=",
"st",
".",
"ishape",
".",
"intersection",
"(",
"[",
"st",
".",
"ishape",
",",
"padded_tile",
"]",
")",
"return",
"inner_tile",
".",
"translate",
"(",
"-",
"st",... | 31.318182 | 0.001408 |
def login(self):
""" perform API auth test returning user and team """
log.debug('performing auth test')
test = self._get(urls['test'])
user = User({ 'name': test['user'], 'id': test['user_id'] })
self._refresh()
return test['team'], user | [
"def",
"login",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'performing auth test'",
")",
"test",
"=",
"self",
".",
"_get",
"(",
"urls",
"[",
"'test'",
"]",
")",
"user",
"=",
"User",
"(",
"{",
"'name'",
":",
"test",
"[",
"'user'",
"]",
",",
... | 40 | 0.013986 |
def resolve_child_module_registries_lineage(registry):
"""
For a given child module registry, attempt to resolve the lineage.
Return an iterator, yielding from parent down to the input registry,
inclusive of the input registry.
"""
children = [registry]
while isinstance(registry, BaseChild... | [
"def",
"resolve_child_module_registries_lineage",
"(",
"registry",
")",
":",
"children",
"=",
"[",
"registry",
"]",
"while",
"isinstance",
"(",
"registry",
",",
"BaseChildModuleRegistry",
")",
":",
"if",
"registry",
".",
"parent",
"in",
"children",
":",
"# this sh... | 46.456522 | 0.000458 |
def sftp_upload_window_size_set(srv,file, method_to_call='put'):
'''
sets config for uploading files with pysftp
'''
channel = srv.sftp_client.get_channel()
channel.lock.acquire()
channel.out_window_size += os.stat(file).st_size * 1.1 # bit more bytes incase packet loss
channel.out_buffer_... | [
"def",
"sftp_upload_window_size_set",
"(",
"srv",
",",
"file",
",",
"method_to_call",
"=",
"'put'",
")",
":",
"channel",
"=",
"srv",
".",
"sftp_client",
".",
"get_channel",
"(",
")",
"channel",
".",
"lock",
".",
"acquire",
"(",
")",
"channel",
".",
"out_wi... | 39.222222 | 0.00831 |
def set_target_n(self, value):
''' setter '''
if isinstance(value, int) is False:
raise TypeError("The type of __target_n must be int.")
self.__target_n = value | [
"def",
"set_target_n",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
"is",
"False",
":",
"raise",
"TypeError",
"(",
"\"The type of __target_n must be int.\"",
")",
"self",
".",
"__target_n",
"=",
"value"
] | 38.4 | 0.010204 |
def create_direct_channel(current):
"""
Create a One-To-One channel between current and selected user.
.. code-block:: python
# request:
{
'view':'_zops_create_direct_channel',
'user_key': key,
}
# response:
{
'des... | [
"def",
"create_direct_channel",
"(",
"current",
")",
":",
"channel",
",",
"sub_name",
"=",
"Channel",
".",
"get_or_create_direct_channel",
"(",
"current",
".",
"user_id",
",",
"current",
".",
"input",
"[",
"'user_key'",
"]",
")",
"current",
".",
"input",
"[",
... | 28.189189 | 0.001854 |
def dr( self, atom1, atom2 ):
"""
Calculate the distance between two atoms.
Args:
atom1 (vasppy.Atom): Atom 1.
atom2 (vasppy.Atom): Atom 2.
Returns:
(float): The distance between Atom 1 and Atom 2.
"""
return self.cell.dr( atom1.r, at... | [
"def",
"dr",
"(",
"self",
",",
"atom1",
",",
"atom2",
")",
":",
"return",
"self",
".",
"cell",
".",
"dr",
"(",
"atom1",
".",
"r",
",",
"atom2",
".",
"r",
")"
] | 26.333333 | 0.018349 |
def likelihood(self, outcomes, modelparams, expparams):
"""
Calculates the likelihood function at the states specified
by modelparams and measurement specified by expparams.
This is given by the Born rule and is the probability of
outcomes given the state and measurement operato... | [
"def",
"likelihood",
"(",
"self",
",",
"outcomes",
",",
"modelparams",
",",
"expparams",
")",
":",
"# By calling the superclass implementation, we can consolidate",
"# call counting there.",
"super",
"(",
"MultiQubitStatePauliModel",
",",
"self",
")",
".",
"likelihood",
"... | 40.72 | 0.009597 |
def get_available_detectors():
"""Return list of detectors known in the currently sourced lalsuite.
This function will query lalsuite about which detectors are known to
lalsuite. Detectors are identified by a two character string e.g. 'K1',
but also by a longer, and clearer name, e.g. KAGRA. This funct... | [
"def",
"get_available_detectors",
"(",
")",
":",
"ld",
"=",
"lal",
".",
"__dict__",
"known_lal_names",
"=",
"[",
"j",
"for",
"j",
"in",
"ld",
".",
"keys",
"(",
")",
"if",
"\"DETECTOR_PREFIX\"",
"in",
"j",
"]",
"known_prefixes",
"=",
"[",
"ld",
"[",
"k"... | 53.352941 | 0.001083 |
def resolve_polytomies(self, merge_compressed=False):
"""
Resolve the polytomies on the tree.
The function scans the tree, resolves polytomies if present,
and re-optimizes the tree with new topology. Note that polytomies are only
resolved if that would result in higher likelihoo... | [
"def",
"resolve_polytomies",
"(",
"self",
",",
"merge_compressed",
"=",
"False",
")",
":",
"self",
".",
"logger",
"(",
"\"TreeTime.resolve_polytomies: resolving multiple mergers...\"",
",",
"1",
")",
"poly_found",
"=",
"0",
"for",
"n",
"in",
"self",
".",
"tree",
... | 39.023256 | 0.009884 |
def plot_predict(self, h=5, past_values=20, intervals=True, **kwargs):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How m... | [
"def",
"plot_predict",
"(",
"self",
",",
"h",
"=",
"5",
",",
"past_values",
"=",
"20",
",",
"intervals",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"figsize",
... | 42.492308 | 0.012385 |
def dependencies_order_of_build(target_contract, dependencies_map):
""" Return an ordered list of contracts that is sufficient to successfully
deploy the target contract.
Note:
This function assumes that the `dependencies_map` is an acyclic graph.
"""
if not dependencies_map:
return... | [
"def",
"dependencies_order_of_build",
"(",
"target_contract",
",",
"dependencies_map",
")",
":",
"if",
"not",
"dependencies_map",
":",
"return",
"[",
"target_contract",
"]",
"if",
"target_contract",
"not",
"in",
"dependencies_map",
":",
"raise",
"ValueError",
"(",
"... | 31.741935 | 0.001972 |
def is_primitive(value):
"""
Checks if value has primitive type.
Primitive types are: numbers, strings, booleans, date and time.
Complex (non-primitive types are): objects, maps and arrays
:param value: a value to check
:return: true if the value has primitive type and... | [
"def",
"is_primitive",
"(",
"value",
")",
":",
"typeCode",
"=",
"TypeConverter",
".",
"to_type_code",
"(",
"value",
")",
"return",
"typeCode",
"==",
"TypeCode",
".",
"String",
"or",
"typeCode",
"==",
"TypeCode",
".",
"Enum",
"or",
"typeCode",
"==",
"TypeCode... | 46.5625 | 0.010526 |
def get_with_rtdcbase(self, col1, col2, method, dataset,
viscosity=None, add_px_err=False):
"""Convenience method that extracts the metadata from RTDCBase
Parameters
----------
col1: str
Name of the first feature of all isoelastics
(e.g.... | [
"def",
"get_with_rtdcbase",
"(",
"self",
",",
"col1",
",",
"col2",
",",
"method",
",",
"dataset",
",",
"viscosity",
"=",
"None",
",",
"add_px_err",
"=",
"False",
")",
":",
"cfg",
"=",
"dataset",
".",
"config",
"return",
"self",
".",
"get",
"(",
"col1",... | 41.914286 | 0.001999 |
def read(self, data_path: str, *args, **kwargs) -> Dict[str, List[Tuple[Any, Any]]]:
"""Reads a file from a path and returns data as a list of tuples of inputs and correct outputs
for every data type in ``train``, ``valid`` and ``test``.
"""
raise NotImplementedError | [
"def",
"read",
"(",
"self",
",",
"data_path",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"Tuple",
"[",
"Any",
",",
"Any",
"]",
"]",
"]",
":",
"raise",
"NotImplementedError"
] | 59.2 | 0.013333 |
def scaled(values, output_min, output_max, input_min=0, input_max=1):
"""
Returns *values* scaled from *output_min* to *output_max*, assuming that
all items in *values* lie between *input_min* and *input_max* (which
default to 0 and 1 respectively). For example, to control the direction of
a motor (... | [
"def",
"scaled",
"(",
"values",
",",
"output_min",
",",
"output_max",
",",
"input_min",
"=",
"0",
",",
"input_max",
"=",
"1",
")",
":",
"values",
"=",
"_normalize",
"(",
"values",
")",
"if",
"input_min",
">=",
"input_max",
":",
"raise",
"ValueError",
"("... | 37.65625 | 0.000809 |
def compartments(M, normalize=True):
"""A/B compartment analysis
Perform a PCA-based A/B compartment analysis on a normalized, single
chromosome contact map. The results are two vectors whose values (negative
or positive) should presumably correlate with the presence of 'active'
vs. 'inert' chromat... | [
"def",
"compartments",
"(",
"M",
",",
"normalize",
"=",
"True",
")",
":",
"if",
"not",
"type",
"(",
"M",
")",
"is",
"np",
".",
"ndarray",
":",
"M",
"=",
"np",
".",
"array",
"(",
"M",
")",
"if",
"M",
".",
"shape",
"[",
"0",
"]",
"!=",
"M",
"... | 26.205128 | 0.000943 |
def fit_similarity(fit1, fit2):
"""
Distance apart for vectors, given in
standard deviations
"""
cov1 = aligned_covariance(fit1)
cov2 = aligned_covariance(fit2)
if fit2.axes[2,2] < 0:
cov2 *= -1
v0 = fit1.normal-fit2.normal
cov0 = cov1+cov2 # Axes are aligned, so no covarianc... | [
"def",
"fit_similarity",
"(",
"fit1",
",",
"fit2",
")",
":",
"cov1",
"=",
"aligned_covariance",
"(",
"fit1",
")",
"cov2",
"=",
"aligned_covariance",
"(",
"fit2",
")",
"if",
"fit2",
".",
"axes",
"[",
"2",
",",
"2",
"]",
"<",
"0",
":",
"cov2",
"*=",
... | 27.736842 | 0.012844 |
def get_branding(self, branding_id):
"""
Get a concrete branding
@branding_id: Id of the branding to fetch
@return Branding
"""
connection = Connection(self.token)
connection.set_url(self.production, self.BRANDINGS_ID_URL % branding_id)
return connection... | [
"def",
"get_branding",
"(",
"self",
",",
"branding_id",
")",
":",
"connection",
"=",
"Connection",
"(",
"self",
".",
"token",
")",
"connection",
".",
"set_url",
"(",
"self",
".",
"production",
",",
"self",
".",
"BRANDINGS_ID_URL",
"%",
"branding_id",
")",
... | 29.454545 | 0.008982 |
def value_counts(self, dropna=True):
"""
Return a Series containing counts of each category.
Every category will have an entry, even those with a count of 0.
Parameters
----------
dropna : bool, default True
Don't include counts of NaN.
Returns
... | [
"def",
"value_counts",
"(",
"self",
",",
"dropna",
"=",
"True",
")",
":",
"from",
"numpy",
"import",
"bincount",
"from",
"pandas",
"import",
"Series",
",",
"CategoricalIndex",
"code",
",",
"cat",
"=",
"self",
".",
"_codes",
",",
"self",
".",
"categories",
... | 27.210526 | 0.001867 |
def _embedding_spectral(matrix, dimensions=3, unit_length=True,
affinity_matrix=None, sigma=1):
"""
Private method to calculate Spectral embedding
:param dimensions: (int)
:return: coordinate matrix (np.array)
"""
if affinity_matrix is None:
aff = rbf(matrix, sigm... | [
"def",
"_embedding_spectral",
"(",
"matrix",
",",
"dimensions",
"=",
"3",
",",
"unit_length",
"=",
"True",
",",
"affinity_matrix",
"=",
"None",
",",
"sigma",
"=",
"1",
")",
":",
"if",
"affinity_matrix",
"is",
"None",
":",
"aff",
"=",
"rbf",
"(",
"matrix"... | 37.153846 | 0.00202 |
def list_servers(backend, socket=DEFAULT_SOCKET_URL, objectify=False):
'''
List servers in haproxy backend.
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.list_servers mysql
... | [
"def",
"list_servers",
"(",
"backend",
",",
"socket",
"=",
"DEFAULT_SOCKET_URL",
",",
"objectify",
"=",
"False",
")",
":",
"ha_conn",
"=",
"_get_conn",
"(",
"socket",
")",
"ha_cmd",
"=",
"haproxy",
".",
"cmds",
".",
"listServers",
"(",
"backend",
"=",
"bac... | 23.684211 | 0.002137 |
def particles_in_range(
self,
compound,
dmax,
max_particles=20,
particle_kdtree=None,
particle_array=None):
"""Find particles within a specified range of another particle.
Parameters
----------
compound : mb.Compoun... | [
"def",
"particles_in_range",
"(",
"self",
",",
"compound",
",",
"dmax",
",",
"max_particles",
"=",
"20",
",",
"particle_kdtree",
"=",
"None",
",",
"particle_array",
"=",
"None",
")",
":",
"if",
"particle_kdtree",
"is",
"None",
":",
"particle_kdtree",
"=",
"P... | 38.840909 | 0.001142 |
def pdf_add(dest: str, source: str, pages: [str], output: str):
"""
Add pages from a source pdf file to an output file. If the output
file does not exist a new file will be created.
:param source: source pdf file
:param dest: destination pdf file
:param pages: list of page numbers or range expre... | [
"def",
"pdf_add",
"(",
"dest",
":",
"str",
",",
"source",
":",
"str",
",",
"pages",
":",
"[",
"str",
"]",
",",
"output",
":",
"str",
")",
":",
"if",
"output",
"is",
"not",
"None",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"output",
")",
":"... | 31.45098 | 0.000605 |
def _input_as_multiline_string(self, data):
"""Writes data to tempfile and sets -infile parameter
data -- list of lines
"""
if data:
self.Parameters['-infile']\
.on(super(Clustalw,self)._input_as_multiline_string(data))
return '' | [
"def",
"_input_as_multiline_string",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"self",
".",
"Parameters",
"[",
"'-infile'",
"]",
".",
"on",
"(",
"super",
"(",
"Clustalw",
",",
"self",
")",
".",
"_input_as_multiline_string",
"(",
"data",
")",
... | 32.222222 | 0.010067 |
def http_req(blink, url='http://example.com', data=None, headers=None,
reqtype='get', stream=False, json_resp=True, is_retry=False):
"""
Perform server requests and check if reauthorization neccessary.
:param blink: Blink instance
:param url: URL to perform request
:param data: Data to... | [
"def",
"http_req",
"(",
"blink",
",",
"url",
"=",
"'http://example.com'",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"reqtype",
"=",
"'get'",
",",
"stream",
"=",
"False",
",",
"json_resp",
"=",
"True",
",",
"is_retry",
"=",
"False",
")... | 40.557692 | 0.000463 |
def report(
config, path, metrics, n, output, include_message=False, format=ReportFormat.CONSOLE, console_format=None,
):
"""
Show information about the cache and runtime.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param path: The path to the file
:typ... | [
"def",
"report",
"(",
"config",
",",
"path",
",",
"metrics",
",",
"n",
",",
"output",
",",
"include_message",
"=",
"False",
",",
"format",
"=",
"ReportFormat",
".",
"CONSOLE",
",",
"console_format",
"=",
"None",
",",
")",
":",
"logger",
".",
"debug",
"... | 35.105882 | 0.001792 |
def build(self, text):
"""
:param text: Content of the span
"""
super(Span, self).build()
self.content = text | [
"def",
"build",
"(",
"self",
",",
"text",
")",
":",
"super",
"(",
"Span",
",",
"self",
")",
".",
"build",
"(",
")",
"self",
".",
"content",
"=",
"text"
] | 24 | 0.013423 |
def _ne16(ins):
''' Compares & pops top 2 operands out of the stack, and checks
if the 1st operand != 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit un/signed version
'''
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append('or a') # Resets carry f... | [
"def",
"_ne16",
"(",
"ins",
")",
":",
"output",
"=",
"_16bit_oper",
"(",
"ins",
".",
"quad",
"[",
"2",
"]",
",",
"ins",
".",
"quad",
"[",
"3",
"]",
")",
"output",
".",
"append",
"(",
"'or a'",
")",
"# Resets carry flag",
"output",
".",
"append",
"(... | 29.6 | 0.002183 |
def value_comparisons(self, values, comp="=", is_assignment=False):
"""Builds out a series of value comparisions.
:values: can either be a dictionary, in which case the return will compare a name to a named
placeholder, using the comp argument. I.E. values = {"first_name": "John", "last_name": "Smith"}
... | [
"def",
"value_comparisons",
"(",
"self",
",",
"values",
",",
"comp",
"=",
"\"=\"",
",",
"is_assignment",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"dict",
")",
":",
"if",
"self",
".",
"sort_columns",
":",
"keys",
"=",
"sorted",
"(... | 37.765957 | 0.010434 |
def parse_code_ul(self, url, ul):
"""Fill the toc item"""
li_list = ul.find_all('li', recursive=False)
li = li_list[0]
span_title = li.find('span',
attrs={'class': re.compile(r'TM\d+Code')},
recursive=False)
section = Sec... | [
"def",
"parse_code_ul",
"(",
"self",
",",
"url",
",",
"ul",
")",
":",
"li_list",
"=",
"ul",
".",
"find_all",
"(",
"'li'",
",",
"recursive",
"=",
"False",
")",
"li",
"=",
"li_list",
"[",
"0",
"]",
"span_title",
"=",
"li",
".",
"find",
"(",
"'span'",... | 46.241379 | 0.001461 |
def add_overlay(orig, area, coast_dir, color=(0, 0, 0), width=0.5, resolution=None,
level_coast=1, level_borders=1, fill_value=None,
grid=None):
"""Add coastline, political borders and grid(graticules) to image.
Uses ``color`` for feature colors where ``color`` is a 3-element tu... | [
"def",
"add_overlay",
"(",
"orig",
",",
"area",
",",
"coast_dir",
",",
"color",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"width",
"=",
"0.5",
",",
"resolution",
"=",
"None",
",",
"level_coast",
"=",
"1",
",",
"level_borders",
"=",
"1",
",",
"... | 40.1875 | 0.001265 |
def generate_unit_triangles(image_width, image_height):
"""Generate coordinates for a tiling of unit triangles."""
# Our triangles lie with one side parallel to the x-axis. Let s be
# the length of one side, and h the height of the triangle.
#
# The for loops (x, y) gives the coordinates of the top... | [
"def",
"generate_unit_triangles",
"(",
"image_width",
",",
"image_height",
")",
":",
"# Our triangles lie with one side parallel to the x-axis. Let s be",
"# the length of one side, and h the height of the triangle.",
"#",
"# The for loops (x, y) gives the coordinates of the top left-hand cor... | 39.363636 | 0.000751 |
def build_ast(expression, debug = False):
"""build an AST from an Excel formula expression in reverse polish notation"""
#use a directed graph to store the tree
G = DiGraph()
stack = []
for n in expression:
# Since the graph does not maintain the order of adding nodes/edges
# add a... | [
"def",
"build_ast",
"(",
"expression",
",",
"debug",
"=",
"False",
")",
":",
"#use a directed graph to store the tree",
"G",
"=",
"DiGraph",
"(",
")",
"stack",
"=",
"[",
"]",
"for",
"n",
"in",
"expression",
":",
"# Since the graph does not maintain the order of addi... | 34.64 | 0.016844 |
def format_obj_keys(obj, formatter):
"""
Take a dictionary with string keys and recursively convert
all keys from one form to another using the formatting function.
The dictionary may contain lists as values, and any nested
dictionaries within those lists will also be converted.
:param object ... | [
"def",
"format_obj_keys",
"(",
"obj",
",",
"formatter",
")",
":",
"if",
"type",
"(",
"obj",
")",
"==",
"list",
":",
"return",
"[",
"format_obj_keys",
"(",
"o",
",",
"formatter",
")",
"for",
"o",
"in",
"obj",
"]",
"elif",
"type",
"(",
"obj",
")",
"=... | 30.439024 | 0.000776 |
def stats(self, node_id=None, metric=None, index_metric=None, params=None):
"""
The cluster nodes stats API allows to retrieve one or more (or all) of
the cluster nodes statistics.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-stats.html>`_
:arg... | [
"def",
"stats",
"(",
"self",
",",
"node_id",
"=",
"None",
",",
"metric",
"=",
"None",
",",
"index_metric",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"GET\"",
",",
"_make_path",
... | 54.459459 | 0.00195 |
def alpha(self, **state):
"""
Calculate the alpha value given the material state.
:param **state: material state
:returns: float
"""
return self.k(**state) / self.rho(**state) / self.Cp(**state) | [
"def",
"alpha",
"(",
"self",
",",
"*",
"*",
"state",
")",
":",
"return",
"self",
".",
"k",
"(",
"*",
"*",
"state",
")",
"/",
"self",
".",
"rho",
"(",
"*",
"*",
"state",
")",
"/",
"self",
".",
"Cp",
"(",
"*",
"*",
"state",
")"
] | 23.6 | 0.008163 |
def __draw_clusters(self):
"""!
@brief Display clusters and outliers using different colors.
"""
data = self.__directory.get_data()
for index_cluster in range(len(self.__clusters)):
color = color_list.get_color(index_cluster)
self.__draw_cluster(d... | [
"def",
"__draw_clusters",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"__directory",
".",
"get_data",
"(",
")",
"for",
"index_cluster",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"__clusters",
")",
")",
":",
"color",
"=",
"color_list",
".",
"get... | 40.454545 | 0.008791 |
def update_derived_metric(self, id, **kwargs): # noqa: E501
"""Update a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.upd... | [
"def",
"update_derived_metric",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"update... | 55.454545 | 0.001612 |
def make_relative (self, other):
"""Return a new path that is the equivalent of this one relative to the path
*other*. Unlike :meth:`relative_to`, this will not throw an error if *self* is
not a sub-path of *other*; instead, it will use ``..`` to build a relative
path. This can result in... | [
"def",
"make_relative",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"is_absolute",
"(",
")",
":",
"return",
"self",
"from",
"os",
".",
"path",
"import",
"relpath",
"other",
"=",
"self",
".",
"__class__",
"(",
"other",
")",
"return",
"self",... | 42.0625 | 0.017442 |
def format_function(
func_body,
func_type=None,
indent=2,
format_locals=True,
):
"""
Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string
representation of the function line by line. The function type is required
for formatting function parameter and return value ... | [
"def",
"format_function",
"(",
"func_body",
",",
"func_type",
"=",
"None",
",",
"indent",
"=",
"2",
",",
"format_locals",
"=",
"True",
",",
")",
":",
"if",
"func_type",
"is",
"None",
":",
"yield",
"'func'",
"else",
":",
"param_section",
"=",
"' (param {})'... | 35.114286 | 0.001584 |
def _cellChunk(self, lines):
"""
Parse CELLIJ Chunk Method
"""
KEYWORDS = ('CELLIJ',
'NUMPIPES',
'SPIPE')
result = {'i': None,
'j': None,
'numPipes': None,
'spipes': []}
chunks... | [
"def",
"_cellChunk",
"(",
"self",
",",
"lines",
")",
":",
"KEYWORDS",
"=",
"(",
"'CELLIJ'",
",",
"'NUMPIPES'",
",",
"'SPIPE'",
")",
"result",
"=",
"{",
"'i'",
":",
"None",
",",
"'j'",
":",
"None",
",",
"'numPipes'",
":",
"None",
",",
"'spipes'",
":",... | 29.2 | 0.001657 |
def get_url(client, name, version, wheel=False, hashed_format=False):
"""Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL
of prefered archive and md5_digest.
"""
try:
release_urls = client.release_urls(name, version)
release_data = client.release_data(name, version)
e... | [
"def",
"get_url",
"(",
"client",
",",
"name",
",",
"version",
",",
"wheel",
"=",
"False",
",",
"hashed_format",
"=",
"False",
")",
":",
"try",
":",
"release_urls",
"=",
"client",
".",
"release_urls",
"(",
"name",
",",
"version",
")",
"release_data",
"=",... | 39.148148 | 0.000461 |
def _build_ds_from_instruction(instruction, ds_from_file_fn):
"""Map an instruction to a real datasets for one particular shard.
Args:
instruction: A `dict` of `tf.Tensor` containing the instruction to load
the particular shard (filename, mask,...)
ds_from_file_fn: `fct`, function which returns the d... | [
"def",
"_build_ds_from_instruction",
"(",
"instruction",
",",
"ds_from_file_fn",
")",
":",
"# Create the example and mask ds for this particular shard",
"examples_ds",
"=",
"ds_from_file_fn",
"(",
"instruction",
"[",
"\"filepath\"",
"]",
")",
"mask_ds",
"=",
"_build_mask_ds",... | 35.230769 | 0.012752 |
def agitator_time_homogeneous(N, P, T, H, mu, rho, D=None, homogeneity=.95):
r'''Calculates time for a fluid mizing in a tank with an impeller to
reach a specified level of homogeneity, according to [1]_.
.. math::
N_p = \frac{Pg}{\rho N^3 D^5}
.. math::
Re_{imp} = \frac{\rho D^2 N}{\m... | [
"def",
"agitator_time_homogeneous",
"(",
"N",
",",
"P",
",",
"T",
",",
"H",
",",
"mu",
",",
"rho",
",",
"D",
"=",
"None",
",",
"homogeneity",
"=",
".95",
")",
":",
"if",
"not",
"D",
":",
"D",
"=",
"T",
"*",
"0.5",
"Np",
"=",
"P",
"*",
"g",
... | 28.911392 | 0.00127 |
def conv1d(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False):
"Create and initialize a `nn.Conv1d` layer with spectral normalization."
conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias)
nn.init.kaiming_normal_(conv.weight)
if bias: conv.bias.data.zero_()
re... | [
"def",
"conv1d",
"(",
"ni",
":",
"int",
",",
"no",
":",
"int",
",",
"ks",
":",
"int",
"=",
"1",
",",
"stride",
":",
"int",
"=",
"1",
",",
"padding",
":",
"int",
"=",
"0",
",",
"bias",
":",
"bool",
"=",
"False",
")",
":",
"conv",
"=",
"nn",
... | 56.5 | 0.049419 |
def run_step(context):
"""pypyr step that checks if a file or directory path exists.
Args:
context: pypyr.context.Context. Mandatory.
The following context key must exist
- pathsToCheck. str/path-like or list of str/paths.
Path to file on... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"context",
".",
"assert_key_has_value",
"(",
"key",
"=",
"'pathCheck'",
",",
"caller",
"=",
"__name__",
")",
"paths_to_check",
"=",
"context",
"[",
"'pathCheck'",
"... | 34.540541 | 0.00038 |
def _on_response(self, action, table, attempt, start, response, future,
measurements):
"""Invoked when the HTTP request to the DynamoDB has returned and
is responsible for setting the future result or exception based upon
the HTTP response provided.
:param str actio... | [
"def",
"_on_response",
"(",
"self",
",",
"action",
",",
"table",
",",
"attempt",
",",
"start",
",",
"response",
",",
"future",
",",
"measurements",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s on %s request #%i = %r'",
",",
"action",
",",
"tabl... | 48.415094 | 0.001146 |
def dump_simulation(simulation, directory):
"""
Write simulation data to directory, so that it can be restored later.
"""
parent_directory = os.path.abspath(os.path.join(directory, os.pardir))
if not os.path.isdir(parent_directory): # To deal with reforms
os.mkdir(parent_directory)
... | [
"def",
"dump_simulation",
"(",
"simulation",
",",
"directory",
")",
":",
"parent_directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"os",
".",
"pardir",
")",
")",
"if",
"not",
"os",
".",
"p... | 35.478261 | 0.001193 |
def prepare(c):
"""
Edit changelog & version, git commit, and git tag, to set up for release.
"""
# Print dry-run/status/actions-to-take data & grab programmatic result
# TODO: maybe expand the enum-based stuff to have values that split up
# textual description, command string, etc. See the TODO... | [
"def",
"prepare",
"(",
"c",
")",
":",
"# Print dry-run/status/actions-to-take data & grab programmatic result",
"# TODO: maybe expand the enum-based stuff to have values that split up",
"# textual description, command string, etc. See the TODO up by their",
"# definition too, re: just making them ... | 47.44898 | 0.000421 |
async def issuer_create_credential_offer(wallet_handle: int,
cred_def_id: str) -> str:
"""
Create credential offer that will be used by Prover for
credential request creation. Offer includes nonce and key correctness proof
for authentication between protocol step... | [
"async",
"def",
"issuer_create_credential_offer",
"(",
"wallet_handle",
":",
"int",
",",
"cred_def_id",
":",
"str",
")",
"->",
"str",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"issuer_create_credential_... | 41.974359 | 0.002388 |
def live_profile(script, argv, profiler_factory, interval, spawn, signum,
pickle_protocol, mono):
"""Profile a Python script continuously."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
parent_sock, child_sock = socket.socketpair()
stderr_r_fd, stderr_w_f... | [
"def",
"live_profile",
"(",
"script",
",",
"argv",
",",
"profiler_factory",
",",
"interval",
",",
"spawn",
",",
"signum",
",",
"pickle_protocol",
",",
"mono",
")",
":",
"filename",
",",
"code",
",",
"globals_",
"=",
"script",
"sys",
".",
"argv",
"[",
":"... | 36.508197 | 0.000437 |
def merge(corpus_1, corpus_2, match_by=['ayjid'], match_threshold=1.,
index_by='ayjid'):
"""
Combines two :class:`.Corpus` instances.
The default behavior is to match :class:`.Paper`\s using the fields in
``match_by``\. If several fields are specified, ``match_threshold`` can be
used to c... | [
"def",
"merge",
"(",
"corpus_1",
",",
"corpus_2",
",",
"match_by",
"=",
"[",
"'ayjid'",
"]",
",",
"match_threshold",
"=",
"1.",
",",
"index_by",
"=",
"'ayjid'",
")",
":",
"def",
"norm",
"(",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"in",
... | 37.296053 | 0.002062 |
def fields(self):
"""Filter fields based on request query parameters."""
fields = super().fields
return apply_subfield_projection(self, copy.copy(fields)) | [
"def",
"fields",
"(",
"self",
")",
":",
"fields",
"=",
"super",
"(",
")",
".",
"fields",
"return",
"apply_subfield_projection",
"(",
"self",
",",
"copy",
".",
"copy",
"(",
"fields",
")",
")"
] | 43.75 | 0.011236 |
def permute(self, ordering: np.ndarray, axis: int) -> None:
"""
Permute the dataset along the indicated axis.
Args:
ordering (list of int): The desired order along the axis
axis (int): The axis along which to permute
Returns:
Nothing.
"""
if self._file.__contains__("tiles"):
del self._fi... | [
"def",
"permute",
"(",
"self",
",",
"ordering",
":",
"np",
".",
"ndarray",
",",
"axis",
":",
"int",
")",
"->",
"None",
":",
"if",
"self",
".",
"_file",
".",
"__contains__",
"(",
"\"tiles\"",
")",
":",
"del",
"self",
".",
"_file",
"[",
"'tiles'",
"]... | 27.826087 | 0.031722 |
def state(self):
"""State of this service."""
if self._proto.HasField('state'):
return yamcsManagement_pb2.ServiceState.Name(self._proto.state)
return None | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"_proto",
".",
"HasField",
"(",
"'state'",
")",
":",
"return",
"yamcsManagement_pb2",
".",
"ServiceState",
".",
"Name",
"(",
"self",
".",
"_proto",
".",
"state",
")",
"return",
"None"
] | 37.4 | 0.010471 |
def eval_input(self, expr):
"""eval_input: testlist NEWLINE* ENDMARKER"""
return ast.Expression(body=[expr], loc=expr.loc) | [
"def",
"eval_input",
"(",
"self",
",",
"expr",
")",
":",
"return",
"ast",
".",
"Expression",
"(",
"body",
"=",
"[",
"expr",
"]",
",",
"loc",
"=",
"expr",
".",
"loc",
")"
] | 45.333333 | 0.014493 |
def lookup(name, min_similarity_ratio=.75):
"""
Look up for a Stan function with similar functionality to a Python
function (or even an R function, see examples). If the function is
not present on the lookup table, then attempts to find similar one
and prints the results. This function requires pack... | [
"def",
"lookup",
"(",
"name",
",",
"min_similarity_ratio",
"=",
".75",
")",
":",
"if",
"lookuptable",
"is",
"None",
":",
"build",
"(",
")",
"if",
"name",
"not",
"in",
"lookuptable",
".",
"keys",
"(",
")",
":",
"from",
"difflib",
"import",
"SequenceMatche... | 38.337838 | 0.000687 |
def _expand_vector(self,x):
'''
Takes a value x in the subspace of not fixed dimensions and expands it with the values of the fixed ones.
:param x: input vector to be expanded by adding the context values
'''
x = np.atleast_2d(x)
x_expanded = np.zeros((x.shape[0],self.spa... | [
"def",
"_expand_vector",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"x_expanded",
"=",
"np",
".",
"zeros",
"(",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"space",
".",
"model_dimensionality",
... | 51.8 | 0.018975 |
def revoke_all(cls, cur, schema_name, roles):
"""
Revoke all privileges from schema, tables, sequences and functions for a specific role
"""
cur.execute('REVOKE ALL ON SCHEMA {0} FROM {1};'
'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};'
'REVOKE... | [
"def",
"revoke_all",
"(",
"cls",
",",
"cur",
",",
"schema_name",
",",
"roles",
")",
":",
"cur",
".",
"execute",
"(",
"'REVOKE ALL ON SCHEMA {0} FROM {1};'",
"'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};'",
"'REVOKE ALL ON ALL SEQUENCES IN SCHEMA {0} FROM {1};'",
"'REVOKE A... | 57.625 | 0.008547 |
def voice_channels(self):
"""List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)]
r.sort(key=lambda ... | [
"def",
"voice_channels",
"(",
"self",
")",
":",
"r",
"=",
"[",
"ch",
"for",
"ch",
"in",
"self",
".",
"_channels",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"ch",
",",
"VoiceChannel",
")",
"]",
"r",
".",
"sort",
"(",
"key",
"=",
"lambda",
... | 44 | 0.011142 |
def simple_error_handler(exc, *args):
"""
Returns the response that should be used for any given exception.
By default we handle the REST framework `APIException`, and also
Django's builtin `Http404` and `PermissionDenied` exceptions.
Any unhandled exceptions may return `None`, which will cause a ... | [
"def",
"simple_error_handler",
"(",
"exc",
",",
"*",
"args",
")",
":",
"if",
"isinstance",
"(",
"exc",
",",
"exceptions",
".",
"APIException",
")",
":",
"headers",
"=",
"{",
"}",
"if",
"getattr",
"(",
"exc",
",",
"'auth_header'",
",",
"None",
")",
":",... | 35.967742 | 0.000873 |
def searchResults(self, REQUEST=None, used=None, **kw):
"""Search the catalog
Search terms can be passed in the REQUEST or as keyword
arguments.
The used argument is now deprecated and ignored
"""
if REQUEST and REQUEST.get('getRequestUID') \
and self.id == CATALOG_ANALYSIS_LISTING... | [
"def",
"searchResults",
"(",
"self",
",",
"REQUEST",
"=",
"None",
",",
"used",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"REQUEST",
"and",
"REQUEST",
".",
"get",
"(",
"'getRequestUID'",
")",
"and",
"self",
".",
"id",
"==",
"CATALOG_ANALYSIS_LIS... | 38.487805 | 0.001236 |
def getSubgraphFieldCount(self, parent_name, graph_name):
"""Returns number of fields for subgraph with name graph_name and parent
graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: Number of fields for... | [
"def",
"getSubgraphFieldCount",
"(",
"self",
",",
"parent_name",
",",
"graph_name",
")",
":",
"graph",
"=",
"self",
".",
"_getSubGraph",
"(",
"parent_name",
",",
"graph_name",
",",
"True",
")",
"return",
"graph",
".",
"getFieldCount",
"(",
")"
] | 40.272727 | 0.013245 |
async def startlisten(self, connmark = -1):
'''
Can call without delegate
'''
if connmark is None:
connmark = self.connmark
self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.STARTLISTEN, True, connmark)) | [
"async",
"def",
"startlisten",
"(",
"self",
",",
"connmark",
"=",
"-",
"1",
")",
":",
"if",
"connmark",
"is",
"None",
":",
"connmark",
"=",
"self",
".",
"connmark",
"self",
".",
"scheduler",
".",
"emergesend",
"(",
"ConnectionControlEvent",
"(",
"self",
... | 39.571429 | 0.017668 |
def scheduling_cutting_plane(J,p,r,w):
"""
scheduling_cutting_plane: heuristic to one machine weighted completion time based on cutting planes
Use a cutting-plane method as a heuristics for solving the
one-machine total weighted completion time problem with release
times.
Parameters:
-... | [
"def",
"scheduling_cutting_plane",
"(",
"J",
",",
"p",
",",
"r",
",",
"w",
")",
":",
"model",
"=",
"Model",
"(",
"\"scheduling: cutting plane\"",
")",
"C",
"=",
"{",
"}",
"# completion time variable",
"for",
"j",
"in",
"J",
":",
"C",
"[",
"j",
"]",
"="... | 29.897059 | 0.012381 |
def process_sels(self):
"""
Process soft clause selectors participating in a new core.
The negation :math:`\\neg{s}` of each selector literal
:math:`s` participating in the unsatisfiable core is added
to the list of relaxation literals, which will be later
... | [
"def",
"process_sels",
"(",
"self",
")",
":",
"# new relaxation variables",
"self",
".",
"rels",
"=",
"[",
"]",
"for",
"l",
"in",
"self",
".",
"core_sels",
":",
"if",
"self",
".",
"wght",
"[",
"l",
"]",
"==",
"self",
".",
"minw",
":",
"# marking variab... | 40.351351 | 0.001962 |
def _copy(self, filename, dir1, dir2):
""" Private function for copying a file """
# NOTE: dir1 is source & dir2 is target
if self._copyfiles:
rel_path = filename.replace('\\', '/').split('/')
rel_dir = '/'.join(rel_path[:-1])
filename = rel_path[-1]
... | [
"def",
"_copy",
"(",
"self",
",",
"filename",
",",
"dir1",
",",
"dir2",
")",
":",
"# NOTE: dir1 is source & dir2 is target",
"if",
"self",
".",
"_copyfiles",
":",
"rel_path",
"=",
"filename",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
".",
"split",
"(... | 38.554217 | 0.000609 |
def query_pa_no_flush(session, permission, role, obj):
"""Query for a :class:`PermissionAssignment` using `session` without any
`flush()`.
It works by looking in session `new`, `dirty` and `deleted`, and issuing a
query with no autoflush.
.. note::
This function is used by `add_permission... | [
"def",
"query_pa_no_flush",
"(",
"session",
",",
"permission",
",",
"role",
",",
"obj",
")",
":",
"to_visit",
"=",
"[",
"session",
".",
"deleted",
",",
"session",
".",
"dirty",
",",
"session",
".",
"new",
"]",
"with",
"session",
".",
"no_autoflush",
":",... | 37.84 | 0.002061 |
def create(self,*fields,**kw):
"""Create a new base with specified field names
A keyword argument mode can be specified ; it is used if a file
with the base name already exists
- if mode = 'open' : open the existing base, ignore the fields
- if mode = 'override' : erase the ... | [
"def",
"create",
"(",
"self",
",",
"*",
"fields",
",",
"*",
"*",
"kw",
")",
":",
"mode",
"=",
"kw",
".",
"get",
"(",
"\"mode\"",
",",
"None",
")",
"if",
"self",
".",
"_table_exists",
"(",
")",
":",
"if",
"mode",
"==",
"\"override\"",
":",
"self",... | 50.36 | 0.020265 |
def read_igor_marginals_txt(marginals_file_name , dim_names=False):
"""Load raw IGoR model marginals.
Parameters
----------
marginals_file_name : str
File name for a IGOR model marginals file.
Returns
-------
model_dict : dict
Dictionary with model marginals.
dimens... | [
"def",
"read_igor_marginals_txt",
"(",
"marginals_file_name",
",",
"dim_names",
"=",
"False",
")",
":",
"with",
"open",
"(",
"marginals_file_name",
",",
"'r'",
")",
"as",
"file",
":",
"#Model parameters are stored inside a dictionary of ndarrays",
"model_dict",
"=",
"{"... | 40.631068 | 0.016095 |
def _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=1.):
"""We want to disincentivize unneeded colors. Generates the QUBO
that does that.
"""
# if we already know the chromatic number, then we don't need to
# disincentivize any colors.
if chi_lb == chi_ub:
return {}
# we mi... | [
"def",
"_minimum_coloring_qubo",
"(",
"x_vars",
",",
"chi_lb",
",",
"chi_ub",
",",
"magnitude",
"=",
"1.",
")",
":",
"# if we already know the chromatic number, then we don't need to",
"# disincentivize any colors.",
"if",
"chi_lb",
"==",
"chi_ub",
":",
"return",
"{",
"... | 31.380952 | 0.001473 |
def index_of(pattern):
'''Return the index of a given pattern'''
return (pattern[0,0] * 2**0 + pattern[0,1] * 2**1 + pattern[0,2] * 2**2 +
pattern[1,0] * 2**3 + pattern[1,1] * 2**4 + pattern[1,2] * 2**5 +
pattern[2,0] * 2**6 + pattern[2,1] * 2**7 + pattern[2,2] * 2**8) | [
"def",
"index_of",
"(",
"pattern",
")",
":",
"return",
"(",
"pattern",
"[",
"0",
",",
"0",
"]",
"*",
"2",
"**",
"0",
"+",
"pattern",
"[",
"0",
",",
"1",
"]",
"*",
"2",
"**",
"1",
"+",
"pattern",
"[",
"0",
",",
"2",
"]",
"*",
"2",
"**",
"2... | 59.4 | 0.033223 |
def completion_post_event_input_accelerators(editor, event):
"""
Implements completion post event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Process event.
:rtype: bool
"""
if editor.... | [
"def",
"completion_post_event_input_accelerators",
"(",
"editor",
",",
"event",
")",
":",
"if",
"editor",
".",
"completer",
":",
"if",
"editor",
".",
"completer",
".",
"popup",
"(",
")",
".",
"isVisible",
"(",
")",
":",
"perform_completion",
"(",
"editor",
"... | 26.1875 | 0.002304 |
def send_notifications(self, notification_type, *args):
""" Fires off the notification for the specific event. Uses var args to pass in a
arbitrary list of parameter according to which notification type was fired.
Args:
notification_type: Type of notification to fire (String from .helpers.enums.... | [
"def",
"send_notifications",
"(",
"self",
",",
"notification_type",
",",
"*",
"args",
")",
":",
"if",
"notification_type",
"in",
"self",
".",
"notifications",
":",
"for",
"notification_id",
",",
"callback",
"in",
"self",
".",
"notifications",
"[",
"notification_... | 42.533333 | 0.01227 |
def getsockopt(self, level, optname, *args, **kwargs):
"""get the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``getsockopt(2)`` for more information.
... | [
"def",
"getsockopt",
"(",
"self",
",",
"level",
",",
"optname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_sock",
".",
"getsockopt",
"(",
"level",
",",
"optname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 42.1 | 0.002323 |
def input(self, prompt, default=None, show_default=True):
"""Provide a command prompt."""
return click.prompt(prompt, default=default, show_default=show_default) | [
"def",
"input",
"(",
"self",
",",
"prompt",
",",
"default",
"=",
"None",
",",
"show_default",
"=",
"True",
")",
":",
"return",
"click",
".",
"prompt",
"(",
"prompt",
",",
"default",
"=",
"default",
",",
"show_default",
"=",
"show_default",
")"
] | 58.333333 | 0.011299 |
def _do_connect(self):
""" Connect to the remote. """
self.load_system_host_keys()
if self.username is None or self.port is None:
self._configure()
try:
self.connect(hostname=self.hostname,
port=self.port,
username... | [
"def",
"_do_connect",
"(",
"self",
")",
":",
"self",
".",
"load_system_host_keys",
"(",
")",
"if",
"self",
".",
"username",
"is",
"None",
"or",
"self",
".",
"port",
"is",
"None",
":",
"self",
".",
"_configure",
"(",
")",
"try",
":",
"self",
".",
"con... | 40.7 | 0.002401 |
def telnet_login(
self,
pri_prompt_terminator=r"#\s*$",
alt_prompt_terminator=r">\s*$",
username_pattern=r"(?:user:|username|login|user name)",
pwd_pattern=r"assword",
delay_factor=1,
max_loops=20,
):
"""Telnet login. Can be username/password or just p... | [
"def",
"telnet_login",
"(",
"self",
",",
"pri_prompt_terminator",
"=",
"r\"#\\s*$\"",
",",
"alt_prompt_terminator",
"=",
"r\">\\s*$\"",
",",
"username_pattern",
"=",
"r\"(?:user:|username|login|user name)\"",
",",
"pwd_pattern",
"=",
"r\"assword\"",
",",
"delay_factor",
"... | 38.195122 | 0.002179 |
def scan(self, cursor=0, match=None, count=None):
"""
Incrementally return lists of key names. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
f = F... | [
"def",
"scan",
"(",
"self",
",",
"cursor",
"=",
"0",
",",
"match",
"=",
"None",
",",
"count",
"=",
"None",
")",
":",
"f",
"=",
"Future",
"(",
")",
"if",
"self",
".",
"keyspace",
"is",
"None",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",... | 29.317073 | 0.00161 |
def set_concurrency_options(self, thread_safe=True, handler_thread=True):
"""Set concurrency options for this device server.
Must be called before :meth:`start`.
Parameters
==========
thread_safe : bool
If True, make the server public methods thread safe. Incurs
... | [
"def",
"set_concurrency_options",
"(",
"self",
",",
"thread_safe",
"=",
"True",
",",
"handler_thread",
"=",
"True",
")",
":",
"if",
"handler_thread",
":",
"assert",
"thread_safe",
",",
"\"handler_thread=True requires thread_safe=True\"",
"self",
".",
"_server",
".",
... | 45.121212 | 0.001315 |
def _make_image_description(self, datasets, **kwargs):
"""
generate image description for mitiff.
Satellite: NOAA 18
Date and Time: 06:58 31/05-2016
SatDir: 0
Channels: 6 In this file: 1-VIS0.63 2-VIS0.86 3(3B)-IR3.7
4-IR10.8 5-IR11.5 6(3A)-VIS1.6
Xsize... | [
"def",
"_make_image_description",
"(",
"self",
",",
"datasets",
",",
"*",
"*",
"kwargs",
")",
":",
"translate_platform_name",
"=",
"{",
"'metop01'",
":",
"'Metop-B'",
",",
"'metop02'",
":",
"'Metop-A'",
",",
"'metop03'",
":",
"'Metop-C'",
",",
"'noaa15'",
":",... | 36.159722 | 0.000748 |
def stem(self, word):
"""Return 'CLEF German stemmer plus' stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = CLEFGermanPlus()
>>> clef_germa... | [
"def",
"stem",
"(",
"self",
",",
"word",
")",
":",
"# lowercase, normalize, and compose",
"word",
"=",
"normalize",
"(",
"'NFC'",
",",
"text_type",
"(",
"word",
".",
"lower",
"(",
")",
")",
")",
"# remove umlauts",
"word",
"=",
"word",
".",
"translate",
"(... | 24.358491 | 0.001489 |
def set_partner_id_from_partner_address_id(
cr, pool, model_name, partner_field, address_field, table=None):
"""
Set the new partner_id on any table with migrated contact ids
:param model_name: the model name of the target table
:param partner_field: the column in the target model's table \
... | [
"def",
"set_partner_id_from_partner_address_id",
"(",
"cr",
",",
"pool",
",",
"model_name",
",",
"partner_field",
",",
"address_field",
",",
"table",
"=",
"None",
")",
":",
"model",
"=",
"pool",
".",
"get",
"(",
"model_name",
")",
"table",
"=",
"table",
"or"... | 41.96 | 0.000932 |
def bucket_create(self, name, bucket_type='couchbase',
bucket_password='', replicas=0, ram_quota=1024,
flush_enabled=False):
"""
Create a new bucket
:param string name: The name of the bucket to create
:param string bucket_type: The type of bu... | [
"def",
"bucket_create",
"(",
"self",
",",
"name",
",",
"bucket_type",
"=",
"'couchbase'",
",",
"bucket_password",
"=",
"''",
",",
"replicas",
"=",
"0",
",",
"ram_quota",
"=",
"1024",
",",
"flush_enabled",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'nam... | 48.897959 | 0.001637 |
def _format_evidence_text(stmt):
"""Returns evidence metadata with highlighted evidence text.
Parameters
----------
stmt : indra.Statement
The Statement with Evidence to be formatted.
Returns
-------
list of dicts
List of dictionaries cor... | [
"def",
"_format_evidence_text",
"(",
"stmt",
")",
":",
"def",
"get_role",
"(",
"ag_ix",
")",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"Complex",
")",
"or",
"isinstance",
"(",
"stmt",
",",
"SelfModification",
")",
"or",
"isinstance",
"(",
"stmt",
",",
"... | 43.8 | 0.001489 |
def object_patch_add_link(self, root, name, ref, create=False, **kwargs):
"""Creates a new merkledag object based on an existing one.
The new object will have a link to the provided object.
.. code-block:: python
>>> c.object_patch_add_link(
... 'QmR79zQQj2aDfnrNgc... | [
"def",
"object_patch_add_link",
"(",
"self",
",",
"root",
",",
"name",
",",
"ref",
",",
"create",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"create\"",
":",
"create",
"}",
")",
"args",
... | 32.441176 | 0.001761 |
def removeAttributeNode(self, attr: Attr) -> Optional[Attr]:
"""Remove ``Attr`` node from this node."""
return self.attributes.removeNamedItem(attr) | [
"def",
"removeAttributeNode",
"(",
"self",
",",
"attr",
":",
"Attr",
")",
"->",
"Optional",
"[",
"Attr",
"]",
":",
"return",
"self",
".",
"attributes",
".",
"removeNamedItem",
"(",
"attr",
")"
] | 54 | 0.012195 |
def VerifySignature(self, message, signature, public_key, unhex=True):
"""
Verify the integrity of the message.
Args:
message (str): the message to verify.
signature (bytearray): the signature belonging to the message.
public_key (ECPoint): the public key to ... | [
"def",
"VerifySignature",
"(",
"self",
",",
"message",
",",
"signature",
",",
"public_key",
",",
"unhex",
"=",
"True",
")",
":",
"return",
"Crypto",
".",
"VerifySignature",
"(",
"message",
",",
"signature",
",",
"public_key",
",",
"unhex",
"=",
"unhex",
")... | 42.928571 | 0.008143 |
def _concatenate_spike_clusters(*pairs):
"""Concatenate a list of pairs (spike_ids, spike_clusters)."""
pairs = [(_as_array(x), _as_array(y)) for (x, y) in pairs]
concat = np.vstack(np.hstack((x[:, None], y[:, None]))
for x, y in pairs)
reorder = np.argsort(concat[:, 0])
conca... | [
"def",
"_concatenate_spike_clusters",
"(",
"*",
"pairs",
")",
":",
"pairs",
"=",
"[",
"(",
"_as_array",
"(",
"x",
")",
",",
"_as_array",
"(",
"y",
")",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"pairs",
"]",
"concat",
"=",
"np",
".",
"vstack",
"... | 50.875 | 0.002415 |
def delete_cluster_custom_object(self, group, version, plural, name, body, **kwargs): # noqa: E501
"""delete_cluster_custom_object # noqa: E501
Deletes the specified cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchro... | [
"def",
"delete_cluster_custom_object",
"(",
"self",
",",
"group",
",",
"version",
",",
"plural",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
... | 83.928571 | 0.000841 |
def findall(self):
"""Find all files under the base and set ``allfiles`` to the absolute
pathnames of files found.
"""
from stat import S_ISREG, S_ISDIR, S_ISLNK
self.allfiles = allfiles = []
root = self.base
stack = [root]
pop = stack.pop
push = ... | [
"def",
"findall",
"(",
"self",
")",
":",
"from",
"stat",
"import",
"S_ISREG",
",",
"S_ISDIR",
",",
"S_ISLNK",
"self",
".",
"allfiles",
"=",
"allfiles",
"=",
"[",
"]",
"root",
"=",
"self",
".",
"base",
"stack",
"=",
"[",
"root",
"]",
"pop",
"=",
"st... | 31.153846 | 0.002395 |
def context(self):
"""
Create a context manager that ensures code runs within action's context.
The action does NOT finish when the context is exited.
"""
parent = _ACTION_CONTEXT.set(self)
try:
yield self
finally:
_ACTION_CONTEXT.reset(pa... | [
"def",
"context",
"(",
"self",
")",
":",
"parent",
"=",
"_ACTION_CONTEXT",
".",
"set",
"(",
"self",
")",
"try",
":",
"yield",
"self",
"finally",
":",
"_ACTION_CONTEXT",
".",
"reset",
"(",
"parent",
")"
] | 28.636364 | 0.009231 |
def _prepare_upload_info(self, source, dest_uri):
"""Prepare Upload object, resolve paths"""
try:
dest_resource = self.get_resource_by_uri(dest_uri)
except ResourceNotFoundError:
dest_resource = None
is_fh = hasattr(source, 'read')
folder_key = None
... | [
"def",
"_prepare_upload_info",
"(",
"self",
",",
"source",
",",
"dest_uri",
")",
":",
"try",
":",
"dest_resource",
"=",
"self",
".",
"get_resource_by_uri",
"(",
"dest_uri",
")",
"except",
"ResourceNotFoundError",
":",
"dest_resource",
"=",
"None",
"is_fh",
"=",
... | 39.355556 | 0.001102 |
def parse_model_group(path, group):
"""Parse a structured model group as obtained from a YAML file
Path can be given as a string or a context.
"""
context = FilePathContext(path)
for reaction_id in group.get('reactions', []):
yield reaction_id
# Parse subgroups
for reaction_id in... | [
"def",
"parse_model_group",
"(",
"path",
",",
"group",
")",
":",
"context",
"=",
"FilePathContext",
"(",
"path",
")",
"for",
"reaction_id",
"in",
"group",
".",
"get",
"(",
"'reactions'",
",",
"[",
"]",
")",
":",
"yield",
"reaction_id",
"# Parse subgroups",
... | 26.866667 | 0.002398 |
def minimumLabelHeight(self):
"""
Returns the minimum height that will be required based on this font size
and labels list.
"""
metrics = QFontMetrics(self.labelFont())
return max(self._minimumLabelHeight,
metrics.height() + self.verticalLabelPad... | [
"def",
"minimumLabelHeight",
"(",
"self",
")",
":",
"metrics",
"=",
"QFontMetrics",
"(",
"self",
".",
"labelFont",
"(",
")",
")",
"return",
"max",
"(",
"self",
".",
"_minimumLabelHeight",
",",
"metrics",
".",
"height",
"(",
")",
"+",
"self",
".",
"vertic... | 40 | 0.009174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.