text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def webhelp(i):
"""
Input: { from access function }
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
a=i.get('repo_uoa','')
m=i.get('module_uoa... | [
"def",
"webhelp",
"(",
"i",
")",
":",
"a",
"=",
"i",
".",
"get",
"(",
"'repo_uoa'",
",",
"''",
")",
"m",
"=",
"i",
".",
"get",
"(",
"'module_uoa'",
",",
"''",
")",
"duoa",
"=",
"i",
".",
"get",
"(",
"'data_uoa'",
",",
"''",
")",
"url",
"=",
... | 20.697674 | 0.04721 |
def add_note(path, filename="note.txt"):
"""Opens a txt file at the given path where user can add and save notes.
Args:
path (str): Directory where note will be saved.
filename (str): Name of note. Defaults to "note.txt"
"""
path = os.path.expanduser(path)
assert os.path.isdir(path)... | [
"def",
"add_note",
"(",
"path",
",",
"filename",
"=",
"\"note.txt\"",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"assert",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
",",
"\"{} is not a valid directory.\"",
"."... | 31.181818 | 0.001414 |
def proj4_to_epsg(projection):
"""Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails"""
def make_definition(value):
return {x.strip().lower() for x in value.split('+') if x}
# Use the EPSG in the definition if available
match = EPSG_RE.search(pro... | [
"def",
"proj4_to_epsg",
"(",
"projection",
")",
":",
"def",
"make_definition",
"(",
"value",
")",
":",
"return",
"{",
"x",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"for",
"x",
"in",
"value",
".",
"split",
"(",
"'+'",
")",
"if",
"x",
"}",
"... | 41.125 | 0.00198 |
def get_user_info(twitter_user):
"""
An example of using the query_user_info method
:param twitter_user: the twitter user to capture user data
:return: twitter_user_data: returns a dictionary of twitter user data
"""
user_info = query_user_info(user=twitter_user)
twitter_user_data = {}
t... | [
"def",
"get_user_info",
"(",
"twitter_user",
")",
":",
"user_info",
"=",
"query_user_info",
"(",
"user",
"=",
"twitter_user",
")",
"twitter_user_data",
"=",
"{",
"}",
"twitter_user_data",
"[",
"\"user\"",
"]",
"=",
"user_info",
".",
"user",
"twitter_user_data",
... | 42.857143 | 0.001087 |
def _maketicks_selected(self, plt, branches):
"""
utility private method to add ticks to a band structure with selected branches
"""
ticks = self.get_ticks()
distance = []
label = []
rm_elems = []
for i in range(1, len(ticks['distance'])):
if t... | [
"def",
"_maketicks_selected",
"(",
"self",
",",
"plt",
",",
"branches",
")",
":",
"ticks",
"=",
"self",
".",
"get_ticks",
"(",
")",
"distance",
"=",
"[",
"]",
"label",
"=",
"[",
"]",
"rm_elems",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
... | 42.214953 | 0.001947 |
def on_start_scene(self, event: StartScene, signal: Callable[[Any], None]):
"""
Start a new scene. The current scene pauses.
"""
self.pause_scene()
self.start_scene(event.new_scene, event.kwargs) | [
"def",
"on_start_scene",
"(",
"self",
",",
"event",
":",
"StartScene",
",",
"signal",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"None",
"]",
")",
":",
"self",
".",
"pause_scene",
"(",
")",
"self",
".",
"start_scene",
"(",
"event",
".",
"new_scene",
... | 38.333333 | 0.008511 |
def _dnsname_to_stdlib(name):
"""
Converts a dNSName SubjectAlternativeName field to the form used by the
standard library on the given Python version.
Cryptography produces a dNSName as a unicode string that was idna-decoded
from ASCII bytes. We need to idna-encode that string to get it back, and
... | [
"def",
"_dnsname_to_stdlib",
"(",
"name",
")",
":",
"def",
"idna_encode",
"(",
"name",
")",
":",
"\"\"\"\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoi... | 37.027778 | 0.000731 |
def set_items(self, items):
""" Defer until later so the view is only updated after all items
are added.
"""
self._pending_view_refreshes +=1
timed_call(self._pending_timeout, self._refresh_layout) | [
"def",
"set_items",
"(",
"self",
",",
"items",
")",
":",
"self",
".",
"_pending_view_refreshes",
"+=",
"1",
"timed_call",
"(",
"self",
".",
"_pending_timeout",
",",
"self",
".",
"_refresh_layout",
")"
] | 34.428571 | 0.020243 |
def install_modules(wip):
"""Install the plugin modules"""
def install_module(hfos_module):
"""Install a single module via setuptools"""
try:
setup = Popen(
[
sys.executable,
'setup.py',
'develop'
... | [
"def",
"install_modules",
"(",
"wip",
")",
":",
"def",
"install_module",
"(",
"hfos_module",
")",
":",
"\"\"\"Install a single module via setuptools\"\"\"",
"try",
":",
"setup",
"=",
"Popen",
"(",
"[",
"sys",
".",
"executable",
",",
"'setup.py'",
",",
"'develop'",... | 25.818182 | 0.001507 |
def get_container_file_download_url(cluster, environ, topology, container,
path, role=None):
'''
:param cluster:
:param environ:
:param topology:
:param container:
:param path:
:param role:
:return:
'''
params = dict(
cluster=cluster,
environ=environ,
... | [
"def",
"get_container_file_download_url",
"(",
"cluster",
",",
"environ",
",",
"topology",
",",
"container",
",",
"path",
",",
"role",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"cluster",
"=",
"cluster",
",",
"environ",
"=",
"environ",
",",
"topol... | 24.153846 | 0.01072 |
def best_buy_2(self):
""" 量縮價不跌
:rtype: bool
"""
result = self.data.value[-1] < self.data.value[-2] and \
self.data.price[-1] > self.data.price[-2]
return result | [
"def",
"best_buy_2",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"data",
".",
"value",
"[",
"-",
"1",
"]",
"<",
"self",
".",
"data",
".",
"value",
"[",
"-",
"2",
"]",
"and",
"self",
".",
"data",
".",
"price",
"[",
"-",
"1",
"]",
">",
... | 27 | 0.013453 |
def _get_arch():
"""
Determines the current processor architecture.
@rtype: str
@return:
On error, returns:
- L{ARCH_UNKNOWN} (C{"unknown"}) meaning the architecture could not be detected or is not known to WinAppDbg.
On success, returns one of the following values:
... | [
"def",
"_get_arch",
"(",
")",
":",
"try",
":",
"si",
"=",
"GetNativeSystemInfo",
"(",
")",
"except",
"Exception",
":",
"si",
"=",
"GetSystemInfo",
"(",
")",
"try",
":",
"return",
"_arch_map",
"[",
"si",
".",
"id",
".",
"w",
".",
"wProcessorArchitecture",... | 42.595238 | 0.002186 |
def ASR_C(value, amount, width):
"""
The ARM ASR_C (arithmetic shift right with carry) operation.
:param value: Value to shift
:type value: int or long or BitVec
:param int amount: How many bits to shift it.
:param int width: Width of the value
:return: Resultant value and carry result
... | [
"def",
"ASR_C",
"(",
"value",
",",
"amount",
",",
"width",
")",
":",
"assert",
"amount",
"<=",
"width",
"assert",
"amount",
">",
"0",
"assert",
"amount",
"+",
"width",
"<=",
"width",
"*",
"2",
"value",
"=",
"Operators",
".",
"SEXTEND",
"(",
"value",
... | 31.888889 | 0.001692 |
def addAPK(self, filename, data):
"""
Add an APK file to the Session and run analysis on it.
:param filename: (file)name of APK file
:param data: binary data of the APK file
:return: a tuple of SHA256 Checksum and APK Object
"""
digest = hashlib.sha256(data).hexd... | [
"def",
"addAPK",
"(",
"self",
",",
"filename",
",",
"data",
")",
":",
"digest",
"=",
"hashlib",
".",
"sha256",
"(",
"data",
")",
".",
"hexdigest",
"(",
")",
"log",
".",
"debug",
"(",
"\"add APK:%s\"",
"%",
"digest",
")",
"apk",
"=",
"APK",
"(",
"da... | 32.666667 | 0.002478 |
def connect(self):
"""connect to the various databases, the credientals and settings of which are found in the sherlock settings file
**Return:**
- ``transientsDbConn`` -- the database hosting the transient source data
- ``cataloguesDbConn`` -- connection to the database hosting... | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``get`` method'",
")",
"transientSettings",
"=",
"self",
".",
"settings",
"[",
"\"database settings\"",
"]",
"[",
"\"transients\"",
"]",
"catalogueSettings",
"=",
"sel... | 36.033708 | 0.001821 |
def ODP(CASRN, AvailableMethods=False, Method=None):
r'''This function handles the retrieval of a chemical's Ozone Depletion
Potential, relative to CFC-11 (trichlorofluoromethane). Lookup is based on
CASRNs. Will automatically select a data source to use if no Method is
provided; returns None if the dat... | [
"def",
"ODP",
"(",
"CASRN",
",",
"AvailableMethods",
"=",
"False",
",",
"Method",
"=",
"None",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"if",
"CASRN",
"in",
"ODP_data",
".",
"index",
":",
"if",
"not",
"pd",
".",
"is... | 40.737288 | 0.000812 |
def search_group_by_id(self, groupID) -> Group:
""" searches a group by given id
Args:
groupID(str): groupID the group to search for
Returns
the group object or None if it couldn't find a group
"""
for g in self.groups:
... | [
"def",
"search_group_by_id",
"(",
"self",
",",
"groupID",
")",
"->",
"Group",
":",
"for",
"g",
"in",
"self",
".",
"groups",
":",
"if",
"g",
".",
"id",
"==",
"groupID",
":",
"return",
"g",
"return",
"None"
] | 28.923077 | 0.010309 |
def occurs_in_type(v, type2):
"""Checks whether a type variable occurs in a type expression.
Note: Must be called with v pre-pruned
Args:
v: The TypeVariable to be tested for
type2: The type in which to search
Returns:
True if v occurs in type2, otherwise False
"""
pr... | [
"def",
"occurs_in_type",
"(",
"v",
",",
"type2",
")",
":",
"pruned_type2",
"=",
"prune",
"(",
"type2",
")",
"if",
"pruned_type2",
"==",
"v",
":",
"return",
"True",
"elif",
"isinstance",
"(",
"pruned_type2",
",",
"TypeOperator",
")",
":",
"return",
"occurs_... | 27.111111 | 0.00198 |
def ac_decode(longval, nbits, probs):
"""Decode the number to a string using the given statistics.
This is a wrapper for :py:meth:`Arithmetic.decode`.
Parameters
----------
longval : int
The first part of an encoded tuple from ac_encode
nbits : int
The second part of an encoded... | [
"def",
"ac_decode",
"(",
"longval",
",",
"nbits",
",",
"probs",
")",
":",
"coder",
"=",
"Arithmetic",
"(",
")",
"coder",
".",
"set_probs",
"(",
"probs",
")",
"return",
"coder",
".",
"decode",
"(",
"longval",
",",
"nbits",
")"
] | 24.733333 | 0.001297 |
def summarize_results(self, individual_results=False):
"""
Prints a summarized table of results from replicate runs, or,
if individual_result=True, then returns a list of separate
dataframes for each replicate run.
"""
## return results depending on algorithm
... | [
"def",
"summarize_results",
"(",
"self",
",",
"individual_results",
"=",
"False",
")",
":",
"## return results depending on algorithm",
"## algorithm 00",
"if",
"(",
"not",
"self",
".",
"params",
".",
"infer_delimit",
")",
"&",
"(",
"not",
"self",
".",
"params",
... | 39.925926 | 0.011775 |
def bovy_ars(domain,isDomainFinite,abcissae,hx,hpx,nsamples=1,
hxparams=(),maxn=100):
"""bovy_ars: Implementation of the Adaptive-Rejection Sampling
algorithm by Gilks & Wild (1992): Adaptive Rejection Sampling
for Gibbs Sampling, Applied Statistics, 41, 337
Based on Wild & Gilks (1993), Al... | [
"def",
"bovy_ars",
"(",
"domain",
",",
"isDomainFinite",
",",
"abcissae",
",",
"hx",
",",
"hpx",
",",
"nsamples",
"=",
"1",
",",
"hxparams",
"=",
"(",
")",
",",
"maxn",
"=",
"100",
")",
":",
"#First set-up the upper and lower hulls",
"hull",
"=",
"setup_hu... | 34.291667 | 0.017129 |
def VarCircle(XY, Par): # must have at least 4 sets of xy points or else division by zero occurs
"""
computing the sample variance of distances from data points (XY) to the circle Par = [a b R]
"""
if type(XY) != numpy.ndarray:
XY = numpy.array(XY)
n = len(XY)
if n < 4:
raise Wa... | [
"def",
"VarCircle",
"(",
"XY",
",",
"Par",
")",
":",
"# must have at least 4 sets of xy points or else division by zero occurs",
"if",
"type",
"(",
"XY",
")",
"!=",
"numpy",
".",
"ndarray",
":",
"XY",
"=",
"numpy",
".",
"array",
"(",
"XY",
")",
"n",
"=",
"le... | 40 | 0.012216 |
def _add_grid_attributes(self, ds):
"""Add model grid attributes to a dataset"""
for name_int, names_ext in self._grid_attrs.items():
ds_coord_name = set(names_ext).intersection(set(ds.coords) |
set(ds.data_vars))
model_attr... | [
"def",
"_add_grid_attributes",
"(",
"self",
",",
"ds",
")",
":",
"for",
"name_int",
",",
"names_ext",
"in",
"self",
".",
"_grid_attrs",
".",
"items",
"(",
")",
":",
"ds_coord_name",
"=",
"set",
"(",
"names_ext",
")",
".",
"intersection",
"(",
"set",
"(",... | 52.914286 | 0.00106 |
def t_filelist(self, s):
r' @\w+'
self.rv.append(Token(type='FILELIST', attr=s[1:])) | [
"def",
"t_filelist",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"rv",
".",
"append",
"(",
"Token",
"(",
"type",
"=",
"'FILELIST'",
",",
"attr",
"=",
"s",
"[",
"1",
":",
"]",
")",
")"
] | 33.333333 | 0.019608 |
def unsubscribe_from_chat(
self,
subscriber: Callable[[events.ChatMessageWasReceived], None],
) -> None:
"""
Not thread-safe.
"""
self._chat_subscribers.remove(subscriber) | [
"def",
"unsubscribe_from_chat",
"(",
"self",
",",
"subscriber",
":",
"Callable",
"[",
"[",
"events",
".",
"ChatMessageWasReceived",
"]",
",",
"None",
"]",
",",
")",
"->",
"None",
":",
"self",
".",
"_chat_subscribers",
".",
"remove",
"(",
"subscriber",
")"
] | 24 | 0.013393 |
def getOutput(self):
"""
Returns the combined output of stdout and stderr
"""
output = self.stdout
if self.stdout:
output += '\r\n'
output += self.stderr
return output | [
"def",
"getOutput",
"(",
"self",
")",
":",
"output",
"=",
"self",
".",
"stdout",
"if",
"self",
".",
"stdout",
":",
"output",
"+=",
"'\\r\\n'",
"output",
"+=",
"self",
".",
"stderr",
"return",
"output"
] | 25.222222 | 0.008511 |
def visit_and_update_expressions(self, visitor_fn):
"""Create an updated version (if needed) of the Filter via the visitor pattern."""
new_predicate = self.predicate.visit_and_update(visitor_fn)
if new_predicate is not self.predicate:
return Filter(new_predicate)
else:
... | [
"def",
"visit_and_update_expressions",
"(",
"self",
",",
"visitor_fn",
")",
":",
"new_predicate",
"=",
"self",
".",
"predicate",
".",
"visit_and_update",
"(",
"visitor_fn",
")",
"if",
"new_predicate",
"is",
"not",
"self",
".",
"predicate",
":",
"return",
"Filter... | 47.285714 | 0.008902 |
def clean_worksheet(wks, gfile_id, wks_name, credentials):
"""DOCS..."""
values = wks.get_all_values()
if values:
df_ = pd.DataFrame(index=range(len(values)),
columns=range(len(values[0])))
df_ = df_.fillna('')
wks = upload(df_, gfile_id, wks_name=wks_name... | [
"def",
"clean_worksheet",
"(",
"wks",
",",
"gfile_id",
",",
"wks_name",
",",
"credentials",
")",
":",
"values",
"=",
"wks",
".",
"get_all_values",
"(",
")",
"if",
"values",
":",
"df_",
"=",
"pd",
".",
"DataFrame",
"(",
"index",
"=",
"range",
"(",
"len"... | 36.583333 | 0.002222 |
def move(name, target, **kwargs):
'''
Move scheduled job to another minion or minions.
CLI Example:
.. code-block:: bash
salt '*' schedule.move jobname target
'''
ret = {'comment': [],
'result': True}
if not name:
ret['comment'] = 'Job name is required.'
... | [
"def",
"move",
"(",
"name",
",",
"target",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'comment'",
":",
"[",
"]",
",",
"'result'",
":",
"True",
"}",
"if",
"not",
"name",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Job name is required.'",
"r... | 30.75 | 0.001969 |
def shutdown(pidfile, signalnb=None, frame=None):
"""Clean up pidfile upon shutdown.
Notice:
We should register this function as signal handler for the following
termination signals:
SIGHUP
SIGTERM
SIGABRT
SIGINT
Arguments:
pidfile (s... | [
"def",
"shutdown",
"(",
"pidfile",
",",
"signalnb",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"log",
".",
"info",
"(",
"\"received %s at %s\"",
",",
"signalnb",
",",
"frame",
")",... | 30.333333 | 0.001332 |
def glm(self, data: ['SASdata', str] = None,
absorb: str = None,
by: str = None,
cls: [str, list] = None,
contrast: str = None,
estimate: str = None,
freq: str = None,
id: str = None,
lsmeans: str = None,
manova:... | [
"def",
"glm",
"(",
"self",
",",
"data",
":",
"[",
"'SASdata'",
",",
"str",
"]",
"=",
"None",
",",
"absorb",
":",
"str",
"=",
"None",
",",
"by",
":",
"str",
"=",
"None",
",",
"cls",
":",
"[",
"str",
",",
"list",
"]",
"=",
"None",
",",
"contras... | 52.085106 | 0.010425 |
def parse_description():
"""
Parse the description in the README file
pandoc --from=markdown --to=rst --output=README.rst README.md
CommandLine:
python -c "import setup; print(setup.parse_description())"
"""
from os.path import dirname, join, exists
readme_fpath = join(dirname(__fi... | [
"def",
"parse_description",
"(",
")",
":",
"from",
"os",
".",
"path",
"import",
"dirname",
",",
"join",
",",
"exists",
"readme_fpath",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"'README.rst'",
")",
"# This breaks on pip install, so check that it exis... | 31.052632 | 0.001645 |
def schedule_host_downtime(self, host, start_time, end_time, fixed,
trigger_id, duration, author, comment):
"""Schedule a host downtime
Format of the line that triggers function call::
SCHEDULE_HOST_DOWNTIME;<host_name>;<start_time>;<end_time>;<fixed>;
<tr... | [
"def",
"schedule_host_downtime",
"(",
"self",
",",
"host",
",",
"start_time",
",",
"end_time",
",",
"fixed",
",",
"trigger_id",
",",
"duration",
",",
"author",
",",
"comment",
")",
":",
"data",
"=",
"{",
"'ref'",
":",
"host",
".",
"uuid",
",",
"'ref_type... | 41.394737 | 0.002484 |
def vMh2_to_m2Lambda(v, Mh2, C, scale_high):
"""Function to numerically determine the parameters of the Higgs potential
given the physical Higgs VEV and mass."""
if C['phi'] == 0 and C['phiBox'] == 0 and C['phiD'] == 0:
return _vMh2_to_m2Lambda_SM(v, Mh2)
else:
def f0(x): # we want the ... | [
"def",
"vMh2_to_m2Lambda",
"(",
"v",
",",
"Mh2",
",",
"C",
",",
"scale_high",
")",
":",
"if",
"C",
"[",
"'phi'",
"]",
"==",
"0",
"and",
"C",
"[",
"'phiBox'",
"]",
"==",
"0",
"and",
"C",
"[",
"'phiD'",
"]",
"==",
"0",
":",
"return",
"_vMh2_to_m2La... | 48.222222 | 0.00113 |
def read_las(source, closefd=True):
""" Entry point for reading las data in pylas
Reads the whole file into memory.
>>> las = read_las("pylastests/simple.las")
>>> las.classification
array([1, 1, 1, ..., 1, 1, 1], dtype=uint8)
Parameters
----------
source : str or io.BytesIO
T... | [
"def",
"read_las",
"(",
"source",
",",
"closefd",
"=",
"True",
")",
":",
"with",
"open_las",
"(",
"source",
",",
"closefd",
"=",
"closefd",
")",
"as",
"reader",
":",
"return",
"reader",
".",
"read",
"(",
")"
] | 26.230769 | 0.001414 |
def do_scan_range(self, line):
"""Do an ad-hoc scan of a range of points (group 1, variation 2, indexes 0-3). Command syntax is: scan_range"""
self.application.master.ScanRange(opendnp3.GroupVariationID(1, 2), 0, 3, opendnp3.TaskConfig().Default()) | [
"def",
"do_scan_range",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"application",
".",
"master",
".",
"ScanRange",
"(",
"opendnp3",
".",
"GroupVariationID",
"(",
"1",
",",
"2",
")",
",",
"0",
",",
"3",
",",
"opendnp3",
".",
"TaskConfig",
"(",
"... | 87.333333 | 0.015152 |
def iter_source_code(paths, config, skipped):
"""Iterate over all Python source files defined in paths."""
for path in paths:
if os.path.isdir(path):
if should_skip(path, config, os.getcwd()):
skipped.append(path)
continue
for dirpath, dirnames, f... | [
"def",
"iter_source_code",
"(",
"paths",
",",
"config",
",",
"skipped",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"if",
"should_skip",
"(",
"path",
",",
"config",
",",
"os",
".",
"get... | 42.428571 | 0.001098 |
def extract_round_trips(transactions,
portfolio_value=None):
"""Group transactions into "round trips". First, transactions are
grouped by day and directionality. Then, long and short
transactions are matched to create round-trip round_trips for which
PnL, duration and returns are... | [
"def",
"extract_round_trips",
"(",
"transactions",
",",
"portfolio_value",
"=",
"None",
")",
":",
"transactions",
"=",
"_groupby_consecutive",
"(",
"transactions",
")",
"roundtrips",
"=",
"[",
"]",
"for",
"sym",
",",
"trans_sym",
"in",
"transactions",
".",
"grou... | 41.528455 | 0.000191 |
def hamm_gen(self,j):
"""
Generates parity check matrix (H) and generator
matrix (G).
Parameters
----------
j: Number of Hamming code parity bits with n = 2^j-1 and k = n-j
returns
-------
G: Systematic generator matrix with left... | [
"def",
"hamm_gen",
"(",
"self",
",",
"j",
")",
":",
"if",
"(",
"j",
"<",
"3",
")",
":",
"raise",
"ValueError",
"(",
"'j must be > 2'",
")",
"# calculate codeword length",
"n",
"=",
"2",
"**",
"j",
"-",
"1",
"# calculate source bit length",
"k",
"=",
"n",... | 27.484375 | 0.022503 |
def __unhook_dll(self, event):
"""
Unhook the requested API calls (in self.apiHooks).
This method is called automatically whenever a DLL is unloaded.
"""
debug = event.debug
pid = event.get_pid()
for hook_api_stub in self.__get_hooks_for_dll(event):
... | [
"def",
"__unhook_dll",
"(",
"self",
",",
"event",
")",
":",
"debug",
"=",
"event",
".",
"debug",
"pid",
"=",
"event",
".",
"get_pid",
"(",
")",
"for",
"hook_api_stub",
"in",
"self",
".",
"__get_hooks_for_dll",
"(",
"event",
")",
":",
"hook_api_stub",
"."... | 34.4 | 0.008499 |
def compute_settings(args, rc_settings):
"""
Merge arguments and rc_settings.
"""
settings = {}
for key, value in args.items():
if key in ['reverse', 'opposite']:
settings[key] = value ^ rc_settings.get(key, False)
else:
settings[key] = value or rc_settings.ge... | [
"def",
"compute_settings",
"(",
"args",
",",
"rc_settings",
")",
":",
"settings",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"args",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"[",
"'reverse'",
",",
"'opposite'",
"]",
":",
"settings",
"[",... | 28.785714 | 0.002404 |
def _find_devices(serial=None):
"""
Returns a list of CrazyRadio devices currently connected to the computer
"""
ret = []
if pyusb1:
for d in usb.core.find(idVendor=0x1915, idProduct=0x7777, find_all=1,
backend=pyusb_backend):
if serial is not None... | [
"def",
"_find_devices",
"(",
"serial",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"pyusb1",
":",
"for",
"d",
"in",
"usb",
".",
"core",
".",
"find",
"(",
"idVendor",
"=",
"0x1915",
",",
"idProduct",
"=",
"0x7777",
",",
"find_all",
"=",
"1",
... | 32.608696 | 0.001295 |
def quote(src_string, return_expr=False):
"""Go from source code to AST nodes.
This function returns a tree without enclosing `Module` or `Expr` nodes.
Args:
src_string: The source code to parse.
return_expr: Whether or not to return a containing expression. This can be
set to `True` if the resu... | [
"def",
"quote",
"(",
"src_string",
",",
"return_expr",
"=",
"False",
")",
":",
"node",
"=",
"parse_string",
"(",
"src_string",
")",
"body",
"=",
"node",
".",
"body",
"if",
"len",
"(",
"body",
")",
"==",
"1",
":",
"if",
"isinstance",
"(",
"body",
"[",... | 25.875 | 0.013975 |
def load_MACHO(macho_id):
"""lightcurve of 2 bands (R, B) from the MACHO survey.
Notes
-----
The files are gathered from the original FATS project tutorial:
https://github.com/isadoranun/tsfeat
"""
tarfname = "{}.tar.bz2".format(macho_id)
tarpath = os.path.join(DATA_PATH, tarfname)
... | [
"def",
"load_MACHO",
"(",
"macho_id",
")",
":",
"tarfname",
"=",
"\"{}.tar.bz2\"",
".",
"format",
"(",
"macho_id",
")",
"tarpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"DATA_PATH",
",",
"tarfname",
")",
"rpath",
"=",
"\"{}.R.mjd\"",
".",
"format",
"... | 28.833333 | 0.000932 |
def create_database(dbpath, schema='', overwrite=True):
"""
Create a new database at the given dbpath
Parameters
----------
dbpath: str
The full path for the new database, including the filename and .db file extension.
schema: str
The path to the .sql schema for the database
... | [
"def",
"create_database",
"(",
"dbpath",
",",
"schema",
"=",
"''",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"dbpath",
".",
"endswith",
"(",
"'.db'",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"dbpath",
")",
"and",
"overwrite",
":",
... | 39.823529 | 0.008652 |
def url_for(self, attr=None, filter_value=None,
service_type=None, endpoint_type="publicURL",
service_name=None, volume_service_name=None):
"""Fetches the public URL from the given service for
a particular endpoint attribute. If none given, returns
the first. See tests fo... | [
"def",
"url_for",
"(",
"self",
",",
"attr",
"=",
"None",
",",
"filter_value",
"=",
"None",
",",
"service_type",
"=",
"None",
",",
"endpoint_type",
"=",
"\"publicURL\"",
",",
"service_name",
"=",
"None",
",",
"volume_service_name",
"=",
"None",
")",
":",
"m... | 43.928571 | 0.001591 |
def rebuild_tree(self, request):
'''
Rebuilds the tree and clears the cache.
'''
self.model.objects.rebuild()
self.message_user(request, _('Menu Tree Rebuilt.'))
return self.clean_cache(request) | [
"def",
"rebuild_tree",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"model",
".",
"objects",
".",
"rebuild",
"(",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"'Menu Tree Rebuilt.'",
")",
")",
"return",
"self",
".",
"clean_cach... | 33.714286 | 0.008264 |
def quote_xml(inStr):
"Escape markup chars, but do not modify CDATA sections."
if not inStr:
return ''
s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
s2 = ''
pos = 0
matchobjects = CDATA_pattern_.finditer(s1)
for mo in matchobjects:
s3 = s1[pos:mo.start()]
... | [
"def",
"quote_xml",
"(",
"inStr",
")",
":",
"if",
"not",
"inStr",
":",
"return",
"''",
"s1",
"=",
"(",
"isinstance",
"(",
"inStr",
",",
"BaseStrType_",
")",
"and",
"inStr",
"or",
"'%s'",
"%",
"inStr",
")",
"s2",
"=",
"''",
"pos",
"=",
"0",
"matchob... | 28.5 | 0.002123 |
def _resize_panels(self):
"""
Resize panels
"""
self.theme.setup_figure(self.figure)
self.facet.spaceout_and_resize_panels() | [
"def",
"_resize_panels",
"(",
"self",
")",
":",
"self",
".",
"theme",
".",
"setup_figure",
"(",
"self",
".",
"figure",
")",
"self",
".",
"facet",
".",
"spaceout_and_resize_panels",
"(",
")"
] | 26.5 | 0.012195 |
def time_track(self, absolute_time=False, accuracy='ns'):
"""Return an array of time or the independent variable for this channel
This depends on the object having the wf_increment
and wf_start_offset properties defined.
Note that wf_start_offset is usually zero for time-series data.
... | [
"def",
"time_track",
"(",
"self",
",",
"absolute_time",
"=",
"False",
",",
"accuracy",
"=",
"'ns'",
")",
":",
"try",
":",
"increment",
"=",
"self",
".",
"property",
"(",
"'wf_increment'",
")",
"offset",
"=",
"self",
".",
"property",
"(",
"'wf_start_offset'... | 36.967742 | 0.00085 |
def render_transparent_chit():
""" Render a transparent chit for external, sized images """
if request.if_none_match.contains('chit') or request.if_modified_since:
return 'Not modified', 304
out_bytes = base64.b64decode(
"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
retur... | [
"def",
"render_transparent_chit",
"(",
")",
":",
"if",
"request",
".",
"if_none_match",
".",
"contains",
"(",
"'chit'",
")",
"or",
"request",
".",
"if_modified_since",
":",
"return",
"'Not modified'",
",",
"304",
"out_bytes",
"=",
"base64",
".",
"b64decode",
"... | 44.4 | 0.002208 |
def open_attributes_file(self):
'''
Called during initialization. Only needs to be explicitly
called if save_and_close_attributes is explicitly called
beforehand.
'''
if not self.saveable():
raise AttributeError("Cannot open attribute file without a valid file... | [
"def",
"open_attributes_file",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"saveable",
"(",
")",
":",
"raise",
"AttributeError",
"(",
"\"Cannot open attribute file without a valid file\"",
")",
"if",
"self",
".",
"_db_closed",
":",
"self",
".",
"_fd",
"=",
... | 47.571429 | 0.010309 |
def validate(self):
"""Validate workflow object.
This method currently validates the workflow object with the use of
cwltool. It writes the workflow to a tmp CWL file, reads it, validates
it and removes the tmp file again. By default, the workflow is written
to file using absolu... | [
"def",
"validate",
"(",
"self",
")",
":",
"# define tmpfile",
"(",
"fd",
",",
"tmpfile",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"os",
".",
"close",
"(",
"fd",
")",
"try",
":",
"# save workflow object to tmpfile,",
"# do not recursively call validate fun... | 39.65 | 0.002463 |
async def sonar_config(self, trigger_pin, echo_pin, cb=None,
ping_interval=50, max_distance=200, cb_type=None):
"""
Configure the pins,ping interval and maximum distance for an HC-SR04
type device.
Single pin configuration may be used. To do so, set both the tr... | [
"async",
"def",
"sonar_config",
"(",
"self",
",",
"trigger_pin",
",",
"echo_pin",
",",
"cb",
"=",
"None",
",",
"ping_interval",
"=",
"50",
",",
"max_distance",
"=",
"200",
",",
"cb_type",
"=",
"None",
")",
":",
"# if there is an entry for the trigger pin in exis... | 44.039216 | 0.001307 |
def list(self, limit=None, marker=None, return_raw=False, other_keys=None):
"""
Returns a list of resource objects. Pagination is supported through the
optional 'marker' and 'limit' parameters.
Some APIs do not follow the typical pattern in their responses, and the
BaseManager s... | [
"def",
"list",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"return_raw",
"=",
"False",
",",
"other_keys",
"=",
"None",
")",
":",
"uri",
"=",
"\"/%s\"",
"%",
"self",
".",
"uri_base",
"pagination_items",
"=",
"[",
"]",
"if"... | 51.551724 | 0.001313 |
def cat_extract(tar, member, targetpath):
"""Extract a regular file member using cat for async-like I/O
Mostly adapted from tarfile.py.
"""
assert member.isreg()
# Fetch the TarInfo object for the given name and build the
# destination pathname, replacing forward slashes to platform
# spe... | [
"def",
"cat_extract",
"(",
"tar",
",",
"member",
",",
"targetpath",
")",
":",
"assert",
"member",
".",
"isreg",
"(",
")",
"# Fetch the TarInfo object for the given name and build the",
"# destination pathname, replacing forward slashes to platform",
"# specific separators.",
"t... | 33.047619 | 0.0007 |
def add(self, nick):
"""\
Indicate that the worker with given nick is performing this task
"""
self.data[nick] = ''
self.workers.add(nick) | [
"def",
"add",
"(",
"self",
",",
"nick",
")",
":",
"self",
".",
"data",
"[",
"nick",
"]",
"=",
"''",
"self",
".",
"workers",
".",
"add",
"(",
"nick",
")"
] | 28.833333 | 0.011236 |
def get_device_address(usb_device):
""" Returns the grizzly's internal address value. Returns a negative error value in case of error. """
try:
usb_device.ctrl_transfer(0x21, 0x09, 0x0300, 0, GrizzlyUSB.COMMAND_GET_ADDR)
internal_addr = usb_device.ctrl_transfer(0xa1, 0x01, 0x0301... | [
"def",
"get_device_address",
"(",
"usb_device",
")",
":",
"try",
":",
"usb_device",
".",
"ctrl_transfer",
"(",
"0x21",
",",
"0x09",
",",
"0x0300",
",",
"0",
",",
"GrizzlyUSB",
".",
"COMMAND_GET_ADDR",
")",
"internal_addr",
"=",
"usb_device",
".",
"ctrl_transfe... | 55.25 | 0.011136 |
def has(self, key: str) -> bool:
"""
Returns True is set() has been called for a key. The cached value may be of type 'None'.
:param key:
:return:
"""
if key in self._services:
return True
return False | [
"def",
"has",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"bool",
":",
"if",
"key",
"in",
"self",
".",
"_services",
":",
"return",
"True",
"return",
"False"
] | 29 | 0.011152 |
def serialize(self, null_values=False):
"""
:type null_values bool
:rtype: dict
"""
ret = {}
property_dict = dict(self.__class__.__dict__) # contain view definition defaults
property_dict.update(self.__dict__) # overrides done at runtime
for k in property_dict.keys():
if k[:1] =... | [
"def",
"serialize",
"(",
"self",
",",
"null_values",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"}",
"property_dict",
"=",
"dict",
"(",
"self",
".",
"__class__",
".",
"__dict__",
")",
"# contain view definition defaults",
"property_dict",
".",
"update",
"(",
"... | 30.810811 | 0.011905 |
def is_sub_to_any(self, *super_entities):
"""
Given a list of super entities, return the entities that have super entities that interset with those provided.
"""
if super_entities:
return self.filter(id__in=EntityRelationship.objects.filter(
super_entity__in=s... | [
"def",
"is_sub_to_any",
"(",
"self",
",",
"*",
"super_entities",
")",
":",
"if",
"super_entities",
":",
"return",
"self",
".",
"filter",
"(",
"id__in",
"=",
"EntityRelationship",
".",
"objects",
".",
"filter",
"(",
"super_entity__in",
"=",
"super_entities",
")... | 44.666667 | 0.009756 |
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is f... | [
"def",
"destroy",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"Attempting to delete instance %s\"",
",",
"name",
")",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called wi... | 30.215385 | 0.001972 |
def _parse_option(cls, token):
"""
Parse an option expression.
:param token: The option expression
:type token: str
:rtype: InputOption
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split("... | [
"def",
"_parse_option",
"(",
"cls",
",",
"token",
")",
":",
"description",
"=",
"\"\"",
"validator",
"=",
"None",
"if",
"\" : \"",
"in",
"token",
":",
"token",
",",
"description",
"=",
"tuple",
"(",
"token",
".",
"split",
"(",
"\" : \"",
",",
"2",
")",... | 28.164179 | 0.001024 |
def perf_total(self, value):
"""The perf_total property.
Args:
value (string). the property value.
"""
if value == self._defaults['perfTotal'] and 'perfTotal' in self._values:
del self._values['perfTotal']
else:
self._values['perfTotal... | [
"def",
"perf_total",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'perfTotal'",
"]",
"and",
"'perfTotal'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'perfTotal'",
"]",
"else",
"... | 32.1 | 0.012121 |
def simulation(self, ts_length=90, random_state=None):
"""
Compute a simulated sample path assuming Gaussian shocks.
Parameters
----------
ts_length : scalar(int), optional(default=90)
Number of periods to simulate for
random_state : int or np.random.RandomS... | [
"def",
"simulation",
"(",
"self",
",",
"ts_length",
"=",
"90",
",",
"random_state",
"=",
"None",
")",
":",
"from",
"scipy",
".",
"signal",
"import",
"dlsim",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"sys",
"=",
"self",
".",
"ma_... | 32.724138 | 0.002047 |
def _query(function,
consul_url,
token=None,
method='GET',
api_version='v1',
data=None,
query_params=None):
'''
Consul object method function to construct and execute on the API URL.
:param api_url: The Consul api url.
:param api_ver... | [
"def",
"_query",
"(",
"function",
",",
"consul_url",
",",
"token",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"api_version",
"=",
"'v1'",
",",
"data",
"=",
"None",
",",
"query_params",
"=",
"None",
")",
":",
"if",
"not",
"query_params",
":",
"query... | 28.234375 | 0.00107 |
def EnumerateClassNames(self, namespace=None, ClassName=None,
DeepInheritance=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Enumerate the names of subclasses of a class, or of the top-level
classes in a namespace.
This method perfor... | [
"def",
"EnumerateClassNames",
"(",
"self",
",",
"namespace",
"=",
"None",
",",
"ClassName",
"=",
"None",
",",
"DeepInheritance",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name,line-too-long",
"exc",
"=",
"None",
"classnames",
"=",... | 38.796992 | 0.000756 |
def get_lines_without_comments(filename: str) -> List[str]:
"""
Reads a file, and returns all lines as a list, left- and right-stripping
the lines and removing everything on a line after the first ``#``.
NOTE: does not cope well with quoted ``#`` symbols!
"""
lines = []
with open(filename) a... | [
"def",
"get_lines_without_comments",
"(",
"filename",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"lines",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"parti... | 36.333333 | 0.001789 |
def make_pixel_mask_from_col_row(column, row, default=0, value=1):
'''Generate mask from column and row lists
Parameters
----------
column : iterable, int
List of colums values.
row : iterable, int
List of row values.
default : int
Value of pixels that are not ... | [
"def",
"make_pixel_mask_from_col_row",
"(",
"column",
",",
"row",
",",
"default",
"=",
"0",
",",
"value",
"=",
"1",
")",
":",
"# FE columns and rows start from 1\r",
"col_array",
"=",
"np",
".",
"array",
"(",
"column",
")",
"-",
"1",
"row_array",
"=",
"np",
... | 32.888889 | 0.002188 |
def tkr_vox2ras(img, zooms=None):
'''
tkr_vox2ras(img) yields the FreeSurfer tkr VOX2RAS matrix for the given nibabel image object
img. The img must have a get_shape() method and header member with a get_zooms() method.
tkr_vox2ras(hdr) operates on a nibabel image header object.
tkr_vox2ras(shape,... | [
"def",
"tkr_vox2ras",
"(",
"img",
",",
"zooms",
"=",
"None",
")",
":",
"if",
"zooms",
"is",
"not",
"None",
":",
"# let's assume that they passed shape, zooms",
"shape",
"=",
"img",
"else",
":",
"try",
":",
"img",
"=",
"img",
".",
"header",
"except",
"Excep... | 46.92 | 0.011696 |
def create(self, subject, displayName, issuerToken, expiration, secret):
"""Create a new guest issuer using the provided issuer token.
This function returns a guest issuer with an api access token.
Args:
subject(basestring): Unique and public identifier
displayName(base... | [
"def",
"create",
"(",
"self",
",",
"subject",
",",
"displayName",
",",
"issuerToken",
",",
"expiration",
",",
"secret",
")",
":",
"check_type",
"(",
"subject",
",",
"basestring",
")",
"check_type",
"(",
"displayName",
",",
"basestring",
")",
"check_type",
"(... | 37.255814 | 0.001217 |
def _calc_colour_hist(img):
"""
calculate colour histogram for each region
the size of output histogram will be BINS * COLOUR_CHANNELS(3)
number of bins is 25 as same as [uijlings_ijcv2013_draft.pdf]
extract HSV
"""
BINS = 25
hist = numpy.array([])
for colour_cha... | [
"def",
"_calc_colour_hist",
"(",
"img",
")",
":",
"BINS",
"=",
"25",
"hist",
"=",
"numpy",
".",
"array",
"(",
"[",
"]",
")",
"for",
"colour_channel",
"in",
"(",
"0",
",",
"1",
",",
"2",
")",
":",
"# extracting one colour channel",
"c",
"=",
"img",
"[... | 23.037037 | 0.001543 |
def build_estimator(model_dir, model_type, model_column_fn, inter_op, intra_op, ctx):
"""Build an estimator appropriate for the given model type."""
wide_columns, deep_columns = model_column_fn()
hidden_units = [100, 75, 50, 25]
# Create a tf.estimator.RunConfig to ensure the model is run on CPU, which
# tra... | [
"def",
"build_estimator",
"(",
"model_dir",
",",
"model_type",
",",
"model_column_fn",
",",
"inter_op",
",",
"intra_op",
",",
"ctx",
")",
":",
"wide_columns",
",",
"deep_columns",
"=",
"model_column_fn",
"(",
")",
"hidden_units",
"=",
"[",
"100",
",",
"75",
... | 43.6875 | 0.009797 |
def get_config_parameter_loglevel(config: ConfigParser,
section: str,
param: str,
default: int) -> int:
"""
Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g.
mapping ``'debug'`` to ``logg... | [
"def",
"get_config_parameter_loglevel",
"(",
"config",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"param",
":",
"str",
",",
"default",
":",
"int",
")",
"->",
"int",
":",
"try",
":",
"value",
"=",
"config",
".",
"get",
"(",
"section",
",",
"p... | 35.742857 | 0.000778 |
def get_events_in_both_arrays(events_one, events_two):
"""
Calculates the events that exist in both arrays.
"""
events_one = np.ascontiguousarray(events_one) # change memory alignement for c++ library
events_two = np.ascontiguousarray(events_two) # change memory alignement for c++ library
eve... | [
"def",
"get_events_in_both_arrays",
"(",
"events_one",
",",
"events_two",
")",
":",
"events_one",
"=",
"np",
".",
"ascontiguousarray",
"(",
"events_one",
")",
"# change memory alignement for c++ library",
"events_two",
"=",
"np",
".",
"ascontiguousarray",
"(",
"events_t... | 47.5 | 0.008264 |
def event(self, button):
"""
button has been clicked
"""
# cancel any pending timer
if self.timer:
self.timer.cancel()
if self.last_button != button:
if self.last_button:
# new button clicked process the one before.
... | [
"def",
"event",
"(",
"self",
",",
"button",
")",
":",
"# cancel any pending timer",
"if",
"self",
".",
"timer",
":",
"self",
".",
"timer",
".",
"cancel",
"(",
")",
"if",
"self",
".",
"last_button",
"!=",
"button",
":",
"if",
"self",
".",
"last_button",
... | 35.535714 | 0.001957 |
def render_particles(self):
"""
Render visible particles at each strip position, by modifying
the strip's color list.
"""
for strip_pos in range(self._start, self._end + 1):
blended = COLORS.black
# Render visible emitters
if self.has_e_color... | [
"def",
"render_particles",
"(",
"self",
")",
":",
"for",
"strip_pos",
"in",
"range",
"(",
"self",
".",
"_start",
",",
"self",
".",
"_end",
"+",
"1",
")",
":",
"blended",
"=",
"COLORS",
".",
"black",
"# Render visible emitters",
"if",
"self",
".",
"has_e_... | 36.787879 | 0.001605 |
def default(self, o):
"""
Overriding default method for JSON encoding. This method does two
things: (a) If an object has a to_dict property, return the to_dict
output. (b) If the @module and @class keys are not in the to_dict,
add them to the output automatically. If the object h... | [
"def",
"default",
"(",
"self",
",",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"{",
"\"@module\"",
":",
"\"datetime\"",
",",
"\"@class\"",
":",
"\"datetime\"",
",",
"\"string\"",
":",
"o",
".",
"_... | 40 | 0.001038 |
def put_mapping(self, using=None, **kwargs):
"""
Register specific mapping definition for a specific type.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.put_mapping`` unchanged.
"""
return self._get_connection(using).indices.put_mapping(index... | [
"def",
"put_mapping",
"(",
"self",
",",
"using",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_get_connection",
"(",
"using",
")",
".",
"indices",
".",
"put_mapping",
"(",
"index",
"=",
"self",
".",
"_name",
",",
"*",
"*",
... | 41.875 | 0.008772 |
def head(self, x, y, layers=None, aq=None):
"""Head at `x`, `y`
Returns
-------
h : array length `naq` or `len(layers)`
head in all `layers` (if not `None`), or all layers of aquifer (otherwise)
"""
if aq is None: aq = self.aq.find_a... | [
"def",
"head",
"(",
"self",
",",
"x",
",",
"y",
",",
"layers",
"=",
"None",
",",
"aq",
"=",
"None",
")",
":",
"if",
"aq",
"is",
"None",
":",
"aq",
"=",
"self",
".",
"aq",
".",
"find_aquifer_data",
"(",
"x",
",",
"y",
")",
"rv",
"=",
"self",
... | 28.75 | 0.014737 |
def get_value(self, continuous_future, dt, field):
"""
Retrieve the value at the given coordinates.
Parameters
----------
sid : int
The asset identifier.
dt : pd.Timestamp
The timestamp for the desired data point.
field : string
... | [
"def",
"get_value",
"(",
"self",
",",
"continuous_future",
",",
"dt",
",",
"field",
")",
":",
"rf",
"=",
"self",
".",
"_roll_finders",
"[",
"continuous_future",
".",
"roll_style",
"]",
"sid",
"=",
"(",
"rf",
".",
"get_contract_center",
"(",
"continuous_futur... | 33.766667 | 0.001919 |
def strict_deps_for_target(self, target, predicate=None):
"""Get the dependencies of `target` filtered by `predicate`, accounting for 'strict_deps'.
If 'strict_deps' is on, instead of using the transitive closure of dependencies, targets will
only be able to see their immediate dependencies declared in the... | [
"def",
"strict_deps_for_target",
"(",
"self",
",",
"target",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"_native_build_settings",
".",
"get_strict_deps_value_for_target",
"(",
"target",
")",
":",
"strict_deps",
"=",
"target",
".",
"strict_dependen... | 43.72 | 0.008953 |
def get_peer_creds(self): # LRU cached on per-instance basis, see __init__
"""Return the PID/UID/GID tuple of the peer socket for UNIX sockets.
This function uses SO_PEERCRED to query the UNIX PID, UID, GID
of the peer, which is only available if the bind address is
a UNIX domain socke... | [
"def",
"get_peer_creds",
"(",
"self",
")",
":",
"# LRU cached on per-instance basis, see __init__",
"PEERCRED_STRUCT_DEF",
"=",
"'3i'",
"if",
"IS_WINDOWS",
"or",
"self",
".",
"socket",
".",
"family",
"!=",
"socket",
".",
"AF_UNIX",
":",
"raise",
"NotImplementedError",... | 39.333333 | 0.001103 |
def build_reaction_from_string(self, reaction_str, verbose=True,
fwd_arrow=None, rev_arrow=None,
reversible_arrow=None, term_split="+"):
"""Builds reaction from reaction equation reaction_str using parser
Takes a string and using the... | [
"def",
"build_reaction_from_string",
"(",
"self",
",",
"reaction_str",
",",
"verbose",
"=",
"True",
",",
"fwd_arrow",
"=",
"None",
",",
"rev_arrow",
"=",
"None",
",",
"reversible_arrow",
"=",
"None",
",",
"term_split",
"=",
"\"+\"",
")",
":",
"# set the arrows... | 40.852632 | 0.001006 |
def add_candidate_adapter_ports(self, ports):
"""
Add a list of storage adapter ports to this storage group's candidate
adapter ports list.
This operation only applies to storage groups of type "fcp".
These adapter ports become candidates for use as backing adapters when
... | [
"def",
"add_candidate_adapter_ports",
"(",
"self",
",",
"ports",
")",
":",
"body",
"=",
"{",
"'adapter-port-uris'",
":",
"[",
"p",
".",
"uri",
"for",
"p",
"in",
"ports",
"]",
",",
"}",
"self",
".",
"manager",
".",
"session",
".",
"post",
"(",
"self",
... | 40.77551 | 0.000978 |
def _count_ngrams(self, n=2, method="word", to_lower=True, ignore_space=True):
"""
For documentation, see turicreate.text_analytics.count_ngrams().
..WARNING:: This function is deprecated, and will be removed in future
versions of Turi Create. Please use the `text_analytics.count_words`... | [
"def",
"_count_ngrams",
"(",
"self",
",",
"n",
"=",
"2",
",",
"method",
"=",
"\"word\"",
",",
"to_lower",
"=",
"True",
",",
"ignore_space",
"=",
"True",
")",
":",
"if",
"(",
"self",
".",
"dtype",
"!=",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\... | 38.114286 | 0.008041 |
def get_raw_transaction(self, tx_hash, verbose=True, **kwargs):
""" Returns detailed information associated with a specific transaction hash.
:param tx_hash: transaction hash
:param verbose:
a boolean indicating whether the detailed transaction information should be returned in
... | [
"def",
"get_raw_transaction",
"(",
"self",
",",
"tx_hash",
",",
"verbose",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_call",
"(",
"JSONRPCMethods",
".",
"GET_RAW_TRANSACTION",
".",
"value",
",",
"params",
"=",
"[",
"tx_hash",
... | 44.555556 | 0.008547 |
def permutation_matrix(permutation):
r"""Return orthogonal permutation matrix for permutation tuple
Return an orthogonal permutation matrix :math:`M_\sigma`
for a permutation :math:`\sigma` defined by the image tuple
:math:`(\sigma(1), \sigma(2),\dots \sigma(n))`,
such that
.. math::
... | [
"def",
"permutation_matrix",
"(",
"permutation",
")",
":",
"assert",
"check_permutation",
"(",
"permutation",
")",
"n",
"=",
"len",
"(",
"permutation",
")",
"op_matrix",
"=",
"np_zeros",
"(",
"(",
"n",
",",
"n",
")",
",",
"dtype",
"=",
"int",
")",
"for",... | 26.972973 | 0.000967 |
def is_managed(using=None):
"""
Checks whether the transaction manager is in manual or in auto state.
"""
if using is None:
managed = False
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
if connection.is_managed():
... | [
"def",
"is_managed",
"(",
"using",
"=",
"None",
")",
":",
"if",
"using",
"is",
"None",
":",
"managed",
"=",
"False",
"for",
"using",
"in",
"tldap",
".",
"backend",
".",
"connections",
":",
"connection",
"=",
"tldap",
".",
"backend",
".",
"connections",
... | 33.538462 | 0.002232 |
def get_msg_login(self, username):
"""message for welcome.
"""
account = self.get_account(username)
if account:
account.update_last_login()
account.save()
return 'welcome.' | [
"def",
"get_msg_login",
"(",
"self",
",",
"username",
")",
":",
"account",
"=",
"self",
".",
"get_account",
"(",
"username",
")",
"if",
"account",
":",
"account",
".",
"update_last_login",
"(",
")",
"account",
".",
"save",
"(",
")",
"return",
"'welcome.'"
... | 28.625 | 0.008475 |
def rotate(self, log):
"""Move the current log to a new file with timestamp and create a new empty log file."""
self.write(log, rotate=True)
self.write({}) | [
"def",
"rotate",
"(",
"self",
",",
"log",
")",
":",
"self",
".",
"write",
"(",
"log",
",",
"rotate",
"=",
"True",
")",
"self",
".",
"write",
"(",
"{",
"}",
")"
] | 44 | 0.01676 |
def divrank_scipy(G, alpha=0.25, d=0.85, personalization=None,
max_iter=100, tol=1.0e-6, nstart=None, weight='weight',
dangling=None):
'''
Returns the DivRank (Diverse Rank) of the nodes in the graph.
This code is based on networkx.pagerank_scipy
'''
import scipy.... | [
"def",
"divrank_scipy",
"(",
"G",
",",
"alpha",
"=",
"0.25",
",",
"d",
"=",
"0.85",
",",
"personalization",
"=",
"None",
",",
"max_iter",
"=",
"100",
",",
"tol",
"=",
"1.0e-6",
",",
"nstart",
"=",
"None",
",",
"weight",
"=",
"'weight'",
",",
"danglin... | 32.842105 | 0.001556 |
def store_meta_data(self, copy_path=None):
"""Save meta data of the state machine model to the file system
This method generates a dictionary of the meta data of the state machine and stores it on the filesystem.
:param str copy_path: Optional, if the path is specified, it will be used instead... | [
"def",
"store_meta_data",
"(",
"self",
",",
"copy_path",
"=",
"None",
")",
":",
"if",
"copy_path",
":",
"meta_file_json",
"=",
"os",
".",
"path",
".",
"join",
"(",
"copy_path",
",",
"storage",
".",
"FILE_NAME_META_DATA",
")",
"else",
":",
"meta_file_json",
... | 45.933333 | 0.008535 |
def run(self, *args, **kwargs):
"""
Probe the input tree and print.
"""
b_status = True
d_probe = {}
d_tree = {}
d_stats = {}
str_error = ''
b_timerStart = False
d_test = {}
for k, ... | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"b_status",
"=",
"True",
"d_probe",
"=",
"{",
"}",
"d_tree",
"=",
"{",
"}",
"d_stats",
"=",
"{",
"}",
"str_error",
"=",
"''",
"b_timerStart",
"=",
"False",
"d_test",
... | 35.727273 | 0.021578 |
def diagonalized_iter(size):
r"""
TODO: generalize to more than 2 dimensions to be more like
itertools.product.
CommandLine:
python -m utool.util_alg --exec-diagonalized_iter
python -m utool.util_alg --exec-diagonalized_iter --size=5
Example:
>>> # ENABLE_DOCTEST
>>... | [
"def",
"diagonalized_iter",
"(",
"size",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
"+",
"1",
")",
":",
"for",
"r",
",",
"c",
"in",
"zip",
"(",
"reversed",
"(",
"range",
"(",
"i",
")",
")",
",",
"(",
"range",
"(",
"i",
")",
... | 32.967742 | 0.000951 |
def get_template_names(self):
"""Returns a list of template names to search for when rendering a
a specific flat menu object (making use of self.handle)"""
site = self._contextual_vals.current_site
handle = self.handle
template_names = []
if settings.SITE_SPECIFIC_TEMPLAT... | [
"def",
"get_template_names",
"(",
"self",
")",
":",
"site",
"=",
"self",
".",
"_contextual_vals",
".",
"current_site",
"handle",
"=",
"self",
".",
"handle",
"template_names",
"=",
"[",
"]",
"if",
"settings",
".",
"SITE_SPECIFIC_TEMPLATE_DIRS",
"and",
"site",
"... | 44.657143 | 0.001252 |
def open_file_dialog(windowTitle, wildcard, defaultDir=os.getcwd(), style=None, parent=None):
""" Opens a wx widget file select dialog.
Wild card specifies which kinds of files are allowed.
Style - specifies style of dialog (read wx documentation for information)
"""
if parent == None:
... | [
"def",
"open_file_dialog",
"(",
"windowTitle",
",",
"wildcard",
",",
"defaultDir",
"=",
"os",
".",
"getcwd",
"(",
")",
",",
"style",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"==",
"None",
":",
"app",
"=",
"wx",
".",
"App",
... | 31.190476 | 0.008889 |
def n_parent_paths(self, n):
"""
return parent paths of n levels.
eg: File('a/b/c/d').n_parent_paths(2) == 'b/c'
"""
rv = os.path.relpath(os.path.join(self.path, '..'), os.path.join(self.path, *['..'] * (n+1)))
return rv.replace('\\', '/') | [
"def",
"n_parent_paths",
"(",
"self",
",",
"n",
")",
":",
"rv",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'..'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"p... | 40.142857 | 0.010453 |
def get_host(self):
"""
returns the host computer running this program
"""
import socket
host_name = socket.gethostname()
for h in hosts:
if h['name'] == host_name:
return h['type'], h['name']
return dict(type='Unknown', name=host_nam... | [
"def",
"get_host",
"(",
"self",
")",
":",
"import",
"socket",
"host_name",
"=",
"socket",
".",
"gethostname",
"(",
")",
"for",
"h",
"in",
"hosts",
":",
"if",
"h",
"[",
"'name'",
"]",
"==",
"host_name",
":",
"return",
"h",
"[",
"'type'",
"]",
",",
"... | 31.3 | 0.012422 |
def structureLink(lines):
"""
Parse STRUCTURE LINK Method
"""
# Constants
KEYWORDS = ('LINK',
'STRUCTURE',
'NUMSTRUCTS',
'STRUCTTYPE')
WEIR_KEYWORDS = ('STRUCTTYPE',
'CREST_LENGTH',
'CREST_LOW_ELEV',
... | [
"def",
"structureLink",
"(",
"lines",
")",
":",
"# Constants",
"KEYWORDS",
"=",
"(",
"'LINK'",
",",
"'STRUCTURE'",
",",
"'NUMSTRUCTS'",
",",
"'STRUCTTYPE'",
")",
"WEIR_KEYWORDS",
"=",
"(",
"'STRUCTTYPE'",
",",
"'CREST_LENGTH'",
",",
"'CREST_LOW_ELEV'",
",",
"'DI... | 35.548387 | 0.001177 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.