text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def hybrid_meco_frequency(m1, m2, chi1, chi2, qm1=None, qm2=None):
"""Return the frequency of the hybrid MECO
Parameters
----------
m1 : float
Mass of the primary object in solar masses.
m2 : float
Mass of the secondary object in solar masses.
chi1: float
Dimensionless s... | [
"def",
"hybrid_meco_frequency",
"(",
"m1",
",",
"m2",
",",
"chi1",
",",
"chi2",
",",
"qm1",
"=",
"None",
",",
"qm2",
"=",
"None",
")",
":",
"if",
"qm1",
"is",
"None",
":",
"qm1",
"=",
"1",
"if",
"qm2",
"is",
"None",
":",
"qm2",
"=",
"1",
"retur... | 30.580645 | 0.002045 |
def find_files(directory, ext=None, recurse=True, case_sensitive=False,
limit=None, offset=0):
'''Get a sorted list of (audio) files in a directory or directory sub-tree.
Examples
--------
>>> # Get all audio files in a directory sub-tree
>>> files = librosa.util.find_files('~/Music'... | [
"def",
"find_files",
"(",
"directory",
",",
"ext",
"=",
"None",
",",
"recurse",
"=",
"True",
",",
"case_sensitive",
"=",
"False",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"0",
")",
":",
"if",
"ext",
"is",
"None",
":",
"ext",
"=",
"[",
"'aac'"... | 26.772727 | 0.000409 |
def get_configdir():
"""Return string representing the configuration directory.
Default is $HOME/.config/glymur. You can override this with the
XDG_CONFIG_HOME environment variable.
"""
if 'XDG_CONFIG_HOME' in os.environ:
return os.path.join(os.environ['XDG_CONFIG_HOME'], 'glymur')
if... | [
"def",
"get_configdir",
"(",
")",
":",
"if",
"'XDG_CONFIG_HOME'",
"in",
"os",
".",
"environ",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"'XDG_CONFIG_HOME'",
"]",
",",
"'glymur'",
")",
"if",
"'HOME'",
"in",
"os",
"."... | 39.375 | 0.00155 |
def get_files(directory, recursive=False):
"""Return a list of all files in the directory."""
files_out = []
if recursive:
for root, dirs, files in os.walk(os.path.abspath(directory)):
files = [os.path.join(root, f) for f in files]
files_out.append(files)
files_out = ... | [
"def",
"get_files",
"(",
"directory",
",",
"recursive",
"=",
"False",
")",
":",
"files_out",
"=",
"[",
"]",
"if",
"recursive",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"dir... | 40.928571 | 0.001706 |
def get_fastq_files_props(self,barcode=None):
"""
Returns the DNAnexus file properties for all FASTQ files in the project that match the
specified barcode, or all FASTQ files if not barcode is specified.
Args:
barcode: `str`. If set, then only FASTQ file properties for FA... | [
"def",
"get_fastq_files_props",
"(",
"self",
",",
"barcode",
"=",
"None",
")",
":",
"fastqs",
"=",
"self",
".",
"get_fastq_dxfile_objects",
"(",
"barcode",
"=",
"barcode",
")",
"#FastqNotFound Exception here if no FASTQs found for specified barcode.",
"dico",
"=",
"{",
... | 49.666667 | 0.014815 |
def send_audio_file(
self, audio_file, device_state, authentication_headers,
dialog_request_id, distance_profile, audio_format
):
"""
Send audio to AVS
The file-like object are steaming uploaded for improved latency.
Returns:
bytes -- wav audio bytes ret... | [
"def",
"send_audio_file",
"(",
"self",
",",
"audio_file",
",",
"device_state",
",",
"authentication_headers",
",",
"dialog_request_id",
",",
"distance_profile",
",",
"audio_format",
")",
":",
"payload",
"=",
"{",
"'context'",
":",
"device_state",
",",
"'event'",
"... | 30.5 | 0.001537 |
def delete_cloud_integration(self, id, **kwargs): # noqa: E501
"""Delete a specific cloud integration # 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.delete_c... | [
"def",
"delete_cloud_integration",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"del... | 43.238095 | 0.002155 |
def nodes_touching_tile(tile_id):
"""
Get a list of node coordinates touching the given tile.
:param tile_id: tile identifier, Tile.tile_id
:return: list of node coordinates touching the given tile, list(int)
"""
coord = tile_id_to_coord(tile_id)
nodes = []
for offset in _tile_node_offs... | [
"def",
"nodes_touching_tile",
"(",
"tile_id",
")",
":",
"coord",
"=",
"tile_id_to_coord",
"(",
"tile_id",
")",
"nodes",
"=",
"[",
"]",
"for",
"offset",
"in",
"_tile_node_offsets",
".",
"keys",
"(",
")",
":",
"nodes",
".",
"append",
"(",
"coord",
"+",
"of... | 34.538462 | 0.002169 |
def _missing_values_set_to_nan(values, missing_value, sparse_missing):
""" Return a copy of values where missing values (equal to missing_value)
are replaced to nan according. If sparse_missing is True,
entries missing in a sparse matrix will also be set to nan.
Sparse matrices will be converted to dens... | [
"def",
"_missing_values_set_to_nan",
"(",
"values",
",",
"missing_value",
",",
"sparse_missing",
")",
":",
"if",
"sp",
".",
"issparse",
"(",
"values",
")",
":",
"assert",
"values",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
"if",
"sparse_missing",
"and",
"sp"... | 43.166667 | 0.000944 |
def updateBoostStrength(self):
"""
Update boost strength using given strength factor during training
"""
if self.training:
self.boostStrength = self.boostStrength * self.boostStrengthFactor | [
"def",
"updateBoostStrength",
"(",
"self",
")",
":",
"if",
"self",
".",
"training",
":",
"self",
".",
"boostStrength",
"=",
"self",
".",
"boostStrength",
"*",
"self",
".",
"boostStrengthFactor"
] | 34.333333 | 0.009479 |
def _move_modules(self, temp_repo, destination):
"""Move odoo modules from the temp directory to the destination.
This step is different from a standard repository. In the base code
of Odoo, the modules are contained in a addons folder at the root
of the git repository. However, when de... | [
"def",
"_move_modules",
"(",
"self",
",",
"temp_repo",
",",
"destination",
")",
":",
"tmp_addons",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_repo",
",",
"'addons'",
")",
"tmp_odoo_addons",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_repo",
",",... | 47.105263 | 0.002191 |
def convert(self, samplerate=None, n_channels=None, bitdepth=None):
'''Converts output audio to the specified format.
Parameters
----------
samplerate : float, default=None
Desired samplerate. If None, defaults to the same as input.
n_channels : int, default=None
... | [
"def",
"convert",
"(",
"self",
",",
"samplerate",
"=",
"None",
",",
"n_channels",
"=",
"None",
",",
"bitdepth",
"=",
"None",
")",
":",
"bitdepths",
"=",
"[",
"8",
",",
"16",
",",
"24",
",",
"32",
",",
"64",
"]",
"if",
"bitdepth",
"is",
"not",
"No... | 38.542857 | 0.001446 |
def mpraw_as_np(shape, dtype):
"""Construct a numpy array of the specified shape and dtype for which the
underlying storage is a multiprocessing RawArray in shared memory.
Parameters
----------
shape : tuple
Shape of numpy array
dtype : data-type
Data type of array
Returns
... | [
"def",
"mpraw_as_np",
"(",
"shape",
",",
"dtype",
")",
":",
"sz",
"=",
"int",
"(",
"np",
".",
"product",
"(",
"shape",
")",
")",
"csz",
"=",
"sz",
"*",
"np",
".",
"dtype",
"(",
"dtype",
")",
".",
"itemsize",
"raw",
"=",
"mp",
".",
"RawArray",
"... | 24.952381 | 0.001838 |
def _password_digest(username, password):
"""Get a password digest to use for authentication.
"""
if not isinstance(password, basestring):
raise TypeError("password must be an instance of basestring")
if not isinstance(username, basestring):
raise TypeError("username must be an instance ... | [
"def",
"_password_digest",
"(",
"username",
",",
"password",
")",
":",
"if",
"not",
"isinstance",
"(",
"password",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"password must be an instance of basestring\"",
")",
"if",
"not",
"isinstance",
"(",
"usern... | 43.166667 | 0.00189 |
def sendConnect(self, data):
"""Send a CONNECT command to the broker
:param data: List of other broker main socket URL"""
# Imported dynamically - Not used if only one broker
if self.backend == 'ZMQ':
import zmq
self.context = zmq.Context()
self.so... | [
"def",
"sendConnect",
"(",
"self",
",",
"data",
")",
":",
"# Imported dynamically - Not used if only one broker",
"if",
"self",
".",
"backend",
"==",
"'ZMQ'",
":",
"import",
"zmq",
"self",
".",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"self",
".",
"s... | 39.9 | 0.002448 |
def parse(self, fo):
"""
Convert MEME output to motifs
Parameters
----------
fo : file-like
File object containing MEME output.
Returns
-------
motifs : list
List of Motif instances.
"""
motifs = []
... | [
"def",
"parse",
"(",
"self",
",",
"fo",
")",
":",
"motifs",
"=",
"[",
"]",
"nucs",
"=",
"{",
"\"A\"",
":",
"0",
",",
"\"C\"",
":",
"1",
",",
"\"G\"",
":",
"2",
",",
"\"T\"",
":",
"3",
"}",
"p",
"=",
"re",
".",
"compile",
"(",
"'MOTIF.+MEME-(\... | 31.94 | 0.017618 |
def write(parsed_obj, spec=None, filename=None):
"""Writes an object created by `parse` to either a file or a bytearray.
If the object doesn't end on a byte boundary, zeroes are appended to it
until it does.
"""
if not isinstance(parsed_obj, BreadStruct):
raise ValueError(
'Obje... | [
"def",
"write",
"(",
"parsed_obj",
",",
"spec",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"parsed_obj",
",",
"BreadStruct",
")",
":",
"raise",
"ValueError",
"(",
"'Object to write must be a structure created '",
"'by br... | 37.625 | 0.001621 |
def y(self,*args,**kwargs):
"""
NAME:
y
PURPOSE:
return y
INPUT:
t - (optional) time at which to get y (can be Quantity)
ro= (Object-wide default) physical scale for distances to use to convert (can be Quantity)
use_physical= ... | [
"def",
"y",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
".",
"_orb",
".",
"y",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"out",
")",
"==",
"1",
":",
"return",
"out",
"[",
"... | 19.366667 | 0.016393 |
def _multiseries(self, col, x, y, ctype, rsum, rmean):
"""
Chart multiple series from a column distinct values
"""
self.autoprint = False
x, y = self._check_fields(x, y)
chart = None
series = self.split_(col)
for key in series:
instance = series[key]
if rsum is not None:
instance.rsum(rsum, in... | [
"def",
"_multiseries",
"(",
"self",
",",
"col",
",",
"x",
",",
"y",
",",
"ctype",
",",
"rsum",
",",
"rmean",
")",
":",
"self",
".",
"autoprint",
"=",
"False",
"x",
",",
"y",
"=",
"self",
".",
"_check_fields",
"(",
"x",
",",
"y",
")",
"chart",
"... | 23.777778 | 0.044893 |
def delete_directory(i):
"""
Input: {
path - path to delete
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
import shu... | [
"def",
"delete_directory",
"(",
"i",
")",
":",
"import",
"shutil",
"p",
"=",
"i",
"[",
"'path'",
"]",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"p",
")",
":",
"shutil",
".",
"rmtree",
"(",
"p",
",",
"onerror",
"=",
"rm_read_only",
")",
"return",
... | 19.857143 | 0.009153 |
def execute(self, request, target_route):
""" :meth:`.WWebServiceProto.execute` method implementation
"""
presenter = self.create_presenter(request, target_route)
presenter_name = target_route.presenter_name()
action_name = target_route.presenter_action()
presenter_args = target_route.presenter_args()
if... | [
"def",
"execute",
"(",
"self",
",",
"request",
",",
"target_route",
")",
":",
"presenter",
"=",
"self",
".",
"create_presenter",
"(",
"request",
",",
"target_route",
")",
"presenter_name",
"=",
"target_route",
".",
"presenter_name",
"(",
")",
"action_name",
"=... | 32.2 | 0.026701 |
def cmvnw(vec, win_size=301, variance_normalization=False):
""" This function is aimed to perform local cepstral mean and
variance normalization on a sliding window. The code assumes that
there is one observation per row.
Args:
vec (array): input feature matrix
(size:(num_observatio... | [
"def",
"cmvnw",
"(",
"vec",
",",
"win_size",
"=",
"301",
",",
"variance_normalization",
"=",
"False",
")",
":",
"# Get the shapes",
"eps",
"=",
"2",
"**",
"-",
"30",
"rows",
",",
"cols",
"=",
"vec",
".",
"shape",
"# Windows size must be odd.",
"assert",
"i... | 35.925926 | 0.001004 |
def copy(self, keys = None):
"""
Return a copy of the segmentlistdict object. The return
value is a new object with a new offsets attribute, with
references to the original keys, and shallow copies of the
segment lists. Modifications made to the offset dictionary
or segmentlists in the object returned by ... | [
"def",
"copy",
"(",
"self",
",",
"keys",
"=",
"None",
")",
":",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"self",
"new",
"=",
"self",
".",
"__class__",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"new",
"[",
"key",
"]",
"=",
"_shallowcopy",
... | 36.953488 | 0.025138 |
def OauthGetAccessToken(self):
"""
Use token_verifier to obtain an access token for the user. If this function returns True, the clients __oauth_token__ member
contains the access token.
@return (boolean) - Boolean indicating whether OauthGetRequestToken wa... | [
"def",
"OauthGetAccessToken",
"(",
"self",
")",
":",
"self",
".",
"__setAuthenticationMethod__",
"(",
"'authenticating_oauth'",
")",
"# obtain access token\r",
"oauth_request",
"=",
"oauth",
".",
"OAuthRequest",
".",
"from_consumer_and_token",
"(",
"self",
".",
"__oauth... | 54.71875 | 0.015713 |
def extract_java_messages():
"""
loop through java_*_0.out.txt and extract potentially dangerous WARN/ERRR/FATAL
messages associated with a test. The test may even pass but something terrible
has actually happened.
:return: none
"""
global g_jenkins_url
global g_failed_test_info_dict
... | [
"def",
"extract_java_messages",
"(",
")",
":",
"global",
"g_jenkins_url",
"global",
"g_failed_test_info_dict",
"global",
"g_java_filenames",
"global",
"g_failed_jobs",
"# record job names of failed jobs",
"global",
"g_failed_job_java_messages",
"# record failed job java message",
"... | 48.444444 | 0.011691 |
def inline_query(self):
"""The query ``str`` for :tl:`KeyboardButtonSwitchInline` objects."""
if isinstance(self.button, types.KeyboardButtonSwitchInline):
return self.button.query | [
"def",
"inline_query",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"button",
",",
"types",
".",
"KeyboardButtonSwitchInline",
")",
":",
"return",
"self",
".",
"button",
".",
"query"
] | 51.25 | 0.009615 |
def all_domain_events(self):
"""
Yields all domain events in the event store.
"""
for originator_id in self.record_manager.all_sequence_ids():
for domain_event in self.get_domain_events(originator_id=originator_id, page_size=100):
yield domain_event | [
"def",
"all_domain_events",
"(",
"self",
")",
":",
"for",
"originator_id",
"in",
"self",
".",
"record_manager",
".",
"all_sequence_ids",
"(",
")",
":",
"for",
"domain_event",
"in",
"self",
".",
"get_domain_events",
"(",
"originator_id",
"=",
"originator_id",
","... | 43.285714 | 0.009709 |
def find_point_in_section_list(point, section_list):
"""Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 3... | [
"def",
"find_point_in_section_list",
"(",
"point",
",",
"section_list",
")",
":",
"if",
"point",
"<",
"section_list",
"[",
"0",
"]",
"or",
"point",
">",
"section_list",
"[",
"-",
"1",
"]",
":",
"return",
"None",
"if",
"point",
"in",
"section_list",
":",
... | 32.68 | 0.000594 |
def boundary_maximum_division(graph, xxx_todo_changeme5):
r"""
Boundary term processing adjacent voxels maximum value using a division relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
The same as `bound... | [
"def",
"boundary_maximum_division",
"(",
"graph",
",",
"xxx_todo_changeme5",
")",
":",
"(",
"gradient_image",
",",
"sigma",
",",
"spacing",
")",
"=",
"xxx_todo_changeme5",
"gradient_image",
"=",
"scipy",
".",
"asarray",
"(",
"gradient_image",
")",
"def",
"boundary... | 38.837209 | 0.008178 |
def findUiActions( widget ):
"""
Looks up actions for the inputed widget based on naming convention.
:param widget | <QWidget>
:return [<QAction>, ..]
"""
import_qt(globals())
output = []
for action in widget.findChildren(QtGui.QAction):
name =... | [
"def",
"findUiActions",
"(",
"widget",
")",
":",
"import_qt",
"(",
"globals",
"(",
")",
")",
"output",
"=",
"[",
"]",
"for",
"action",
"in",
"widget",
".",
"findChildren",
"(",
"QtGui",
".",
"QAction",
")",
":",
"name",
"=",
"nativestring",
"(",
"actio... | 29.0625 | 0.016667 |
def range_per(self):
""" Range percentage
計算最新日之漲跌幅度百分比
"""
rp = float((self.raw_data[-1] - self.raw_data[-2]) / self.raw_data[-2] * 100)
return rp | [
"def",
"range_per",
"(",
"self",
")",
":",
"rp",
"=",
"float",
"(",
"(",
"self",
".",
"raw_data",
"[",
"-",
"1",
"]",
"-",
"self",
".",
"raw_data",
"[",
"-",
"2",
"]",
")",
"/",
"self",
".",
"raw_data",
"[",
"-",
"2",
"]",
"*",
"100",
")",
... | 27.666667 | 0.011696 |
def cut(self, sentence, cut_all=False, HMM=True):
'''
The main function that segments an entire sentence that contains
Chinese characters into separated words.
Parameter:
- sentence: The str(unicode) to be segmented.
- cut_all: Model type. True for full pattern, ... | [
"def",
"cut",
"(",
"self",
",",
"sentence",
",",
"cut_all",
"=",
"False",
",",
"HMM",
"=",
"True",
")",
":",
"sentence",
"=",
"strdecode",
"(",
"sentence",
")",
"if",
"cut_all",
":",
"re_han",
"=",
"re_han_cut_all",
"re_skip",
"=",
"re_skip_cut_all",
"el... | 32.512195 | 0.002185 |
def pickle_all(self, path):
"""Back up entire JSS to a Python Pickle.
For each object type, retrieve all objects, and then pickle
the entire smorgasbord. This will almost certainly take a long
time!
Pickling is Python's method for serializing/deserializing
Python object... | [
"def",
"pickle_all",
"(",
"self",
",",
"path",
")",
":",
"all_search_methods",
"=",
"[",
"(",
"name",
",",
"self",
".",
"__getattribute__",
"(",
"name",
")",
")",
"for",
"name",
"in",
"dir",
"(",
"self",
")",
"if",
"name",
"[",
"0",
"]",
".",
"isup... | 46.611111 | 0.001751 |
def Seek(self, offset, whence=os.SEEK_SET):
"""Moves the reading cursor."""
if whence == os.SEEK_SET:
self._offset = offset
elif whence == os.SEEK_CUR:
self._offset += offset
elif whence == os.SEEK_END:
self._offset = self._length + offset
else:
raise ValueError("Invalid whe... | [
"def",
"Seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"os",
".",
"SEEK_SET",
")",
":",
"if",
"whence",
"==",
"os",
".",
"SEEK_SET",
":",
"self",
".",
"_offset",
"=",
"offset",
"elif",
"whence",
"==",
"os",
".",
"SEEK_CUR",
":",
"self",
"."... | 30.636364 | 0.014409 |
def watch(self, filepath, func=None, delay=None, ignore=None):
"""Add the given filepath for watcher list.
Once you have intialized a server, watch file changes before
serve the server::
server.watch('static/*.stylus', 'make static')
def alert():
print('... | [
"def",
"watch",
"(",
"self",
",",
"filepath",
",",
"func",
"=",
"None",
",",
"delay",
"=",
"None",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"string_types",
")",
":",
"cmd",
"=",
"func",
"func",
"=",
"shell",
"(",
... | 41.793103 | 0.001613 |
def index_humansorted(seq, key=None, reverse=False, alg=ns.DEFAULT):
"""
This is a wrapper around ``index_natsorted(seq, alg=ns.LOCALE)``.
Parameters
----------
seq: iterable
The input to sort.
key: callable, optional
A key used to determine how to sort each element of the sequ... | [
"def",
"index_humansorted",
"(",
"seq",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"alg",
"=",
"ns",
".",
"DEFAULT",
")",
":",
"return",
"index_natsorted",
"(",
"seq",
",",
"key",
",",
"reverse",
",",
"alg",
"|",
"ns",
".",
"LOCALE",... | 26.659574 | 0.00077 |
def next(self, timeout=0):
"""Return empty unless new data is ready for the client.
Arguments:
timeout: Default timeout=0 range zero to float specifies a time-out as a floating point
number in seconds. Will sit and wait for timeout seconds. When the timeout argument is omitted
... | [
"def",
"next",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"try",
":",
"waitin",
",",
"_waitout",
",",
"_waiterror",
"=",
"select",
".",
"select",
"(",
"(",
"self",
".",
"streamSock",
",",
")",
",",
"(",
")",
",",
"(",
")",
",",
"timeout",
... | 52.666667 | 0.009326 |
def CopyToDict(self):
"""Copies the attribute container to a dictionary.
Returns:
dict[str, object]: attribute values per name.
"""
dictionary = {}
for attribute_name, attribute_value in self.GetAttributes():
if attribute_value is None:
continue
dictionary[attribute_name]... | [
"def",
"CopyToDict",
"(",
"self",
")",
":",
"dictionary",
"=",
"{",
"}",
"for",
"attribute_name",
",",
"attribute_value",
"in",
"self",
".",
"GetAttributes",
"(",
")",
":",
"if",
"attribute_value",
"is",
"None",
":",
"continue",
"dictionary",
"[",
"attribute... | 24.857143 | 0.00831 |
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_... | [
"def",
"get",
"(",
"path",
")",
":",
"file_path",
"=",
"__get_docker_file_path",
"(",
"path",
")",
"if",
"file_path",
"is",
"None",
":",
"return",
"__standardize_result",
"(",
"False",
",",
"'Path {} is not present'",
".",
"format",
"(",
"path",
")",
",",
"N... | 30.111111 | 0.001192 |
def _values(self):
"""Getter for series values (flattened)"""
return [abs(val) for val in super(Dot, self)._values if val != 0] | [
"def",
"_values",
"(",
"self",
")",
":",
"return",
"[",
"abs",
"(",
"val",
")",
"for",
"val",
"in",
"super",
"(",
"Dot",
",",
"self",
")",
".",
"_values",
"if",
"val",
"!=",
"0",
"]"
] | 47 | 0.013986 |
def Clapeyron(T, Tc, Pc, dZ=1, Psat=101325):
r'''Calculates enthalpy of vaporization at arbitrary temperatures using the
Clapeyron equation.
The enthalpy of vaporization is given by:
.. math::
\Delta H_{vap} = RT \Delta Z \frac{\ln (P_c/Psat)}{(1-T_{r})}
Parameters
----------
T : ... | [
"def",
"Clapeyron",
"(",
"T",
",",
"Tc",
",",
"Pc",
",",
"dZ",
"=",
"1",
",",
"Psat",
"=",
"101325",
")",
":",
"Tr",
"=",
"T",
"/",
"Tc",
"return",
"R",
"*",
"T",
"*",
"dZ",
"*",
"log",
"(",
"Pc",
"/",
"Psat",
")",
"/",
"(",
"1.",
"-",
... | 26.769231 | 0.001386 |
def reads_overlapping_variants(variants, samfile, **kwargs):
"""
Generates sequence of tuples, each containing a variant paired with
a list of AlleleRead objects.
Parameters
----------
variants : varcode.VariantCollection
samfile : pysam.AlignmentFile
use_duplicate_reads : bool
... | [
"def",
"reads_overlapping_variants",
"(",
"variants",
",",
"samfile",
",",
"*",
"*",
"kwargs",
")",
":",
"chromosome_names",
"=",
"set",
"(",
"samfile",
".",
"references",
")",
"for",
"variant",
"in",
"variants",
":",
"# I imagine the conversation went like this:",
... | 34.553191 | 0.000599 |
def sum_transactions(transactions):
""" Sums transactions into a total of remaining vacation days. """
workdays_per_year = 250
previous_date = None
rate = 0
day_sum = 0
for transaction in transactions:
date, action, value = _parse_transaction_entry(transaction)
if previous_date i... | [
"def",
"sum_transactions",
"(",
"transactions",
")",
":",
"workdays_per_year",
"=",
"250",
"previous_date",
"=",
"None",
"rate",
"=",
"0",
"day_sum",
"=",
"0",
"for",
"transaction",
"in",
"transactions",
":",
"date",
",",
"action",
",",
"value",
"=",
"_parse... | 31.92 | 0.002433 |
def dropout_mask(x:Tensor, sz:Collection[int], p:float):
"Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element."
return x.new(*sz).bernoulli_(1-p).div_(1-p) | [
"def",
"dropout_mask",
"(",
"x",
":",
"Tensor",
",",
"sz",
":",
"Collection",
"[",
"int",
"]",
",",
"p",
":",
"float",
")",
":",
"return",
"x",
".",
"new",
"(",
"*",
"sz",
")",
".",
"bernoulli_",
"(",
"1",
"-",
"p",
")",
".",
"div_",
"(",
"1"... | 69.666667 | 0.023697 |
def find_string_in_dict_or_list(i):
"""
Input: {
dict - dictionary 1
(search_string) - search string
(ignore_case) - ignore case of letters
}
Output: {
return - return code = 0, if successful
... | [
"def",
"find_string_in_dict_or_list",
"(",
"i",
")",
":",
"d",
"=",
"i",
".",
"get",
"(",
"'dict'",
",",
"{",
"}",
")",
"found",
"=",
"'no'",
"wc",
"=",
"False",
"ss",
"=",
"i",
".",
"get",
"(",
"'search_string'",
",",
"''",
")",
"if",
"ss",
".",... | 23.821429 | 0.043916 |
def _speak_as(
self,
element,
regular_expression,
data_property_value,
operation
):
"""
Execute a operation by regular expression for element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
... | [
"def",
"_speak_as",
"(",
"self",
",",
"element",
",",
"regular_expression",
",",
"data_property_value",
",",
"operation",
")",
":",
"children",
"=",
"[",
"]",
"pattern",
"=",
"re",
".",
"compile",
"(",
"regular_expression",
")",
"content",
"=",
"element",
".... | 33.386364 | 0.001984 |
def generate_path_parameters_validator(api_path, path_parameters, context):
"""
Generates a validator function that given a path, validates that it against
the path parameters
"""
path_parameter_validator = functools.partial(
validate_path_parameters,
api_path=api_path,
path_... | [
"def",
"generate_path_parameters_validator",
"(",
"api_path",
",",
"path_parameters",
",",
"context",
")",
":",
"path_parameter_validator",
"=",
"functools",
".",
"partial",
"(",
"validate_path_parameters",
",",
"api_path",
"=",
"api_path",
",",
"path_parameters",
"=",
... | 33.583333 | 0.002415 |
def form_invalid(self, post_form, attachment_formset, poll_option_formset, **kwargs):
""" Processes invalid forms. """
poll_errors = [k for k in post_form.errors.keys() if k.startswith('poll_')]
if (
poll_errors or
(
poll_option_formset and
... | [
"def",
"form_invalid",
"(",
"self",
",",
"post_form",
",",
"attachment_formset",
",",
"poll_option_formset",
",",
"*",
"*",
"kwargs",
")",
":",
"poll_errors",
"=",
"[",
"k",
"for",
"k",
"in",
"post_form",
".",
"errors",
".",
"keys",
"(",
")",
"if",
"k",
... | 43.466667 | 0.009009 |
def _xml_to_dict(xml):
'''
Helper function to covert xml into a data dictionary.
xml
The xml data to convert.
'''
dicts = {}
for item in xml:
key = item.tag.lower()
idx = 1
while key in dicts:
key += six.text_type(idx)
idx += 1
if ... | [
"def",
"_xml_to_dict",
"(",
"xml",
")",
":",
"dicts",
"=",
"{",
"}",
"for",
"item",
"in",
"xml",
":",
"key",
"=",
"item",
".",
"tag",
".",
"lower",
"(",
")",
"idx",
"=",
"1",
"while",
"key",
"in",
"dicts",
":",
"key",
"+=",
"six",
".",
"text_ty... | 21.5 | 0.002227 |
def extract_citation_context(self, n_words=20):
"""Generate a dictionary of all bib keys in the document (and input
documents), with rich of metadata about the context of each
citation in the document.
For example, suppose ``'Sick:2014'`` is cited twice within a document.
Then t... | [
"def",
"extract_citation_context",
"(",
"self",
",",
"n_words",
"=",
"20",
")",
":",
"bib_keys",
"=",
"defaultdict",
"(",
"list",
")",
"# Get bib keys in this document",
"for",
"match",
"in",
"texutils",
".",
"cite_pattern",
".",
"finditer",
"(",
"self",
".",
... | 40.461538 | 0.000742 |
def save_figure(self,event=None, transparent=True, dpi=600):
""" save figure image to file"""
if self.panel is not None:
self.panel.save_figure(event=event,
transparent=transparent, dpi=dpi) | [
"def",
"save_figure",
"(",
"self",
",",
"event",
"=",
"None",
",",
"transparent",
"=",
"True",
",",
"dpi",
"=",
"600",
")",
":",
"if",
"self",
".",
"panel",
"is",
"not",
"None",
":",
"self",
".",
"panel",
".",
"save_figure",
"(",
"event",
"=",
"eve... | 49.8 | 0.011858 |
def load(steps, reload=False):
"""
safely load steps in place, excluding those that fail
Args:
steps: the steps to load
"""
# work on collections by default for fewer isinstance() calls per call to load()
if reload:
_STEP_CACHE.clear()
if callable(steps):
steps = ste... | [
"def",
"load",
"(",
"steps",
",",
"reload",
"=",
"False",
")",
":",
"# work on collections by default for fewer isinstance() calls per call to load()",
"if",
"reload",
":",
"_STEP_CACHE",
".",
"clear",
"(",
")",
"if",
"callable",
"(",
"steps",
")",
":",
"steps",
"... | 26.774194 | 0.002326 |
def _default_pprint(obj, p, cycle):
"""
The default print function. Used if an object does not provide one and
it's none of the builtin objects.
"""
klass = getattr(obj, '__class__', None) or type(obj)
if getattr(klass, '__repr__', None) not in _baseclass_reprs:
# A user-provided repr.
... | [
"def",
"_default_pprint",
"(",
"obj",
",",
"p",
",",
"cycle",
")",
":",
"klass",
"=",
"getattr",
"(",
"obj",
",",
"'__class__'",
",",
"None",
")",
"or",
"type",
"(",
"obj",
")",
"if",
"getattr",
"(",
"klass",
",",
"'__repr__'",
",",
"None",
")",
"n... | 31.027778 | 0.000868 |
def combine_results(self, results):
"""Combine results from different batches of filtering"""
result = {}
for key in results[0]:
result[key] = numpy.concatenate([r[key] for r in results])
return result | [
"def",
"combine_results",
"(",
"self",
",",
"results",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"results",
"[",
"0",
"]",
":",
"result",
"[",
"key",
"]",
"=",
"numpy",
".",
"concatenate",
"(",
"[",
"r",
"[",
"key",
"]",
"for",
"r",
... | 40 | 0.008163 |
def set_server(self, wsgi_app, fnc_serve=None):
"""
figures out how the wsgi application is to be served
according to config
"""
self.set_wsgi_app(wsgi_app)
ssl_config = self.get_config("ssl")
ssl_context = {}
if self.get_config("server") == "gevent":
... | [
"def",
"set_server",
"(",
"self",
",",
"wsgi_app",
",",
"fnc_serve",
"=",
"None",
")",
":",
"self",
".",
"set_wsgi_app",
"(",
"wsgi_app",
")",
"ssl_config",
"=",
"self",
".",
"get_config",
"(",
"\"ssl\"",
")",
"ssl_context",
"=",
"{",
"}",
"if",
"self",
... | 26.071429 | 0.00132 |
def _remove_curly_braces(text):
"""Remove everything in curly braces.
Curly braces may be nested, so we keep track of depth.
Args:
text: a string
Returns:
a string
"""
current_pos = 0
depth = 0
ret = ""
for match in re.finditer("[{}]", text):
if depth == 0:
ret += text[current_pos:... | [
"def",
"_remove_curly_braces",
"(",
"text",
")",
":",
"current_pos",
"=",
"0",
"depth",
"=",
"0",
"ret",
"=",
"\"\"",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"\"[{}]\"",
",",
"text",
")",
":",
"if",
"depth",
"==",
"0",
":",
"ret",
"+=",
"... | 22.84 | 0.016807 |
def _api_decrypt():
'''
Return the response dictionary from the KMS decrypt API call.
'''
kms = _kms()
data_key = _cfg_data_key()
try:
return kms.decrypt(CiphertextBlob=data_key)
except botocore.exceptions.ClientError as orig_exc:
error_code = orig_exc.response.get('Error', {... | [
"def",
"_api_decrypt",
"(",
")",
":",
"kms",
"=",
"_kms",
"(",
")",
"data_key",
"=",
"_cfg_data_key",
"(",
")",
"try",
":",
"return",
"kms",
".",
"decrypt",
"(",
"CiphertextBlob",
"=",
"data_key",
")",
"except",
"botocore",
".",
"exceptions",
".",
"Clien... | 38.666667 | 0.001684 |
def get_repo_info(repo_name, profile='github', ignore_cache=False):
'''
Return information for a given repo.
.. versionadded:: 2016.11.0
repo_name
The name of the repository.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. co... | [
"def",
"get_repo_info",
"(",
"repo_name",
",",
"profile",
"=",
"'github'",
",",
"ignore_cache",
"=",
"False",
")",
":",
"org_name",
"=",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
"key",
"=",
"\"github.{0}:{1}:repo_info\"",
".",
"format",
"(",
... | 30.367347 | 0.001302 |
def checkcache(filename=None):
"""Discard cache entries that are out of date.
(This is not checked upon each call!)"""
if filename is None:
filenames = cache.keys()
else:
if filename in cache:
filenames = [filename]
else:
return
for filename in filen... | [
"def",
"checkcache",
"(",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filenames",
"=",
"cache",
".",
"keys",
"(",
")",
"else",
":",
"if",
"filename",
"in",
"cache",
":",
"filenames",
"=",
"[",
"filename",
"]",
"else",
":"... | 29.043478 | 0.001449 |
def get_value(self, value):
""" Replace variable names with placeholders (e.g. ':v1') """
next_key = ":v%d" % self._next_value
self._next_value += 1
self._values[next_key] = value
return next_key | [
"def",
"get_value",
"(",
"self",
",",
"value",
")",
":",
"next_key",
"=",
"\":v%d\"",
"%",
"self",
".",
"_next_value",
"self",
".",
"_next_value",
"+=",
"1",
"self",
".",
"_values",
"[",
"next_key",
"]",
"=",
"value",
"return",
"next_key"
] | 38.333333 | 0.008511 |
def effective_n(mcmc):
"""
Args:
mcmc (MCMCResults): Pre-sliced MCMC samples to compute diagnostics for.
"""
if mcmc.n_chains < 2:
raise ValueError(
'Calculation of effective sample size requires multiple chains '
'of the same length.')
def get_neff(x):
... | [
"def",
"effective_n",
"(",
"mcmc",
")",
":",
"if",
"mcmc",
".",
"n_chains",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'Calculation of effective sample size requires multiple chains '",
"'of the same length.'",
")",
"def",
"get_neff",
"(",
"x",
")",
":",
"\"\"\"Com... | 36.614035 | 0.0014 |
def reset(self):
"""Reset metric counter."""
self._positions = []
self._line = 1
self._curr = None # current scope we are analyzing
self._scope = 0
self.language = None | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_positions",
"=",
"[",
"]",
"self",
".",
"_line",
"=",
"1",
"self",
".",
"_curr",
"=",
"None",
"# current scope we are analyzing",
"self",
".",
"_scope",
"=",
"0",
"self",
".",
"language",
"=",
"None... | 30.142857 | 0.009217 |
def build_attrs(self, base_attrs, extra_attrs=None, **kwargs):
"""
Helper function for building an attribute dictionary.
This is combination of the same method from Django<=1.10 and Django1.11+
"""
attrs = dict(base_attrs, **kwargs)
if extra_attrs:
attrs.upda... | [
"def",
"build_attrs",
"(",
"self",
",",
"base_attrs",
",",
"extra_attrs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"dict",
"(",
"base_attrs",
",",
"*",
"*",
"kwargs",
")",
"if",
"extra_attrs",
":",
"attrs",
".",
"update",
"(",
"e... | 34.7 | 0.008427 |
def _get_result_paths(self, data):
""" Set the result paths
"""
# Swarm OTU map (mandatory output)
return {'OtuMap': ResultPath(Path=self.Parameters['-o'].Value,
IsWritten=True)} | [
"def",
"_get_result_paths",
"(",
"self",
",",
"data",
")",
":",
"# Swarm OTU map (mandatory output)",
"return",
"{",
"'OtuMap'",
":",
"ResultPath",
"(",
"Path",
"=",
"self",
".",
"Parameters",
"[",
"'-o'",
"]",
".",
"Value",
",",
"IsWritten",
"=",
"True",
")... | 34.571429 | 0.008065 |
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
... | [
"def",
"get_operation_status",
"(",
"kwargs",
"=",
"None",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_instance function must be called with -f or --function.'",
... | 24.102564 | 0.002045 |
def main(func=None, argv=None, input_stream=stdin, output_stream=stdout,
error_stream=stderr, exit=True):
"""runs a function as a command.
runs a function as a command - reading input from `input_stream`, writing
output into `output_stream` and providing arguments from `argv`.
Example Usage:
... | [
"def",
"main",
"(",
"func",
"=",
"None",
",",
"argv",
"=",
"None",
",",
"input_stream",
"=",
"stdin",
",",
"output_stream",
"=",
"stdout",
",",
"error_stream",
"=",
"stderr",
",",
"exit",
"=",
"True",
")",
":",
"executor",
"=",
"executors",
".",
"get_f... | 36.891892 | 0.000714 |
def summarize_ranges(array):
"""
:type array: List[int]
:rtype: List[]
"""
res = []
if len(array) == 1:
return [str(array[0])]
i = 0
while i < len(array):
num = array[i]
while i + 1 < len(array) and array[i + 1] - array[i] == 1:
i += 1
if array... | [
"def",
"summarize_ranges",
"(",
"array",
")",
":",
"res",
"=",
"[",
"]",
"if",
"len",
"(",
"array",
")",
"==",
"1",
":",
"return",
"[",
"str",
"(",
"array",
"[",
"0",
"]",
")",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"array",
")",
... | 22.736842 | 0.002222 |
def setModelData(self, editor, model, index):
"""
Updates the item with the new data value.
:param editor | <QtGui.QWidget>
model | <QtGui.QModel>
index | <QtGui.QModelIndex>
"""
value = editor.currentText()
... | [
"def",
"setModelData",
"(",
"self",
",",
"editor",
",",
"model",
",",
"index",
")",
":",
"value",
"=",
"editor",
".",
"currentText",
"(",
")",
"model",
".",
"setData",
"(",
"index",
",",
"wrapVariant",
"(",
"value",
")",
")"
] | 35.5 | 0.008242 |
def parse_v3_signing_block(self):
"""
Parse the V2 signing block and extract all features
"""
self._v3_signing_data = []
# calling is_signed_v3 should also load the signature, if any
if not self.is_signed_v3():
return
block_bytes = self._v2_blocks[s... | [
"def",
"parse_v3_signing_block",
"(",
"self",
")",
":",
"self",
".",
"_v3_signing_data",
"=",
"[",
"]",
"# calling is_signed_v3 should also load the signature, if any",
"if",
"not",
"self",
".",
"is_signed_v3",
"(",
")",
":",
"return",
"block_bytes",
"=",
"self",
".... | 35.877551 | 0.001384 |
def vectorized_beta(dependents, independent, allowed_missing, out=None):
"""
Compute slopes of linear regressions between columns of ``dependents`` and
``independent``.
Parameters
----------
dependents : np.array[N, M]
Array with columns of data to be regressed against ``independent``.
... | [
"def",
"vectorized_beta",
"(",
"dependents",
",",
"independent",
",",
"allowed_missing",
",",
"out",
"=",
"None",
")",
":",
"# Cache these as locals since we're going to call them multiple times.",
"nan",
"=",
"np",
".",
"nan",
"isnan",
"=",
"np",
".",
"isnan",
"N",... | 34.957447 | 0.000296 |
def uninitialize_ui(self):
"""
Uninitializes the Component ui.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Uninitializing '{0}' Component ui.".format(self.__class__.__name__))
# Signals / Slots.
self.Port_spinBox.valueChanged.disconnect(se... | [
"def",
"uninitialize_ui",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Uninitializing '{0}' Component ui.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"# Signals / Slots.",
"self",
".",
"Port_spinBox",
".",
"valueChanged... | 38.473684 | 0.008011 |
def get_sdr_data_helper(reserve_fn, get_fn, record_id, reservation_id=None):
"""Helper function to retrieve the sdr data using the specified
functions.
This can be used for SDRs from the Sensor Device or form the SDR
repository.
"""
if reservation_id is None:
reservation_id = reserve_f... | [
"def",
"get_sdr_data_helper",
"(",
"reserve_fn",
",",
"get_fn",
",",
"record_id",
",",
"reservation_id",
"=",
"None",
")",
":",
"if",
"reservation_id",
"is",
"None",
":",
"reservation_id",
"=",
"reserve_fn",
"(",
")",
"(",
"next_id",
",",
"data",
")",
"=",
... | 29.192308 | 0.000637 |
def urlopen(self, method, url, body=None, headers=None, **kwargs):
"""Implementation of urllib3's urlopen."""
# pylint: disable=arguments-differ
# We use kwargs to collect additional args that we don't need to
# introspect here. However, we do explicitly collect the two
# positio... | [
"def",
"urlopen",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=arguments-differ",
"# We use kwargs to collect additional args that we don't need to",
"# introspect ... | 42.102041 | 0.000947 |
def series2df(Series, layer=2, split_sign = '_'):
"""expect pass a series that each row is string formated Json data with the same structure"""
try:
Series.columns
Series = Series.iloc[:,0]
except:
pass
def _helper(x, layer=2):
try:
return flatten_dict(as... | [
"def",
"series2df",
"(",
"Series",
",",
"layer",
"=",
"2",
",",
"split_sign",
"=",
"'_'",
")",
":",
"try",
":",
"Series",
".",
"columns",
"Series",
"=",
"Series",
".",
"iloc",
"[",
":",
",",
"0",
"]",
"except",
":",
"pass",
"def",
"_helper",
"(",
... | 29.3 | 0.021488 |
def _iter_avro_blocks(fo, header, codec, writer_schema, reader_schema):
"""Return iterator over avro blocks."""
sync_marker = header['sync']
read_block = BLOCK_READERS.get(codec)
if not read_block:
raise ValueError('Unrecognized codec: %r' % codec)
while True:
offset = fo.tell()
... | [
"def",
"_iter_avro_blocks",
"(",
"fo",
",",
"header",
",",
"codec",
",",
"writer_schema",
",",
"reader_schema",
")",
":",
"sync_marker",
"=",
"header",
"[",
"'sync'",
"]",
"read_block",
"=",
"BLOCK_READERS",
".",
"get",
"(",
"codec",
")",
"if",
"not",
"rea... | 25.92 | 0.001488 |
def query_version(stream: aioxmpp.stream.StanzaStream,
target: aioxmpp.JID) -> version_xso.Query:
"""
Query the software version of an entity.
:param stream: A stanza stream to send the query on.
:type stream: :class:`aioxmpp.stream.StanzaStream`
:param target: The address of the ... | [
"def",
"query_version",
"(",
"stream",
":",
"aioxmpp",
".",
"stream",
".",
"StanzaStream",
",",
"target",
":",
"aioxmpp",
".",
"JID",
")",
"->",
"version_xso",
".",
"Query",
":",
"return",
"(",
"yield",
"from",
"stream",
".",
"send",
"(",
"aioxmpp",
".",... | 38.107143 | 0.000914 |
def generate_basis(z):
"""
Generate an arbitrary basis (also known as a coordinate frame)
from a given z-axis vector.
Parameters
----------
z: (3,) float
A vector along the positive z-axis
Returns
-------
x : (3,) float
Vector along x axis
y : (3,) float
Vecto... | [
"def",
"generate_basis",
"(",
"z",
")",
":",
"# get a copy of input vector",
"z",
"=",
"np",
".",
"array",
"(",
"z",
",",
"dtype",
"=",
"np",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"# must be a 3D vector",
"if",
"z",
".",
"shape",
"!=",
"(",
"3... | 26 | 0.000862 |
def filter_mean(matrix, top):
"""Filter genes in an expression matrix by mean expression.
Parameters
----------
matrix: ExpMatrix
The expression matrix.
top: int
The number of genes to retain.
Returns
-------
ExpMatrix
The filtered expression matrix.
"""
... | [
"def",
"filter_mean",
"(",
"matrix",
",",
"top",
")",
":",
"assert",
"isinstance",
"(",
"matrix",
",",
"ExpMatrix",
")",
"assert",
"isinstance",
"(",
"top",
",",
"int",
")",
"if",
"top",
">=",
"matrix",
".",
"p",
":",
"logger",
".",
"warning",
"(",
"... | 23.096774 | 0.00134 |
def p_expr_label(p):
""" expr : ID
"""
p[0] = Expr.makenode(Container(MEMORY.get_label(p[1], p.lineno(1)), p.lineno(1))) | [
"def",
"p_expr_label",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Expr",
".",
"makenode",
"(",
"Container",
"(",
"MEMORY",
".",
"get_label",
"(",
"p",
"[",
"1",
"]",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")",
",",
"p",
".",
"lineno",
"("... | 32.25 | 0.015152 |
def delete(self, ignore=None):
"""Yield tuple with deleted index name and responses from a client."""
ignore = ignore or []
def _delete(tree_or_filename, alias=None):
"""Delete indexes and aliases by walking DFS."""
if alias:
yield alias, self.client.indi... | [
"def",
"delete",
"(",
"self",
",",
"ignore",
"=",
"None",
")",
":",
"ignore",
"=",
"ignore",
"or",
"[",
"]",
"def",
"_delete",
"(",
"tree_or_filename",
",",
"alias",
"=",
"None",
")",
":",
"\"\"\"Delete indexes and aliases by walking DFS.\"\"\"",
"if",
"alias"... | 36.730769 | 0.002041 |
def update(self, roomId, title=None, **request_parameters):
"""Update details for a room, by ID.
Args:
roomId(basestring): The room ID.
title(basestring): A user-friendly name for the room.
**request_parameters: Additional request parameters (provides
... | [
"def",
"update",
"(",
"self",
",",
"roomId",
",",
"title",
"=",
"None",
",",
"*",
"*",
"request_parameters",
")",
":",
"check_type",
"(",
"roomId",
",",
"basestring",
",",
"may_be_none",
"=",
"False",
")",
"check_type",
"(",
"roomId",
",",
"basestring",
... | 34.83871 | 0.001802 |
def get_vaults_by_query(self, vault_query):
"""Gets a list of ``Vault`` objects matching the given search.
arg: vault_query (osid.authorization.VaultQuery): the vault
query
return: (osid.authorization.VaultList) - the returned
``VaultList``
raise: Nul... | [
"def",
"get_vaults_by_query",
"(",
"self",
",",
"vault_query",
")",
":",
"# Implemented from template for",
"# osid.resource.BinQuerySession.get_bins_by_query_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_sessio... | 48.12 | 0.00163 |
def update(self, forecasts, observations):
"""
Update the statistics with forecasts and observations.
Args:
forecasts: The discrete Cumulative Distribution Functions of
observations:
"""
if len(observations.shape) == 1:
obs_cdfs = np.zeros((ob... | [
"def",
"update",
"(",
"self",
",",
"forecasts",
",",
"observations",
")",
":",
"if",
"len",
"(",
"observations",
".",
"shape",
")",
"==",
"1",
":",
"obs_cdfs",
"=",
"np",
".",
"zeros",
"(",
"(",
"observations",
".",
"size",
",",
"self",
".",
"thresho... | 42.315789 | 0.002433 |
def get_userlist(self):
"""
This collects all the users with open files on the system, and filters
based on the variables user_include and user_exclude
"""
# convert user/group lists to arrays if strings
if isinstance(self.config['user_include'], basestring):
sel... | [
"def",
"get_userlist",
"(",
"self",
")",
":",
"# convert user/group lists to arrays if strings",
"if",
"isinstance",
"(",
"self",
".",
"config",
"[",
"'user_include'",
"]",
",",
"basestring",
")",
":",
"self",
".",
"config",
"[",
"'user_include'",
"]",
"=",
"se... | 44.272727 | 0.000502 |
def populateFromFile(self, dataUrl):
"""
Populates the instance variables of this FeatureSet from the specified
data URL.
"""
self._dbFilePath = dataUrl
self._db = Gff3DbBackend(self._dbFilePath) | [
"def",
"populateFromFile",
"(",
"self",
",",
"dataUrl",
")",
":",
"self",
".",
"_dbFilePath",
"=",
"dataUrl",
"self",
".",
"_db",
"=",
"Gff3DbBackend",
"(",
"self",
".",
"_dbFilePath",
")"
] | 33.857143 | 0.00823 |
def loss_value(self, x_data, y_true, y_pred):
""" Calculate a value of loss function """
y_pred = y_pred.view(-1, y_pred.size(2))
y_true = y_true.view(-1).to(torch.long)
return F.nll_loss(y_pred, y_true) | [
"def",
"loss_value",
"(",
"self",
",",
"x_data",
",",
"y_true",
",",
"y_pred",
")",
":",
"y_pred",
"=",
"y_pred",
".",
"view",
"(",
"-",
"1",
",",
"y_pred",
".",
"size",
"(",
"2",
")",
")",
"y_true",
"=",
"y_true",
".",
"view",
"(",
"-",
"1",
"... | 46.2 | 0.008511 |
def _CaptureEnvironmentLabels(self):
"""Captures information about the environment, if possible."""
if 'labels' not in self.breakpoint:
self.breakpoint['labels'] = {}
if callable(breakpoint_labels_collector):
for (key, value) in six.iteritems(breakpoint_labels_collector()):
self.breakpo... | [
"def",
"_CaptureEnvironmentLabels",
"(",
"self",
")",
":",
"if",
"'labels'",
"not",
"in",
"self",
".",
"breakpoint",
":",
"self",
".",
"breakpoint",
"[",
"'labels'",
"]",
"=",
"{",
"}",
"if",
"callable",
"(",
"breakpoint_labels_collector",
")",
":",
"for",
... | 42.375 | 0.008671 |
def create_cud_from_task(task, placeholder_dict, prof=None):
"""
Purpose: Create a Compute Unit description based on the defined Task.
:arguments:
:task: EnTK Task object
:placeholder_dict: dictionary holding the values for placeholders
:return: ComputeUnitDescription
"""
try:... | [
"def",
"create_cud_from_task",
"(",
"task",
",",
"placeholder_dict",
",",
"prof",
"=",
"None",
")",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"'Creating CU from Task %s'",
"%",
"(",
"task",
".",
"uid",
")",
")",
"if",
"prof",
":",
"prof",
".",
"prof"... | 37.803279 | 0.002113 |
def show_distance_matrix(self):
"""!
@brief Shows gray visualization of U-matrix (distance matrix).
@see get_distance_matrix()
"""
distance_matrix = self.get_distance_matrix()
plt.imshow(distance_matrix, cmap = plt.get_cmap('hot'), inte... | [
"def",
"show_distance_matrix",
"(",
"self",
")",
":",
"distance_matrix",
"=",
"self",
".",
"get_distance_matrix",
"(",
")",
"plt",
".",
"imshow",
"(",
"distance_matrix",
",",
"cmap",
"=",
"plt",
".",
"get_cmap",
"(",
"'hot'",
")",
",",
"interpolation",
"=",
... | 30.923077 | 0.019324 |
def _get_postvalue_from_absoluteURI(url):
"""Bug [ 1513000 ] POST Request-URI not limited to "abs_path"
Request-URI = "*" | absoluteURI | abs_path | authority
Not a complete solution, but it seems to work with all known
implementations. ValueError thrown if bad uri.
"""
cache = _get_postva... | [
"def",
"_get_postvalue_from_absoluteURI",
"(",
"url",
")",
":",
"cache",
"=",
"_get_postvalue_from_absoluteURI",
".",
"cache",
"path",
"=",
"cache",
".",
"get",
"(",
"url",
",",
"''",
")",
"if",
"not",
"path",
":",
"scheme",
",",
"authpath",
"=",
"url",
".... | 38.625 | 0.011058 |
def IntegerMultiplication(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Multiplies one vertex by another
:param left: a vertex to be multiplied
:param right: a vertex to be multiplied
"""
return Integer(context.jvm_vie... | [
"def",
"IntegerMultiplication",
"(",
"left",
":",
"vertex_constructor_param_types",
",",
"right",
":",
"vertex_constructor_param_types",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Vertex",
":",
"return",
"Integer",
"(",
"context",
"... | 51.625 | 0.014286 |
def _load_steps(self, raw_steps):
""" load steps -> basically load all the datetime isoformats into datetimes """
for step in raw_steps:
if 'start' in step:
step['start'] = parser.parse(step['start'])
if 'stop' in step:
step['stop'] = parser.parse(... | [
"def",
"_load_steps",
"(",
"self",
",",
"raw_steps",
")",
":",
"for",
"step",
"in",
"raw_steps",
":",
"if",
"'start'",
"in",
"step",
":",
"step",
"[",
"'start'",
"]",
"=",
"parser",
".",
"parse",
"(",
"step",
"[",
"'start'",
"]",
")",
"if",
"'stop'",... | 43.875 | 0.00838 |
def total_value(self):
"""
[float]总权益
"""
return sum(account.total_value for account in six.itervalues(self._accounts)) | [
"def",
"total_value",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"account",
".",
"total_value",
"for",
"account",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"_accounts",
")",
")"
] | 29.4 | 0.019868 |
def clearAdvancedActions( self ):
"""
Clears out the advanced action map.
"""
self._advancedMap.clear()
margins = list(self.getContentsMargins())
margins[2] = 0
self.setContentsMargins(*margins) | [
"def",
"clearAdvancedActions",
"(",
"self",
")",
":",
"self",
".",
"_advancedMap",
".",
"clear",
"(",
")",
"margins",
"=",
"list",
"(",
"self",
".",
"getContentsMargins",
"(",
")",
")",
"margins",
"[",
"2",
"]",
"=",
"0",
"self",
".",
"setContentsMargins... | 31 | 0.023529 |
def scale(self, w=1.0, h=1.0):
"""Resizes the layer to the given width and height.
When width w or height h is a floating-point number,
scales percentual,
otherwise scales to the given size in pixels.
"""
from types import FloatType
w0, h0 = self.... | [
"def",
"scale",
"(",
"self",
",",
"w",
"=",
"1.0",
",",
"h",
"=",
"1.0",
")",
":",
"from",
"types",
"import",
"FloatType",
"w0",
",",
"h0",
"=",
"self",
".",
"img",
".",
"size",
"if",
"type",
"(",
"w",
")",
"==",
"FloatType",
":",
"w",
"=",
"... | 28.055556 | 0.019157 |
def is_local_port_open(port):
"""
Args:
port (int):
Returns:
bool:
References:
http://stackoverflow.com/questions/7436801/identifying-listening-ports-using-python
CommandLine:
python -m utool.util_web is_local_port_open --show
Example:
>>> # DISABLE_DO... | [
"def",
"is_local_port_open",
"(",
"port",
")",
":",
"import",
"socket",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"result",
"=",
"s",
".",
"connect_ex",
"(",
"(",
"'127.0.0.1'",
",",
"port",... | 27.576923 | 0.001348 |
def compress(raw_data):
"""Compress raw bytes with the filepack algorithm.
:param raw_data: an array of raw data bytes to compress
:rtype: a list of compressed bytes
"""
raw_data = bytearray(raw_data)
compressed_data = []
data_size = len(raw_data)
index = 0
next_bytes = [-1, -1, ... | [
"def",
"compress",
"(",
"raw_data",
")",
":",
"raw_data",
"=",
"bytearray",
"(",
"raw_data",
")",
"compressed_data",
"=",
"[",
"]",
"data_size",
"=",
"len",
"(",
"raw_data",
")",
"index",
"=",
"0",
"next_bytes",
"=",
"[",
"-",
"1",
",",
"-",
"1",
","... | 30.107527 | 0.000346 |
def check_new_round(self, hours=24, tournament=1):
"""Check if a new round has started within the last `hours`.
Args:
hours (int, optional): timeframe to consider, defaults to 24
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
bool:... | [
"def",
"check_new_round",
"(",
"self",
",",
"hours",
"=",
"24",
",",
"tournament",
"=",
"1",
")",
":",
"query",
"=",
"'''\n query($tournament: Int!) {\n rounds(tournament: $tournament\n number: 0) {\n number\n ... | 34.096774 | 0.00184 |
def from_params(cls, params):
"""Returns a list of MultipartParam objects from a sequence of
name, value pairs, MultipartParam instances,
or from a mapping of names to values
The values may be strings or file objects, or MultipartParam objects.
MultipartParam object names must m... | [
"def",
"from_params",
"(",
"cls",
",",
"params",
")",
":",
"if",
"hasattr",
"(",
"params",
",",
"'items'",
")",
":",
"params",
"=",
"params",
".",
"items",
"(",
")",
"retval",
"=",
"[",
"]",
"for",
"item",
"in",
"params",
":",
"if",
"isinstance",
"... | 37.882353 | 0.001514 |
def t_insert_dict_if_new(self, tblname, d, PKfields, fields=None):
'''A version of insertDictIfNew for transactions. This does not call commit.'''
SQL, values = self._insert_dict_if_new_inner(tblname, d, PKfields, fields=fields)
if SQL != False:
self.execute_select(SQL, parameters=va... | [
"def",
"t_insert_dict_if_new",
"(",
"self",
",",
"tblname",
",",
"d",
",",
"PKfields",
",",
"fields",
"=",
"None",
")",
":",
"SQL",
",",
"values",
"=",
"self",
".",
"_insert_dict_if_new_inner",
"(",
"tblname",
",",
"d",
",",
"PKfields",
",",
"fields",
"=... | 55.428571 | 0.01269 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.