text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def to_datetime(jdc):
'''Return a datetime for the input floating point Julian Day Count'''
year, month, day = gregorian.from_jd(jdc)
# in jdc: 0.0 = noon, 0.5 = midnight
# the 0.5 changes it to 0.0 = midnight, 0.5 = noon
frac = (jdc + 0.5) % 1
hours = int(24 * frac)
mfrac = frac * 24 - h... | [
"def",
"to_datetime",
"(",
"jdc",
")",
":",
"year",
",",
"month",
",",
"day",
"=",
"gregorian",
".",
"from_jd",
"(",
"jdc",
")",
"# in jdc: 0.0 = noon, 0.5 = midnight",
"# the 0.5 changes it to 0.0 = midnight, 0.5 = noon",
"frac",
"=",
"(",
"jdc",
"+",
"0.5",
")",... | 28.181818 | 21.818182 |
def mesh_nmasked(self):
"""
A 2D (masked) array of the number of masked pixels in each mesh.
Only meshes included in the background estimation are included.
The array is masked only if meshes were excluded.
"""
return self._make_2d_array(
np.ma.count_masked(s... | [
"def",
"mesh_nmasked",
"(",
"self",
")",
":",
"return",
"self",
".",
"_make_2d_array",
"(",
"np",
".",
"ma",
".",
"count_masked",
"(",
"self",
".",
"_data_sigclip",
",",
"axis",
"=",
"1",
")",
")"
] | 37.666667 | 17.888889 |
def delete_variant_by_id(cls, variant_id, **kwargs):
"""Delete Variant
Delete an instance of Variant by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_variant_by_id(variant_id,... | [
"def",
"delete_variant_by_id",
"(",
"cls",
",",
"variant_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_delete_variant_by_id_w... | 40.952381 | 19.619048 |
def NewDefaultAgency(self, **kwargs):
"""Create a new Agency object and make it the default agency for this Schedule"""
agency = self._gtfs_factory.Agency(**kwargs)
if not agency.agency_id:
agency.agency_id = util.FindUniqueId(self._agencies)
self._default_agency = agency
self.SetDefaultAgency... | [
"def",
"NewDefaultAgency",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"agency",
"=",
"self",
".",
"_gtfs_factory",
".",
"Agency",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"agency",
".",
"agency_id",
":",
"agency",
".",
"agency_id",
"=",
"util",
... | 48.25 | 13.875 |
def reply_to(self, message, text, **kwargs):
"""
Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)`
"""
return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) | [
"def",
"reply_to",
"(",
"self",
",",
"message",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"send_message",
"(",
"message",
".",
"chat",
".",
"id",
",",
"text",
",",
"reply_to_message_id",
"=",
"message",
".",
"message_id",
"... | 58.2 | 29.8 |
def _set(self, value):
"""Override setter, allow clearing cursor"""
super(AttachmentsField, self)._set(value)
self._cursor = None | [
"def",
"_set",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"AttachmentsField",
",",
"self",
")",
".",
"_set",
"(",
"value",
")",
"self",
".",
"_cursor",
"=",
"None"
] | 37.5 | 10 |
def relative_datetime(self):
"""Return human-readable relative time string."""
now = datetime.now(timezone.utc)
tense = "from now" if self.created_at > now else "ago"
return "{0} {1}".format(humanize.naturaldelta(now - self.created_at), tense) | [
"def",
"relative_datetime",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
"timezone",
".",
"utc",
")",
"tense",
"=",
"\"from now\"",
"if",
"self",
".",
"created_at",
">",
"now",
"else",
"\"ago\"",
"return",
"\"{0} {1}\"",
".",
"format",
... | 54.2 | 15.6 |
def get_extra_radiation(datetime_or_doy, solar_constant=1366.1,
method='spencer', epoch_year=2014, **kwargs):
"""
Determine extraterrestrial radiation from day of year.
Parameters
----------
datetime_or_doy : numeric, array, date, datetime, Timestamp, DatetimeIndex
D... | [
"def",
"get_extra_radiation",
"(",
"datetime_or_doy",
",",
"solar_constant",
"=",
"1366.1",
",",
"method",
"=",
"'spencer'",
",",
"epoch_year",
"=",
"2014",
",",
"*",
"*",
"kwargs",
")",
":",
"to_doy",
",",
"to_datetimeindex",
",",
"to_output",
"=",
"_handle_e... | 36.631579 | 24.578947 |
def perr(self, *args, **kwargs):
""" Console to STERR """
kwargs['file'] = self.err
self.print(*args, **kwargs)
sys.stderr.flush() | [
"def",
"perr",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'file'",
"]",
"=",
"self",
".",
"err",
"self",
".",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"sys",
".",
"stderr",
".",
"flush",
... | 31.6 | 6.8 |
def collect_fields(
ctx, # type: ExecutionContext
runtime_type, # type: GraphQLObjectType
selection_set, # type: SelectionSet
fields, # type: DefaultOrderedDict
prev_fragment_names, # type: Set[str]
):
# type: (...) -> DefaultOrderedDict
"""
Given a selectionSet, adds all of the fie... | [
"def",
"collect_fields",
"(",
"ctx",
",",
"# type: ExecutionContext",
"runtime_type",
",",
"# type: GraphQLObjectType",
"selection_set",
",",
"# type: SelectionSet",
"fields",
",",
"# type: DefaultOrderedDict",
"prev_fragment_names",
",",
"# type: Set[str]",
")",
":",
"# type... | 34.067797 | 20.338983 |
def _add_initial_value(self, data_id, value, initial_dist=0.0,
fringe=None, check_cutoff=None, no_call=None):
"""
Add initial values updating workflow, seen, and fringe.
:param fringe:
Heapq of closest available nodes.
:type fringe: list[(float | i... | [
"def",
"_add_initial_value",
"(",
"self",
",",
"data_id",
",",
"value",
",",
"initial_dist",
"=",
"0.0",
",",
"fringe",
"=",
"None",
",",
"check_cutoff",
"=",
"None",
",",
"no_call",
"=",
"None",
")",
":",
"# Namespace shortcuts for speed.",
"nodes",
",",
"s... | 34.307692 | 25.557692 |
def _remote_add(self):
"""Execute git remote add."""
self.repo.create_remote(
'origin',
'git@github.com:{username}/{repo}.git'.format(
username=self.metadata.username,
repo=self.metadata.name)) | [
"def",
"_remote_add",
"(",
"self",
")",
":",
"self",
".",
"repo",
".",
"create_remote",
"(",
"'origin'",
",",
"'git@github.com:{username}/{repo}.git'",
".",
"format",
"(",
"username",
"=",
"self",
".",
"metadata",
".",
"username",
",",
"repo",
"=",
"self",
"... | 37 | 10.285714 |
def to_docstring(kwargs, lpad=''):
"""Reconstruct a docstring from keyword argument info.
Basically reverses :func:`extract_kwargs`.
Parameters
----------
kwargs: list
Output from the extract_kwargs function
lpad: str, optional
Padding string (from the left).
Returns
-... | [
"def",
"to_docstring",
"(",
"kwargs",
",",
"lpad",
"=",
"''",
")",
":",
"buf",
"=",
"io",
".",
"StringIO",
"(",
")",
"for",
"name",
",",
"type_",
",",
"description",
"in",
"kwargs",
":",
"buf",
".",
"write",
"(",
"'%s%s: %s\\n'",
"%",
"(",
"lpad",
... | 25.972973 | 20.324324 |
def _merge(dts):
"""
merge multiple samples in one matrix
"""
df = pd.concat(dts)
ma = df.pivot(index='isomir', columns='sample', values='counts')
ma_mirna = ma
ma = ma.fillna(0)
ma_mirna['mirna'] = [m.split(":")[0] for m in ma.index.values]
ma_mirna = ma_mirna.groupby(['mirna']).su... | [
"def",
"_merge",
"(",
"dts",
")",
":",
"df",
"=",
"pd",
".",
"concat",
"(",
"dts",
")",
"ma",
"=",
"df",
".",
"pivot",
"(",
"index",
"=",
"'isomir'",
",",
"columns",
"=",
"'sample'",
",",
"values",
"=",
"'counts'",
")",
"ma_mirna",
"=",
"ma",
"ma... | 28.384615 | 16.076923 |
def shell():
"Open a shell"
from gui.tools.debug import Shell
shell = Shell()
shell.show()
return shell | [
"def",
"shell",
"(",
")",
":",
"from",
"gui",
".",
"tools",
".",
"debug",
"import",
"Shell",
"shell",
"=",
"Shell",
"(",
")",
"shell",
".",
"show",
"(",
")",
"return",
"shell"
] | 20.333333 | 20 |
def frame_indexing(frame, multi_index, level_i, indexing_type='label'):
"""Index dataframe based on one level of MultiIndex.
Arguments
---------
frame : pandas.DataFrame
The datafrme to select records from.
multi_index : pandas.MultiIndex
A pandas multiindex were one fo the levels i... | [
"def",
"frame_indexing",
"(",
"frame",
",",
"multi_index",
",",
"level_i",
",",
"indexing_type",
"=",
"'label'",
")",
":",
"if",
"indexing_type",
"==",
"\"label\"",
":",
"data",
"=",
"frame",
".",
"loc",
"[",
"multi_index",
".",
"get_level_values",
"(",
"lev... | 32.392857 | 20.285714 |
def transmit(self, payload, **kwargs):
"""
Transmit content metadata items to the integrated channel.
"""
items_to_create, items_to_update, items_to_delete, transmission_map = self._partition_items(payload)
self._prepare_items_for_delete(items_to_delete)
prepared_items = ... | [
"def",
"transmit",
"(",
"self",
",",
"payload",
",",
"*",
"*",
"kwargs",
")",
":",
"items_to_create",
",",
"items_to_update",
",",
"items_to_delete",
",",
"transmission_map",
"=",
"self",
".",
"_partition_items",
"(",
"payload",
")",
"self",
".",
"_prepare_ite... | 52.886364 | 27.431818 |
def distance(self, physical_qubit1, physical_qubit2):
"""Returns the undirected distance between physical_qubit1 and physical_qubit2.
Args:
physical_qubit1 (int): A physical qubit
physical_qubit2 (int): Another physical qubit
Returns:
int: The undirected dis... | [
"def",
"distance",
"(",
"self",
",",
"physical_qubit1",
",",
"physical_qubit2",
")",
":",
"if",
"physical_qubit1",
"not",
"in",
"self",
".",
"physical_qubits",
":",
"raise",
"CouplingError",
"(",
"\"%s not in coupling graph\"",
"%",
"(",
"physical_qubit1",
",",
")... | 41.55 | 20.55 |
async def vsetup(self, author):
"""Creates the voice client
Args:
author (discord.Member): The user that the voice ui will seek
"""
if self.vready:
logger.warning("Attempt to init voice when already initialised")
return
if self.state != 'sta... | [
"async",
"def",
"vsetup",
"(",
"self",
",",
"author",
")",
":",
"if",
"self",
".",
"vready",
":",
"logger",
".",
"warning",
"(",
"\"Attempt to init voice when already initialised\"",
")",
"return",
"if",
"self",
".",
"state",
"!=",
"'starting'",
":",
"logger",... | 38.733333 | 23.8 |
def psffunc(self, *args, **kwargs):
"""Calculates a linescan psf"""
if self.polychromatic:
func = psfcalc.calculate_polychrome_linescan_psf
else:
func = psfcalc.calculate_linescan_psf
return func(*args, **kwargs) | [
"def",
"psffunc",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"polychromatic",
":",
"func",
"=",
"psfcalc",
".",
"calculate_polychrome_linescan_psf",
"else",
":",
"func",
"=",
"psfcalc",
".",
"calculate_linescan_psf",... | 37.428571 | 10.714286 |
def RobotFactory(path, parent=None):
'''Return an instance of SuiteFile, ResourceFile, SuiteFolder
Exactly which is returned depends on whether it's a file or
folder, and if a file, the contents of the file. If there is a
testcase table, this will return an instance of SuiteFile,
otherwise it will ... | [
"def",
"RobotFactory",
"(",
"path",
",",
"parent",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"SuiteFolder",
"(",
"path",
",",
"parent",
")",
"else",
":",
"rf",
"=",
"RobotFile",
"(",
"path",
",",... | 30.181818 | 20.818182 |
def total(self, xbin1=1, xbin2=-2):
"""
Return the total yield and its associated statistical and
systematic uncertainties.
"""
integral, stat_error = self.hist.integral(
xbin1=xbin1, xbin2=xbin2, error=True)
# sum systematics in quadrature
ups = [0]
... | [
"def",
"total",
"(",
"self",
",",
"xbin1",
"=",
"1",
",",
"xbin2",
"=",
"-",
"2",
")",
":",
"integral",
",",
"stat_error",
"=",
"self",
".",
"hist",
".",
"integral",
"(",
"xbin1",
"=",
"xbin1",
",",
"xbin2",
"=",
"xbin2",
",",
"error",
"=",
"True... | 36.416667 | 12.916667 |
def find_unique_repos(where):
"""
Search for repositories and deduplicate based on ``repo.fpath``
Args:
where (str): path to search from
Yields:
Repository subclass
"""
repos = Dict()
path_uuids = Dict()
log.debug("find_unique_repos(%r)" % where)
for repo in find_fi... | [
"def",
"find_unique_repos",
"(",
"where",
")",
":",
"repos",
"=",
"Dict",
"(",
")",
"path_uuids",
"=",
"Dict",
"(",
")",
"log",
".",
"debug",
"(",
"\"find_unique_repos(%r)\"",
"%",
"where",
")",
"for",
"repo",
"in",
"find_find_repos",
"(",
"where",
")",
... | 27.464286 | 16.321429 |
def getContinuousSet(self, id_):
"""
Returns the ContinuousSet with the specified id, or raises a
ContinuousSetNotFoundException otherwise.
"""
if id_ not in self._continuousSetIdMap:
raise exceptions.ContinuousSetNotFoundException(id_)
return self._continuous... | [
"def",
"getContinuousSet",
"(",
"self",
",",
"id_",
")",
":",
"if",
"id_",
"not",
"in",
"self",
".",
"_continuousSetIdMap",
":",
"raise",
"exceptions",
".",
"ContinuousSetNotFoundException",
"(",
"id_",
")",
"return",
"self",
".",
"_continuousSetIdMap",
"[",
"... | 40.75 | 10 |
def find_parent_split(node, orientation):
"""
Find the first parent split relative to the given node
according to the desired orientation
"""
if (node and node.orientation == orientation
and len(node.children) > 1):
return node
if not node or node.type == "workspace":
r... | [
"def",
"find_parent_split",
"(",
"node",
",",
"orientation",
")",
":",
"if",
"(",
"node",
"and",
"node",
".",
"orientation",
"==",
"orientation",
"and",
"len",
"(",
"node",
".",
"children",
")",
">",
"1",
")",
":",
"return",
"node",
"if",
"not",
"node"... | 26.642857 | 15.071429 |
def _compute_heating_rates(self):
'''Compute energy flux convergences to get heating rates in :math:`W/m^2`.'''
self._compute_flux()
self.heating_rate['Ts'] = -self._flux
# Modify only the lowest model level
self.heating_rate['Tatm'][..., -1, np.newaxis] = self._flux | [
"def",
"_compute_heating_rates",
"(",
"self",
")",
":",
"self",
".",
"_compute_flux",
"(",
")",
"self",
".",
"heating_rate",
"[",
"'Ts'",
"]",
"=",
"-",
"self",
".",
"_flux",
"# Modify only the lowest model level",
"self",
".",
"heating_rate",
"[",
"'Tatm'",
"... | 50.333333 | 16.666667 |
def HashBuffer(self, buf):
"""Updates underlying hashers with a given buffer.
Args:
buf: A byte buffer (string object) that is going to be fed to the hashers.
"""
for hasher in itervalues(self._hashers):
hasher.update(buf)
if self._progress:
self._progress()
self._bytes_r... | [
"def",
"HashBuffer",
"(",
"self",
",",
"buf",
")",
":",
"for",
"hasher",
"in",
"itervalues",
"(",
"self",
".",
"_hashers",
")",
":",
"hasher",
".",
"update",
"(",
"buf",
")",
"if",
"self",
".",
"_progress",
":",
"self",
".",
"_progress",
"(",
")",
... | 27 | 18.75 |
def b58decode(v):
'''Decode a Base58 encoded string'''
if not isinstance(v, str):
v = v.decode('ascii')
origlen = len(v)
v = v.lstrip(alphabet[0])
newlen = len(v)
acc = b58decode_int(v)
result = []
while acc > 0:
acc, mod = divmod(acc, 256)
result.append(mod)
... | [
"def",
"b58decode",
"(",
"v",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"str",
")",
":",
"v",
"=",
"v",
".",
"decode",
"(",
"'ascii'",
")",
"origlen",
"=",
"len",
"(",
"v",
")",
"v",
"=",
"v",
".",
"lstrip",
"(",
"alphabet",
"[",
"0... | 20.444444 | 22.222222 |
def select(self, *column_names, **kwargs):
'''
Select the provided column names from the model, do not return an entity,
do not involve the rom session, just get the raw and/or processed column
data from Redis.
Keyword-only arguments:
* *include_pk=False* - whether ... | [
"def",
"select",
"(",
"self",
",",
"*",
"column_names",
",",
"*",
"*",
"kwargs",
")",
":",
"include_pk",
"=",
"kwargs",
".",
"pop",
"(",
"'include_pk'",
",",
"False",
")",
"decode",
"=",
"kwargs",
".",
"pop",
"(",
"'decode'",
",",
"True",
")",
"ff",
... | 43.621622 | 27.432432 |
def makeGLMModel(model, coefs, threshold=.5):
"""
Create a custom GLM model using the given coefficients.
Needs to be passed source model trained on the dataset to extract the dataset information from.
:param model: source model, used for extracting dataset information
:param c... | [
"def",
"makeGLMModel",
"(",
"model",
",",
"coefs",
",",
"threshold",
"=",
".5",
")",
":",
"model_json",
"=",
"h2o",
".",
"api",
"(",
"\"POST /3/MakeGLMModel\"",
",",
"data",
"=",
"{",
"\"model\"",
":",
"model",
".",
"_model_json",
"[",
"\"model_id\"",
"]",... | 43.35 | 21.35 |
def find_executable(name: str, flags=os.X_OK) -> List[str]:
r"""Finds executable `name`.
Similar to Unix ``which`` command.
Returns list of zero or more full paths to `name`.
"""
result = []
extensions = [x for x in os.environ.get("PATHEXT", "").split(os.pathsep) if x]
path = os.environ.ge... | [
"def",
"find_executable",
"(",
"name",
":",
"str",
",",
"flags",
"=",
"os",
".",
"X_OK",
")",
"->",
"List",
"[",
"str",
"]",
":",
"result",
"=",
"[",
"]",
"extensions",
"=",
"[",
"x",
"for",
"x",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"\"... | 34.238095 | 14.666667 |
def list(self, **params):
"""
Retrieve all orders
Returns all orders available to the user according to the parameters provided
:calls: ``get /orders``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, whic... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"orders",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/orders\"",
",",
"params",
"=",
"params",
")",
"return",
"orders"
] | 33.285714 | 25.428571 |
def require(f):
'''
The @require decorator, usable in an immutable class (see immutable), specifies that the
following function is actually a validation check on the immutable class. These functions
will appear as static members of the class and get called automatically when the relevant
data change... | [
"def",
"require",
"(",
"f",
")",
":",
"(",
"args",
",",
"varargs",
",",
"kwargs",
",",
"dflts",
")",
"=",
"getargspec_py27like",
"(",
"f",
")",
"if",
"varargs",
"is",
"not",
"None",
"or",
"kwargs",
"is",
"not",
"None",
"or",
"dflts",
":",
"raise",
... | 49.222222 | 26.777778 |
def render_image(self, rgbobj, dst_x, dst_y):
"""Render the image represented by (rgbobj) at dst_x, dst_y
in the pixel space.
*** internal method-- do not use ***
"""
self.logger.debug("redraw surface=%s" % (self.surface))
if self.surface is None:
return
... | [
"def",
"render_image",
"(",
"self",
",",
"rgbobj",
",",
"dst_x",
",",
"dst_y",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"redraw surface=%s\"",
"%",
"(",
"self",
".",
"surface",
")",
")",
"if",
"self",
".",
"surface",
"is",
"None",
":",
"... | 37.675676 | 15.675676 |
def prepare_logged(x, y):
"""
Transform `x` and `y` to a log scale while dealing with zeros.
This function scales `x` and `y` such that the points that are zero in one
array are set to the min of the other array.
When plotting expression data, frequently one sample will have reads in
a particu... | [
"def",
"prepare_logged",
"(",
"x",
",",
"y",
")",
":",
"xi",
"=",
"np",
".",
"log2",
"(",
"x",
")",
"yi",
"=",
"np",
".",
"log2",
"(",
"y",
")",
"xv",
"=",
"np",
".",
"isfinite",
"(",
"xi",
")",
"yv",
"=",
"np",
".",
"isfinite",
"(",
"yi",
... | 30.5 | 24 |
def setErrorHandler(self,f,arg):
"""Register an error handler that will be called back as
f(arg,msg,severity,reserved).
@reserved is currently always None."""
libxml2mod.xmlParserCtxtSetErrorHandler(self._o,f,arg) | [
"def",
"setErrorHandler",
"(",
"self",
",",
"f",
",",
"arg",
")",
":",
"libxml2mod",
".",
"xmlParserCtxtSetErrorHandler",
"(",
"self",
".",
"_o",
",",
"f",
",",
"arg",
")"
] | 41.166667 | 11.666667 |
def hex2rgb(h):
"""
Convert hex colors to RGB tuples
Parameters
----------
h : str
String hex color value
>>> hex2rgb("#ff0033")
'255,0,51'
"""
if not h.startswith('#') or len(h) != 7:
raise ValueError("Does not look like a hex color: '{0}'".format(h))
return ',... | [
"def",
"hex2rgb",
"(",
"h",
")",
":",
"if",
"not",
"h",
".",
"startswith",
"(",
"'#'",
")",
"or",
"len",
"(",
"h",
")",
"!=",
"7",
":",
"raise",
"ValueError",
"(",
"\"Does not look like a hex color: '{0}'\"",
".",
"format",
"(",
"h",
")",
")",
"return"... | 21.157895 | 19.473684 |
def fasttagcount(sam, out, genemap, positional, minevidence, cb_histogram,
cb_cutoff, subsample, parse_tags, gene_tags, umi_matrix):
''' Count up evidence for tagged molecules, this implementation assumes the
alignment file is coordinate sorted
'''
from pysam import AlignmentFile
... | [
"def",
"fasttagcount",
"(",
"sam",
",",
"out",
",",
"genemap",
",",
"positional",
",",
"minevidence",
",",
"cb_histogram",
",",
"cb_cutoff",
",",
"subsample",
",",
"parse_tags",
",",
"gene_tags",
",",
"umi_matrix",
")",
":",
"from",
"pysam",
"import",
"Align... | 35.081448 | 18.918552 |
def what_task(self, token_id, presented_pronunciation, index, phonemes, phonemes_probability,
warn=True, default=True):
"""Provide the prediction of the what task.
This function is used to predict the probability of a given phoneme being reported at a given index
for a given t... | [
"def",
"what_task",
"(",
"self",
",",
"token_id",
",",
"presented_pronunciation",
",",
"index",
",",
"phonemes",
",",
"phonemes_probability",
",",
"warn",
"=",
"True",
",",
"default",
"=",
"True",
")",
":",
"if",
"phonemes_probability",
"is",
"not",
"None",
... | 52.595745 | 33.021277 |
def fragment_fromstring(html, create_parent=False,
guess_charset=False, parser=None):
"""Parses a single HTML element; it is an error if there is more than
one element, or if anything but whitespace precedes or follows the
element.
If create_parent is true (or is a tag name) the... | [
"def",
"fragment_fromstring",
"(",
"html",
",",
"create_parent",
"=",
"False",
",",
"guess_charset",
"=",
"False",
",",
"parser",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"html",
",",
"_strings",
")",
":",
"raise",
"TypeError",
"(",
"'string ... | 36.102564 | 16.666667 |
def get_bucket_type_props(self, bucket_type):
"""
Fetch bucket-type properties
"""
self._check_bucket_types(bucket_type)
msg_code = riak.pb.messages.MSG_CODE_GET_BUCKET_TYPE_REQ
codec = self._get_codec(msg_code)
msg = codec.encode_get_bucket_type_props(bucket_type... | [
"def",
"get_bucket_type_props",
"(",
"self",
",",
"bucket_type",
")",
":",
"self",
".",
"_check_bucket_types",
"(",
"bucket_type",
")",
"msg_code",
"=",
"riak",
".",
"pb",
".",
"messages",
".",
"MSG_CODE_GET_BUCKET_TYPE_REQ",
"codec",
"=",
"self",
".",
"_get_cod... | 41.7 | 8.3 |
def main(*argv):
""" main driver of program """
try:
# Inputs
#
adminUsername = argv[0]
adminPassword = argv[1]
siteURL = argv[2]
groupTitle = argv[3]
groupTags = argv[4]
description = argv[5]
access = argv[6]
# Logic
#... | [
"def",
"main",
"(",
"*",
"argv",
")",
":",
"try",
":",
"# Inputs",
"#",
"adminUsername",
"=",
"argv",
"[",
"0",
"]",
"adminPassword",
"=",
"argv",
"[",
"1",
"]",
"siteURL",
"=",
"argv",
"[",
"2",
"]",
"groupTitle",
"=",
"argv",
"[",
"3",
"]",
"... | 41.388889 | 17.759259 |
def encode(self, envelope, session, encoding=None, **kwargs):
""" :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation.
:param envelope: original envelope
:param session: original session
:param encoding: encoding to use (default is 'utf-8')
:param kwargs: additional arguments
:return: WMe... | [
"def",
"encode",
"(",
"self",
",",
"envelope",
",",
"session",
",",
"encoding",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"envelope",
".",
"message",
"(",
")",
"message",
"=",
"message",
".",
"encode",
"(",
")",
"if",
"encoding"... | 38.538462 | 15.307692 |
def run(self):
"""
Run the database seeds.
"""
self.factory.register(User, self.users_factory)
self.factory(User, 50).create() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"factory",
".",
"register",
"(",
"User",
",",
"self",
".",
"users_factory",
")",
"self",
".",
"factory",
"(",
"User",
",",
"50",
")",
".",
"create",
"(",
")"
] | 23 | 13 |
def load(data, udf, data_dir, overwrite):
"""Load Ibis test data and build/upload UDFs"""
con = make_ibis_client(ENV)
# validate our environment before performing possibly expensive operations
if not can_write_to_hdfs(con):
raise IbisError('Failed to write to HDFS; check your settings')
if ... | [
"def",
"load",
"(",
"data",
",",
"udf",
",",
"data_dir",
",",
"overwrite",
")",
":",
"con",
"=",
"make_ibis_client",
"(",
"ENV",
")",
"# validate our environment before performing possibly expensive operations",
"if",
"not",
"can_write_to_hdfs",
"(",
"con",
")",
":"... | 37.580645 | 19.612903 |
def random(self, namespace=0):
"""
Returns query string for random page
"""
query = self.LIST.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LIST='random')
query += "&rnlimit=1&rnnamespace=%d" % namespace
emoji = [
u'\U... | [
"def",
"random",
"(",
"self",
",",
"namespace",
"=",
"0",
")",
":",
"query",
"=",
"self",
".",
"LIST",
".",
"substitute",
"(",
"WIKI",
"=",
"self",
".",
"uri",
",",
"ENDPOINT",
"=",
"self",
".",
"endpoint",
",",
"LIST",
"=",
"'random'",
")",
"query... | 28.678571 | 14.107143 |
def show_hydrophobic(self):
"""Visualizes hydrophobic contacts."""
hydroph = self.plcomplex.hydrophobic_contacts
if not len(hydroph.bs_ids) == 0:
self.select_by_ids('Hydrophobic-P', hydroph.bs_ids, restrict=self.protname)
self.select_by_ids('Hydrophobic-L', hydroph.lig_id... | [
"def",
"show_hydrophobic",
"(",
"self",
")",
":",
"hydroph",
"=",
"self",
".",
"plcomplex",
".",
"hydrophobic_contacts",
"if",
"not",
"len",
"(",
"hydroph",
".",
"bs_ids",
")",
"==",
"0",
":",
"self",
".",
"select_by_ids",
"(",
"'Hydrophobic-P'",
",",
"hyd... | 51.0625 | 20.8125 |
def increment(handler, increment, item_id, counter_name):
"""Increment a counter attribute atomically"""
data = {'operation': 'increment_counter',
'id': item_id,
'counter_name': counter_name,
'increment': increment}
handler.invoke(data) | [
"def",
"increment",
"(",
"handler",
",",
"increment",
",",
"item_id",
",",
"counter_name",
")",
":",
"data",
"=",
"{",
"'operation'",
":",
"'increment_counter'",
",",
"'id'",
":",
"item_id",
",",
"'counter_name'",
":",
"counter_name",
",",
"'increment'",
":",
... | 39.714286 | 8.285714 |
def exchange_declare(self, exchange, type, durable, auto_delete):
"""Declare an named exchange."""
return self.channel.exchange_declare(exchange=exchange,
type=type,
durable=durable,
... | [
"def",
"exchange_declare",
"(",
"self",
",",
"exchange",
",",
"type",
",",
"durable",
",",
"auto_delete",
")",
":",
"return",
"self",
".",
"channel",
".",
"exchange_declare",
"(",
"exchange",
"=",
"exchange",
",",
"type",
"=",
"type",
",",
"durable",
"=",
... | 58.833333 | 18.833333 |
def _set_permissions(zip_file_info, extracted_path):
"""
Sets permissions on the extracted file by reading the ``external_attr`` property of given file info.
Parameters
----------
zip_file_info : zipfile.ZipInfo
Object containing information about a file within a zip archive
extracted_... | [
"def",
"_set_permissions",
"(",
"zip_file_info",
",",
"extracted_path",
")",
":",
"# Permission information is stored in first two bytes.",
"permission",
"=",
"zip_file_info",
".",
"external_attr",
">>",
"16",
"if",
"not",
"permission",
":",
"# Zips created on certain Windows... | 37.409091 | 25.590909 |
def delete_client(client_id, preserve_cache):
"""Delete all objects related to client
@param client_id: ID of client user
@param preserve_cache: Boolean, whether to delete the chrome profile folder or not
"""
if client_id in drivers:
drivers.pop(client_id).quit()
try:
... | [
"def",
"delete_client",
"(",
"client_id",
",",
"preserve_cache",
")",
":",
"if",
"client_id",
"in",
"drivers",
":",
"drivers",
".",
"pop",
"(",
"client_id",
")",
".",
"quit",
"(",
")",
"try",
":",
"timers",
"[",
"client_id",
"]",
".",
"stop",
"(",
")",... | 30.578947 | 13.736842 |
def get_access_tokens(self, authorization_code):
"""From the authorization code, get the "access token" and the "refresh token" from Box.
Args:
authorization_code (str). Authorisation code emitted by Box at the url provided by the function :func:`get_authorization_url`.
Returns:
... | [
"def",
"get_access_tokens",
"(",
"self",
",",
"authorization_code",
")",
":",
"response",
"=",
"self",
".",
"box_request",
".",
"get_access_token",
"(",
"authorization_code",
")",
"try",
":",
"att",
"=",
"response",
".",
"json",
"(",
")",
"except",
"Exception"... | 35.923077 | 25.884615 |
def login_required_with_ajax(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is logged in,
redirecting to the log-in page if necessary, but returns a special
response for ajax requests. See
:meth:`eulcommon.djangoextras.auth.decorators.user... | [
"def",
"login_required_with_ajax",
"(",
"function",
"=",
"None",
",",
"redirect_field_name",
"=",
"REDIRECT_FIELD_NAME",
")",
":",
"# NOTE: currently only this format works: @login_required_with_ajax()",
"# But this format errors: @login_required_with_ajax",
"if",
"function",
"is",
... | 38.578947 | 23.315789 |
def load_data(self, filename, *args, **kwargs):
"""
load data from text file.
:param filename: name of file to read
:type filename: str
:returns: data read from file using :func:`numpy.genfromtxt`
:rtype: dict
:raises: :exc:`~simkit.core.exceptions.UnnamedDataErr... | [
"def",
"load_data",
"(",
"self",
",",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# header keys",
"header_param",
"=",
"self",
".",
"parameters",
".",
"get",
"(",
"'header'",
")",
"# default is None",
"# data keys",
"data_param",
"=",
... | 48.023256 | 19.883721 |
def list_sessions(self, updated_since=None, max_results=100, skip=0, **kwargs):
"""List session IDs.
List the Session IDs with pending messages in the queue where the state of the session
has been updated since the timestamp provided. If no timestamp is provided, all will be returned.
I... | [
"def",
"list_sessions",
"(",
"self",
",",
"updated_since",
"=",
"None",
",",
"max_results",
"=",
"100",
",",
"skip",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"entity",
"and",
"not",
"self",
".",
"requires_session",
":",
"raise",
... | 49.135135 | 27.540541 |
def search_definition(self, module, keyword, arg):
"""Search for a defintion with `keyword` `name`
Search the module and its submodules."""
r = module.search_one(keyword, arg)
if r is not None:
return r
for i in module.search('include'):
modulename = i.arg... | [
"def",
"search_definition",
"(",
"self",
",",
"module",
",",
"keyword",
",",
"arg",
")",
":",
"r",
"=",
"module",
".",
"search_one",
"(",
"keyword",
",",
"arg",
")",
"if",
"r",
"is",
"not",
"None",
":",
"return",
"r",
"for",
"i",
"in",
"module",
".... | 37.5 | 9.571429 |
def search(title=None, artist=None, artist_id=None, combined=None, description=None, style=None, mood=None,
results=None, start=None, max_tempo=None, min_tempo=None,
max_duration=None, min_duration=None, max_loudness=None, min_loudness=None,
artist_max_familiarity=None, artist_min_famil... | [
"def",
"search",
"(",
"title",
"=",
"None",
",",
"artist",
"=",
"None",
",",
"artist_id",
"=",
"None",
",",
"combined",
"=",
"None",
",",
"description",
"=",
"None",
",",
"style",
"=",
"None",
",",
"mood",
"=",
"None",
",",
"results",
"=",
"None",
... | 63.855556 | 36.133333 |
def p_delays_intnumber(self, p):
'delays : DELAY intnumber'
p[0] = DelayStatement(
IntConst(p[2], lineno=p.lineno(1)), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_delays_intnumber",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"DelayStatement",
"(",
"IntConst",
"(",
"p",
"[",
"2",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
",",
"lineno",
"=",
"p",
".",
"lineno... | 39.8 | 11 |
async def outlook(self) -> dict:
"""Get allergen outlook."""
try:
return await self._request(
'get', 'https://www.pollen.com/api/forecast/outlook')
except RequestError as err:
if '404' in str(err):
raise InvalidZipError('No data returned fo... | [
"async",
"def",
"outlook",
"(",
"self",
")",
"->",
"dict",
":",
"try",
":",
"return",
"await",
"self",
".",
"_request",
"(",
"'get'",
",",
"'https://www.pollen.com/api/forecast/outlook'",
")",
"except",
"RequestError",
"as",
"err",
":",
"if",
"'404'",
"in",
... | 38.1 | 13.2 |
def _get_bounds(self, ib, dimension):
"""ib == 0/1 means lower/upper bound, return a vector of length
`dimension` """
sign_ = 2 * ib - 1
assert sign_**2 == 1
if self.bounds is None or self.bounds[ib] is None:
return array(dimension * [sign_ * np.Inf])
res = []... | [
"def",
"_get_bounds",
"(",
"self",
",",
"ib",
",",
"dimension",
")",
":",
"sign_",
"=",
"2",
"*",
"ib",
"-",
"1",
"assert",
"sign_",
"**",
"2",
"==",
"1",
"if",
"self",
".",
"bounds",
"is",
"None",
"or",
"self",
".",
"bounds",
"[",
"ib",
"]",
"... | 39.923077 | 11.461538 |
def _mor_to_pobject(self, mo_ref):
"""Converts a MOR to a psphere object."""
kls = classmapper(mo_ref._type)
new_object = kls(mo_ref, self)
return new_object | [
"def",
"_mor_to_pobject",
"(",
"self",
",",
"mo_ref",
")",
":",
"kls",
"=",
"classmapper",
"(",
"mo_ref",
".",
"_type",
")",
"new_object",
"=",
"kls",
"(",
"mo_ref",
",",
"self",
")",
"return",
"new_object"
] | 37 | 4.8 |
def _compute_mean(self, C, rup, dists, sites, imt):
"""
Returns the mean ground motion acceleration and velocity
"""
mean = (self._get_magnitude_scaling_term(C, rup.mag) +
self._get_distance_scaling_term(C, rup.mag, dists.rrup) +
self._get_site_amplificati... | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"rup",
",",
"dists",
",",
"sites",
",",
"imt",
")",
":",
"mean",
"=",
"(",
"self",
".",
"_get_magnitude_scaling_term",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"+",
"self",
".",
"_get_distance_scaling_t... | 43.315789 | 19.210526 |
def save_checkpoint(prefix, epoch, symbol, arg_params, aux_params):
"""Checkpoint the model data into file.
Parameters
----------
prefix : str
Prefix of model name.
epoch : int
The epoch number of the model.
symbol : Symbol
The input Symbol.
arg_params : dict of str ... | [
"def",
"save_checkpoint",
"(",
"prefix",
",",
"epoch",
",",
"symbol",
",",
"arg_params",
",",
"aux_params",
")",
":",
"if",
"symbol",
"is",
"not",
"None",
":",
"symbol",
".",
"save",
"(",
"'%s-symbol.json'",
"%",
"prefix",
")",
"save_dict",
"=",
"{",
"("... | 36.928571 | 20.428571 |
def fragment(self, value=None):
"""
Return or set the fragment (hash)
:param string value: the new fragment to use
:returns: string or new :class:`URL` instance
"""
if value is not None:
return URL._mutate(self, fragment=value)
return unicode_unquote(... | [
"def",
"fragment",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"return",
"URL",
".",
"_mutate",
"(",
"self",
",",
"fragment",
"=",
"value",
")",
"return",
"unicode_unquote",
"(",
"self",
".",
"_tuple",
"... | 33.2 | 11 |
def get_dtext(value):
""" dtext = <printable ascii except \ [ ]> / obs-dtext
obs-dtext = obs-NO-WS-CTL / quoted-pair
We allow anything except the excluded characters, but if we find any
ASCII other than the RFC defined printable ASCII an NonPrintableDefect is
added to the token's defects list. ... | [
"def",
"get_dtext",
"(",
"value",
")",
":",
"ptext",
",",
"value",
",",
"had_qp",
"=",
"_get_ptext_to_endchars",
"(",
"value",
",",
"'[]'",
")",
"ptext",
"=",
"ValueTerminal",
"(",
"ptext",
",",
"'ptext'",
")",
"if",
"had_qp",
":",
"ptext",
".",
"defects... | 43.894737 | 21.105263 |
def drop(self, columns):
"""Drop 1 or more columns. Any column which does not exist in the DataFrame is skipped, i.e. not removed,
without raising an exception.
Unlike Pandas' drop, this is currently restricted to dropping columns.
Parameters
----------
columns : str or... | [
"def",
"drop",
"(",
"self",
",",
"columns",
")",
":",
"if",
"isinstance",
"(",
"columns",
",",
"str",
")",
":",
"new_data",
"=",
"OrderedDict",
"(",
")",
"if",
"columns",
"not",
"in",
"self",
".",
"_gather_column_names",
"(",
")",
":",
"raise",
"KeyErr... | 31.324324 | 19.756757 |
def uncluster_annotations(self, input_annotations, reverse_pipe):
'''
Update the annotations hash provided by pplacer to include all
representatives within each cluster
Parameters
----------
input_annotations : hash
Classifications for each representative seq... | [
"def",
"uncluster_annotations",
"(",
"self",
",",
"input_annotations",
",",
"reverse_pipe",
")",
":",
"output_annotations",
"=",
"{",
"}",
"for",
"placed_alignment_file_path",
",",
"clusters",
"in",
"self",
".",
"seq_library",
".",
"iteritems",
"(",
")",
":",
"i... | 45.853659 | 30.536585 |
def getAllEventsByDay(request, fromDate, toDate, *, home=None):
"""
Return all the events (under home if given) for the dates given, grouped by
day.
:param request: Django request object
:param fromDate: starting date (inclusive)
:param toDate: finish date (inclusive)
:param home: only incl... | [
"def",
"getAllEventsByDay",
"(",
"request",
",",
"fromDate",
",",
"toDate",
",",
"*",
",",
"home",
"=",
"None",
")",
":",
"qrys",
"=",
"[",
"SimpleEventPage",
".",
"events",
"(",
"request",
")",
".",
"byDay",
"(",
"fromDate",
",",
"toDate",
")",
",",
... | 47.4 | 21.9 |
def subtype_group_id(self):
"""
str: Subtype Group ID
"""
self._validate()
self._validate_for_subtype_group_id()
parts = []
parts.append(self.election_type)
parts.append(self.subtype)
parts.append(self.date)
return ".".join(parts) | [
"def",
"subtype_group_id",
"(",
"self",
")",
":",
"self",
".",
"_validate",
"(",
")",
"self",
".",
"_validate_for_subtype_group_id",
"(",
")",
"parts",
"=",
"[",
"]",
"parts",
".",
"append",
"(",
"self",
".",
"election_type",
")",
"parts",
".",
"append",
... | 25 | 11 |
def decrypt_report(self, device_id, root, data, **kwargs):
"""Decrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (... | [
"def",
"decrypt_report",
"(",
"self",
",",
"device_id",
",",
"root",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"report_key",
"=",
"self",
".",
"_verify_derive_key",
"(",
"device_id",
",",
"root",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"from",
... | 41.35 | 27.15 |
def make_wheelfile_inner(base_name, base_dir='.'):
"""Create a whl file from all the files under 'base_dir'.
Places .dist-info at the end of the archive."""
zip_filename = base_name + ".whl"
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
# XXX support bz2, xz when availa... | [
"def",
"make_wheelfile_inner",
"(",
"base_name",
",",
"base_dir",
"=",
"'.'",
")",
":",
"zip_filename",
"=",
"base_name",
"+",
"\".whl\"",
"log",
".",
"info",
"(",
"\"creating '%s' and adding '%s' to it\"",
",",
"zip_filename",
",",
"base_dir",
")",
"# XXX support b... | 28.621622 | 21.324324 |
def connect_reftrack_scenenode(self, refobj, scenenode):
"""Connect the given reftrack node with the given scene node
:param refobj: the reftrack node to connect
:type refobj: str
:param scenenode: the jb_sceneNode to connect
:type scenenode: str
:returns: None
:... | [
"def",
"connect_reftrack_scenenode",
"(",
"self",
",",
"refobj",
",",
"scenenode",
")",
":",
"conns",
"=",
"[",
"(",
"\"%s.scenenode\"",
"%",
"refobj",
",",
"\"%s.reftrack\"",
"%",
"scenenode",
")",
",",
"(",
"\"%s.taskfile_id\"",
"%",
"scenenode",
",",
"\"%s.... | 39.375 | 16.1875 |
def write_memory(self, session, space, offset, data, width, extended=False):
"""Write in an 8-bit, 16-bit, 32-bit, 64-bit value to the specified memory space and offset.
Corresponds to viOut* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param ... | [
"def",
"write_memory",
"(",
"self",
",",
"session",
",",
"space",
",",
"offset",
",",
"data",
",",
"width",
",",
"extended",
"=",
"False",
")",
":",
"if",
"width",
"==",
"8",
":",
"return",
"self",
".",
"out_8",
"(",
"session",
",",
"space",
",",
"... | 49.875 | 23.833333 |
def get_date_822():
"""return output of 822-date command"""
cmd = '/bin/date'
if not os.path.exists(cmd):
raise ValueError('%s command does not exist.'%cmd)
args = [cmd,'-R']
result = get_cmd_stdout(args).strip()
result = normstr(result)
return result | [
"def",
"get_date_822",
"(",
")",
":",
"cmd",
"=",
"'/bin/date'",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cmd",
")",
":",
"raise",
"ValueError",
"(",
"'%s command does not exist.'",
"%",
"cmd",
")",
"args",
"=",
"[",
"cmd",
",",
"'-R'",
"]"... | 31 | 13.555556 |
def _BernII_to_Flavio_II(C, udlnu, parameters):
"""From BernII to FlavioII basis
for charged current process semileptonic operators.
`udlnu` should be of the form 'udl_enu_tau', 'cbl_munu_e' etc."""
p = parameters
u = uflav[udlnu[0]]
d = dflav[udlnu[1]]
l = lflav[udlnu[4:udlnu.find('n')]]
... | [
"def",
"_BernII_to_Flavio_II",
"(",
"C",
",",
"udlnu",
",",
"parameters",
")",
":",
"p",
"=",
"parameters",
"u",
"=",
"uflav",
"[",
"udlnu",
"[",
"0",
"]",
"]",
"d",
"=",
"dflav",
"[",
"udlnu",
"[",
"1",
"]",
"]",
"l",
"=",
"lflav",
"[",
"udlnu",... | 45.130435 | 15.782609 |
def makerandCIJ_dir(n, k, seed=None):
'''
This function generates a directed random network
Parameters
----------
N : int
number of vertices
K : int
number of edges
seed : hashable, optional
If None (default), use the np.random's global random state to generate rando... | [
"def",
"makerandCIJ_dir",
"(",
"n",
",",
"k",
",",
"seed",
"=",
"None",
")",
":",
"rng",
"=",
"get_rng",
"(",
"seed",
")",
"ix",
",",
"=",
"np",
".",
"where",
"(",
"np",
".",
"logical_not",
"(",
"np",
".",
"eye",
"(",
"n",
")",
")",
".",
"fla... | 24.933333 | 24.2 |
def refresh(self, movie):
""" Try to refresh metadata of the movie through the datasource.
"""
if '_tmdbtv_id' in movie:
refreshed = {'_Datasource': self.name}
tvseries_id = movie['_tmdbtv_id']
series = self._tmdb_series(tvseries_id)
alternatives =... | [
"def",
"refresh",
"(",
"self",
",",
"movie",
")",
":",
"if",
"'_tmdbtv_id'",
"in",
"movie",
":",
"refreshed",
"=",
"{",
"'_Datasource'",
":",
"self",
".",
"name",
"}",
"tvseries_id",
"=",
"movie",
"[",
"'_tmdbtv_id'",
"]",
"series",
"=",
"self",
".",
"... | 65.666667 | 28.433333 |
async def sinter(self, keys, *args):
"""
Return the intersection of sets specified by ``keys``
Cluster impl:
Querry all keys, intersection and return result
"""
k = list_or_args(keys, args)
res = await self.smembers(k[0])
for arg in k[1:]:
... | [
"async",
"def",
"sinter",
"(",
"self",
",",
"keys",
",",
"*",
"args",
")",
":",
"k",
"=",
"list_or_args",
"(",
"keys",
",",
"args",
")",
"res",
"=",
"await",
"self",
".",
"smembers",
"(",
"k",
"[",
"0",
"]",
")",
"for",
"arg",
"in",
"k",
"[",
... | 25.714286 | 16.285714 |
def save(self):
"""Convert to JSON.
Returns
-------
`dict`
JSON data.
"""
data = super().save()
data['state_sizes'] = self.state_sizes
data['reset_on_sentence_end'] = self.reset_on_sentence_end
return data | [
"def",
"save",
"(",
"self",
")",
":",
"data",
"=",
"super",
"(",
")",
".",
"save",
"(",
")",
"data",
"[",
"'state_sizes'",
"]",
"=",
"self",
".",
"state_sizes",
"data",
"[",
"'reset_on_sentence_end'",
"]",
"=",
"self",
".",
"reset_on_sentence_end",
"retu... | 23.25 | 18.583333 |
def _create_security_group(self, ingress):
"""Send a POST to spinnaker to create a new security group.
Returns:
boolean: True if created successfully
"""
template_kwargs = {
'app': self.app_name,
'env': self.env,
'region': self.region,
... | [
"def",
"_create_security_group",
"(",
"self",
",",
"ingress",
")",
":",
"template_kwargs",
"=",
"{",
"'app'",
":",
"self",
".",
"app_name",
",",
"'env'",
":",
"self",
".",
"env",
",",
"'region'",
":",
"self",
".",
"region",
",",
"'vpc'",
":",
"get_vpc_id... | 32.428571 | 20.142857 |
def makedminfo(tabdesc, group_spec=None):
"""Creates a data manager information object.
Create a data manager information dictionary outline from a table description.
The resulting dictionary is a bare outline and is available for the purposes of
further customising the data manager via the `group_spec` argume... | [
"def",
"makedminfo",
"(",
"tabdesc",
",",
"group_spec",
"=",
"None",
")",
":",
"if",
"group_spec",
"is",
"None",
":",
"group_spec",
"=",
"{",
"}",
"class",
"DMGroup",
"(",
"object",
")",
":",
"\"\"\"\n Keep track of the columns, type and spec of each data manager... | 28.894118 | 20.917647 |
def fmt_border(self, dimensions, t = 'm', border_style = 'utf8.a', border_formating = {}):
"""
Format table separator line.
"""
cells = []
for column in dimensions:
cells.append(self.bchar('h', t, border_style) * (dimensions[column] + 2))
border = '{}{}{}'.fo... | [
"def",
"fmt_border",
"(",
"self",
",",
"dimensions",
",",
"t",
"=",
"'m'",
",",
"border_style",
"=",
"'utf8.a'",
",",
"border_formating",
"=",
"{",
"}",
")",
":",
"cells",
"=",
"[",
"]",
"for",
"column",
"in",
"dimensions",
":",
"cells",
".",
"append",... | 48.6 | 29 |
def sync_tools(
self, all_=False, destination=None, dry_run=False, public=False,
source=None, stream=None, version=None):
"""Copy Juju tools into this model.
:param bool all_: Copy all versions, not just the latest
:param str destination: Path to local destination direct... | [
"def",
"sync_tools",
"(",
"self",
",",
"all_",
"=",
"False",
",",
"destination",
"=",
"None",
",",
"dry_run",
"=",
"False",
",",
"public",
"=",
"False",
",",
"source",
"=",
"None",
",",
"stream",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
... | 44.375 | 21.875 |
def uniform_index(index,length):
'''
uniform_index(0,3)
uniform_index(-1,3)
uniform_index(-4,3)
uniform_index(-3,3)
uniform_index(5,3)
'''
if(index<0):
rl = length+index
if(rl<0):
index = 0
else:
index = rl
elif(inde... | [
"def",
"uniform_index",
"(",
"index",
",",
"length",
")",
":",
"if",
"(",
"index",
"<",
"0",
")",
":",
"rl",
"=",
"length",
"+",
"index",
"if",
"(",
"rl",
"<",
"0",
")",
":",
"index",
"=",
"0",
"else",
":",
"index",
"=",
"rl",
"elif",
"(",
"i... | 20.315789 | 19.684211 |
def anyword_substring_search_inner(query_word, target_words):
""" return True if ANY target_word matches a query_word
"""
for target_word in target_words:
if(target_word.startswith(query_word)):
return query_word
return False | [
"def",
"anyword_substring_search_inner",
"(",
"query_word",
",",
"target_words",
")",
":",
"for",
"target_word",
"in",
"target_words",
":",
"if",
"(",
"target_word",
".",
"startswith",
"(",
"query_word",
")",
")",
":",
"return",
"query_word",
"return",
"False"
] | 25.5 | 18.7 |
def _write_var_data_sparse(self, f, zVar, var, dataType, numElems, recVary,
oneblock):
'''
Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this ... | [
"def",
"_write_var_data_sparse",
"(",
"self",
",",
"f",
",",
"zVar",
",",
"var",
",",
"dataType",
",",
"numElems",
",",
"recVary",
",",
"oneblock",
")",
":",
"rec_start",
"=",
"oneblock",
"[",
"0",
"]",
"rec_end",
"=",
"oneblock",
"[",
"1",
"]",
"indat... | 34.716049 | 19.654321 |
def predict(self, temp_type):
"""
Transpile the predict method.
Parameters
----------
:param temp_type: string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
The transpiled predict method... | [
"def",
"predict",
"(",
"self",
",",
"temp_type",
")",
":",
"# Exported:",
"if",
"temp_type",
"==",
"'exported'",
":",
"temp",
"=",
"self",
".",
"temp",
"(",
"'exported.class'",
")",
"return",
"temp",
".",
"format",
"(",
"class_name",
"=",
"self",
".",
"c... | 29.227273 | 15.954545 |
def get_question_text(constant):
"""Find a constant by name and return its value.
:param constant: The name of the constant to look for.
:type constant: string
:returns: The value of the constant or red error message.
:rtype: string
"""
if constant in dir(safe.gui.tools.wizard.wizard_strin... | [
"def",
"get_question_text",
"(",
"constant",
")",
":",
"if",
"constant",
"in",
"dir",
"(",
"safe",
".",
"gui",
".",
"tools",
".",
"wizard",
".",
"wizard_strings",
")",
":",
"return",
"getattr",
"(",
"safe",
".",
"gui",
".",
"tools",
".",
"wizard",
".",... | 34.538462 | 20 |
def stop(self, force=False, wait=False):
"""
Terminate all VMs in this cluster and delete its repository.
:param bool force:
remove cluster from storage even if not all nodes could be stopped.
"""
log.debug("Stopping cluster `%s` ...", self.name)
failed = self... | [
"def",
"stop",
"(",
"self",
",",
"force",
"=",
"False",
",",
"wait",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"\"Stopping cluster `%s` ...\"",
",",
"self",
".",
"name",
")",
"failed",
"=",
"self",
".",
"_stop_all_nodes",
"(",
"wait",
")",
"if"... | 36.576923 | 18.961538 |
def update_pos(pos_dict, start_key, nbr=2):
"Update the `pos_dict` by moving all positions after `start_key` by `nbr`."
for key,idx in pos_dict.items():
if str.lower(key) >= str.lower(start_key): pos_dict[key] += nbr
return pos_dict | [
"def",
"update_pos",
"(",
"pos_dict",
",",
"start_key",
",",
"nbr",
"=",
"2",
")",
":",
"for",
"key",
",",
"idx",
"in",
"pos_dict",
".",
"items",
"(",
")",
":",
"if",
"str",
".",
"lower",
"(",
"key",
")",
">=",
"str",
".",
"lower",
"(",
"start_ke... | 49.6 | 19.6 |
def register(self, endpoint, scheme=None, handler=None, **kwargs):
"""Register a handler with this TChannel.
This may be used as a decorator:
.. code-block:: python
app = TChannel(name='bar')
@app.register("hello", "json")
def hello_handler(request, respon... | [
"def",
"register",
"(",
"self",
",",
"endpoint",
",",
"scheme",
"=",
"None",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"endpoint",
"is",
"not",
"None",
",",
"\"endpoint is required\"",
"if",
"endpoint",
"is",
"TChannel",
"... | 35.328358 | 21.835821 |
def pfprint(item, end='\n', file=None):
"""Prints an item.
:param item: The item to print
:param end: String to append to the end of printed output
:param file: File to which output is printed
:rtype: None
Example::
>>> from operator import add
>>> fn = pfreduce(add, initial=... | [
"def",
"pfprint",
"(",
"item",
",",
"end",
"=",
"'\\n'",
",",
"file",
"=",
"None",
")",
":",
"# Can't just make sys.stdout the file argument's default value, because",
"# then we would be capturing the stdout file descriptor, and then",
"# doctest -- which works by redefining sys.std... | 26.32 | 22.28 |
def _get_library_root_key_for_os_path(self, path):
"""Return library root key if path is within library root paths"""
path = os.path.realpath(path)
library_root_key = None
for library_root_key, library_root_path in self._library_root_paths.items():
rel_path = os.path.relpath(... | [
"def",
"_get_library_root_key_for_os_path",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"library_root_key",
"=",
"None",
"for",
"library_root_key",
",",
"library_root_path",
"in",
"self",
".",
"_librar... | 42.666667 | 13.166667 |
def url(ctx):
"""Prints the notebook url for this project.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon notebook url
```
"""
user, project_name = get_project_or_local(ctx.obj.get('project'))
try:
response = PolyaxonClient().project.g... | [
"def",
"url",
"(",
"ctx",
")",
":",
"user",
",",
"project_name",
"=",
"get_project_or_local",
"(",
"ctx",
".",
"obj",
".",
"get",
"(",
"'project'",
")",
")",
"try",
":",
"response",
"=",
"PolyaxonClient",
"(",
")",
".",
"project",
".",
"get_project",
"... | 34.115385 | 28.076923 |
def bedpe(args):
"""
%prog bedpe bedfile
Convert to bedpe format. Use --span to write another bed file that contain
the span of the read pairs.
"""
from jcvi.assembly.coverage import bed_to_bedpe
p = OptionParser(bedpe.__doc__)
p.add_option("--span", default=False, action="store_true",... | [
"def",
"bedpe",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"assembly",
".",
"coverage",
"import",
"bed_to_bedpe",
"p",
"=",
"OptionParser",
"(",
"bedpe",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--span\"",
",",
"default",
"=",
"False",
",",
... | 35.142857 | 18.428571 |
def parse(self, rrstr):
# type: (bytes) -> None
'''
Parse a Rock Ridge Platform Dependent record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexc... | [
"def",
"parse",
"(",
"self",
",",
"rrstr",
")",
":",
"# type: (bytes) -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'PD record already initialized!'",
")",
"(",
"su_len_unused",
",",
"su_entry_version... | 30 | 27.142857 |
def find_expectations(self,
expectation_type=None,
column=None,
expectation_kwargs=None,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
dis... | [
"def",
"find_expectations",
"(",
"self",
",",
"expectation_type",
"=",
"None",
",",
"column",
"=",
"None",
",",
"expectation_kwargs",
"=",
"None",
",",
"discard_result_format_kwargs",
"=",
"True",
",",
"discard_include_configs_kwargs",
"=",
"True",
",",
"discard_cat... | 47.617647 | 26.264706 |
def handleEvent(self, eventObj):
"""This method should be called every time through the main loop.
Returns:
False - if no event happens.
True - if the user clicks the animation to start it playing.
"""
if not self.visible:
return
if n... | [
"def",
"handleEvent",
"(",
"self",
",",
"eventObj",
")",
":",
"if",
"not",
"self",
".",
"visible",
":",
"return",
"if",
"not",
"self",
".",
"isEnabled",
":",
"return",
"False",
"if",
"eventObj",
".",
"type",
"!=",
"MOUSEBUTTONDOWN",
":",
"# The animation o... | 32.833333 | 21.5 |
def save(df, path):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output tfrecord file.
"""
if os.environ.get('TENSORPACK_COMPATIBLE_SERIALIZE', 'msgpack') == 'msgpack':
def _dumps(dp):
return dumps(dp)
else:
... | [
"def",
"save",
"(",
"df",
",",
"path",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'TENSORPACK_COMPATIBLE_SERIALIZE'",
",",
"'msgpack'",
")",
"==",
"'msgpack'",
":",
"def",
"_dumps",
"(",
"dp",
")",
":",
"return",
"dumps",
"(",
"dp",
")",
... | 33.5 | 16.166667 |
def select_random_ports(n):
"""Selects and return n random ports that are available."""
ports = []
for i in xrange(n):
sock = socket.socket()
sock.bind(('', 0))
while sock.getsockname()[1] in _random_ports:
sock.close()
sock = socket.socket()
sock.... | [
"def",
"select_random_ports",
"(",
"n",
")",
":",
"ports",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
")",
"sock",
".",
"bind",
"(",
"(",
"''",
",",
"0",
")",
")",
"while",
"sock",
... | 30.117647 | 12.764706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.