content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_merge2_sql_semantics_innerjoin_single_keep_firstlast():
"""
Test that merge2 matches the following SQL query:
select
f.id as foo_id,
f.col1 as foo_col1,
f.col2 as foo_col2,
b.id as bar_id,
b.col1 as bar_col1,
b.col2 as bar_col2,
b.... | 75,500 |
def runScenario(name, *args):
"""
Execute given scenario with optional arguments.
If called from command line, then arguments will all be strings. Scenario functions must sanitize inputs.
"""
# check the dynamically loaded list of scenarios
scenarioFunction = getScenario(name)
# call it
... | 75,501 |
def map_ids_to_bounding_boxes(
inkscape: str,
xml: etree.Element,
) -> Dict[str, BoundingBox]:
# noinspection SpellCheckingInspection
"""
Query an svg file for bounding-box dimensions
:param inkscape: path to an inkscape executable on your local file system
IMPORTANT: path cannot end wi... | 75,502 |
def create_ensemble(datasets, mf_flag=False):
"""Create an xarray datset of ensemble of climate simulation from a list of netcdf files. Input data is
concatenated along a newly created data dimension ('realization')
Returns a xarray dataset object containing input data from the list of netcdf files concate... | 75,503 |
def isabs(s):
"""Test whether a path is absolute. """
return s.startswith('/') | 75,504 |
def load_csv_as_dataframe(gcs_bucket, filename, dtype=None, chunksize=None,
parse_dates=False, thousands=None):
"""Loads csv data from the provided gcs_bucket and filename to a DataFrame.
Expects the data to be in csv format, with the first row as the column
names.
gc... | 75,505 |
def check_memory():
"""Return True when less than 0.5gb RAM available"""
mu = psutil.virtual_memory()
# memory in GB
GB_mem_free = mu.available/(2**30)
stats["check_memory_wrap"] = (f"\n Total RAM available(in GB): {mu.total/(2**30):.2f}\n\
Available RAM(in GB): {GB_mem_free:.2f}")
if GB_mem_free < 0.5:... | 75,506 |
def read_csv(fname, log = True, since_midnight = True):
"""Generates a single Peak instance from a file or list of files
Arguments
---------
fname: string or list of strings
log: bool.
If the actual or the log of the amplitude is given. If log is True the value in the file will be 10**amp
... | 75,507 |
def aer2geodetic(az, el, srange, lat0, lon0, h0, ell=None, deg=True):
# type: (float, float, float, float, float, float, Ellipsoid, bool) -> tuple
"""
gives geodetic coordinates of a point with az, el, range
from an observer at lat0, lon0, h0
Parameters
----------
az : float
azimut... | 75,508 |
async def play_game_human(client, player_id, realtime, game_time_limit):
"""Allow humans to play"""
while True:
state = await client.observation()
if client.game_result:
return client.game_result[player_id]
if game_time_limit and (state.observation.observation.game_loop * 0.7... | 75,509 |
def dictAttack(target,username,passwords,maxlines):
"""
This function performs dictionary attack to the specified username
:param target:
:param username:
:param passwords: Tha path of the dictionary to use for the attack
:param maxlines:
"""
passwordsFile = open(passwords, 'r')
wit... | 75,510 |
def random_secret_exponent(curve_order):
""" Generates a random secret exponent. """
random_256bit_hex_string = binascii.hexlify(get_entropy(32))
random_256bit_int = int(random_256bit_hex_string, 16)
int_secret_exponent = fit_number_in_range(random_256bit_int, 1, curve_order)
return int_secret_expo... | 75,511 |
def get_tile_num(fname, key='tile'):
""" Given 'key' extract 'num' from 'key_num' in string. """
l = os.path.splitext(fname)[0].split('_') # fname -> list
i = l.index(key)
return int(l[i+1]) | 75,512 |
def astype(value, types=None):
"""Return argument as one of types if possible."""
if value[0] in '\'"':
return value[1:-1]
if types is None:
types = int, float, str
for typ in types:
try:
return typ(value)
except (ValueError, TypeError, UnicodeEncodeError):
... | 75,513 |
def run_serial(n):
"""Program code to run."""
data = []
for i in range(n):
filename = f'data/{i}.json'
datum = load(filename)
data.append(datum)
sumA = sum_by_letter(data, 'A')
sumB = sum_by_letter(data, 'B')
sumC = sum_by_letter(data, 'C')
mean_score = mean([sumA, su... | 75,514 |
def adjlist_to_metis(adjlist, nodew=None, nodesz=None):
"""
Rudimentary adjacency list converter.
Primarily of use if you don't have or don't want to use NetworkX.
:param adjlist: A list of tuples. Each list element represents a node or vertex
in the graph. Each item in the tuples represents an e... | 75,515 |
def _minmax(*args):
""" Return the min and max of the input arguments """
min_ = min(*args)
max_ = max(*args)
return(min_, max_) | 75,516 |
def find_variable(text, start):
""" Return `(name, var_start, var_end)` or None.
The variable may be of two forms: `$XYZ` or `{$XYZ}`. The latter is to
be used when otherwise the variable name would be followed by a name
character, which would make it ambiguous.
"""
result = None
i = text.... | 75,517 |
def get_payday_leap_years(
payday,
frequency='biweekly',
count=5,
starting_year=date.today().year
):
"""Get the next n payday leap years.
Return a list of the next n payday leap years, where n is specified
by `count`.
Args:
payday (date): A payday from the specified pay calenda... | 75,518 |
def output_message(message):
"""This function will output an error message formatted in JSON to display on the StatusBoard app"""
output = json.dumps({"error": message}, indent=4)
return output | 75,519 |
def xslt(req, *opts):
"""
Transform the working document using an XSLT file.
:param req: The request
:param opts: Options (unused)
:return: the transformation result
Apply an XSLT stylesheet to the working document. The xslt pipe takes a set of keyword arguments. The only required
argument is 'stylesheet' which i... | 75,520 |
def gl_disable_depth(gl_state):
"""Disable OpenGl depth test
Parameters
----------
gl_state : vtkOpenGLState
"""
gl_state.vtkglDisable(_GL['GL_DEPTH_TEST']) | 75,521 |
def test_const_set_size__sized_int_works():
"""Already-sized integers shouldn't have a problem with the size override
code.
"""
field = fields.Int64(const=1234567890)
assert field.size is not None, "Size wasn't set."
assert field.size == 8, "Size is incorrect." | 75,522 |
def _time_distributed_dense(x, w, b=None, dropout=None,
input_dim=None, output_dim=None,
timesteps=None, training=None):
"""Apply `y . w + b` for every temporal slice y of x.
# Arguments
x: input tensor.
w: weight matrix.
b: optiona... | 75,523 |
def build_scheduled_client_work(
model_fn: Callable[[], model_lib.Model],
learning_rate_fn: Callable[[int], float],
optimizer_fn: Callable[[float], TFFOrKerasOptimizer],
metrics_aggregator: Callable[[
model_lib.MetricFinalizersType, computation_types.StructWithPythonType
], computation_base.... | 75,524 |
def filter_by_letterset(letters: Set[str], words_set: Iterator[str]) \
-> Iterator[str]:
"""
Filters the words in the dictionary by the letter-set. So, the set
{'h', 'o', 'w'} will match 'how' and 'who' but not 'whom'
Args:
letters: The set of letters to use to filter against the diction... | 75,525 |
def evaluate_confusion_matrix(y_true, y_pred, labels):
"""
Calculates a Confusion for each each of for y_true / y_pred and returns a formatted dictionary with the results.
:param ndarray y_true: The (potentially multiple) observed targets
:param ndarray y_pred: The (potentially multiple) prediction pro... | 75,526 |
def get_redirects(func_name: str, attr: str,
redirect_from: Callable) -> Optional[BaseModel]:
"""Get an attribute :code:`attr` from function :code:`func_name` from context of
:code:`redirect_from`
Like :func:`check_for_redirects` but instead of checking whether current
function's docs... | 75,527 |
def send_msgpack(socket, obj, flags=0, protocol=-1):
"""pickle an object, and zip the pickle before sending it"""
p = msgpack.packb(obj, use_bin_type=True)
return socket.send(p, flags=flags) | 75,528 |
def decompile_apk_dir(apps_dir, out_dir=None):
"""depr"""
apk_ls = glob(os.path.join(apps_dir, '*.apk'))
assert all(apk.endswith('.apk') for apk in apk_ls)
# count = 0
app_dir_ls = []
for apk_fn in apk_ls:
try:
app_dir, package = prep_dir_apk(apps_dir, apk_fn)
ap... | 75,529 |
def scale_cube(path, scale, hdu='PRIMARY', band=None, apply_scale=True):
"""Scale a single cube by a given value."""
hdulist = pf.open(path, 'update')
try:
old_scale = hdulist[hdu].header['RESCALE']
except KeyError:
old_scale = 1.0
# only apply scaling if actually requested, otherwis... | 75,530 |
def CreateFromSurface(surface, multiple=False):
"""
Constructs a mesh from a surface
Args:
surface (Surface): Surface to approximate
Returns:
Mesh: New mesh representing the surface
"""
url = "rhino/geometry/mesh/createfromsurface-surface"
if multiple: url += "?multiple=tru... | 75,531 |
def multiscatterplot(
data=None,
columns=None,
group_by=None,
color=None,
opacity=1,
tooltip=None,
height=600,
width=800,
):
"""Generate many scatterplots.
Based on several columns, pairwise.
"""
opt_args = choose_kwargs(locals(), ["color", "tooltip"])
assert group_... | 75,532 |
def register_tf_serializable(name=None, predicate=None):
"""See the docstring for `register_serializable`."""
return register_serializable(package="tf", name=name, predicate=predicate) | 75,533 |
def test_run_succeeds_normally(cli):
"""Test when an output is detected"""
exit_code, cwl = cli('run', 'touch', 'foo')
assert exit_code == 0
assert len(cwl.inputs) == 1
assert cwl.inputs[0].default == 'foo'
assert cwl.inputs[0].type == 'string'
assert len(cwl.outputs) == 1
assert cwl.ou... | 75,534 |
def compute_inertia_ellipsoid(points):
"""Compute inertia ellipsoid for `points`.
Please note, that order of Ellipsoid.axes might not correspond to the order of image axes!
Arguments:
points {numpy.array} -- an array of points (x, y, z)
Returns:
[analysis.Ellipsoid] -- inertia ellipso... | 75,535 |
def get_back_to_settings_button(poll):
"""Get the back to options menu button for option sub menus."""
locale = poll.user.locale
payload = f'{CallbackType.menu_back.value}:{poll.id}:{CallbackResult.settings.value}'
return InlineKeyboardButton(text=i18n.t('keyboard.back', locale=locale),
... | 75,536 |
def add_and_remove_cv_file():
"""add/remove cv file"""
file_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]
paths = ["{}{}".format(file_name, str(x).rjust(1, '0'))
for x in range(FILES_NUM)]
try:
for x in paths:
if os.path.exists("{}".format(x))... | 75,537 |
def collect_logs_fixture(request):
"""
This fixture collects ocs logs after tier execution and this will allow
to see the cluster's status after the execution on all execution status options.
"""
def finalizer():
"""
Tracking both logs separately reduce changes of collision
"... | 75,538 |
def Exec(args, env=None, no_exit=False):
"""Emulates the os.exec* set of commands, but uses subprocess.
This executes the given command, waits for it to finish, and then exits this
process with the exit code of the child process.
Args:
args: [str], The arguments to execute. The first argument is the comm... | 75,539 |
def downsample_average(trace: Trace, factor: int = 2) -> Trace:
"""
Downsample samples of `trace` by `factor` by averaging `factor` consecutive samples in
non-intersecting windows.
:param trace:
:param factor:
:return:
"""
resized = np.resize(trace.samples, len(trace.samples) - (len(tra... | 75,540 |
def generate_acrostic(tokenizer, model, head):
"""
随机生成一首藏头诗
:param tokenizer: 分词器
:param model: 用于生成古诗的模型
:param head: 藏头诗的头
:return: 一个字符串,表示一首古诗
"""
# 使用空串初始化token_ids,加入[CLS]
token_ids = tokenizer.encode('')
token_ids = token_ids[:-1]
# 标点符号,这里简单的只把逗号和句号作为标点
punctuati... | 75,541 |
def run_cmd(cmd, ignore_return_code=False, no_shell=False):
"""
Run a command using the async function that logs the output.
:param cmd: command to run
:param ignore_return_code: whether a non-zero return code should be ignored
:param noshell: don't run the command in a sub-shell
:returns: tupl... | 75,542 |
def distance0(cell1, cell2):
"""Return 0 distance for A* to behave like Dijkstra's algorithm."""
return 0 | 75,543 |
def writeAttrs(attrs, group):
"""
Writes a dictionary of attributes (attrs) onto the attrs of an HDF5
Group (group). Any conflicts will be overwritten.
This function assumes the attributes to be tuples of (value, unit) where
value may be an int,float, or str, and unit is a str.
"""
for... | 75,544 |
def get_allowed_post_types_from_link_type(link_type):
"""
Determine allowed_post_types based on a value for reddit's link_type setting
Args:
link_type (str): the link type or None
Returns:
list of str: list of allowed post types
"""
if link_type in [LINK_TYPE_LINK, LINK_TYPE_SE... | 75,545 |
def get_dev_config():
"""Get dev config object."""
config_class = get_config_class()
return config_class(config_yaml=DEV_CONFIG_YAML) | 75,546 |
def get_adjmatrix_from_image(image):
"""Get the adjacenty matrix from image
Args:
searchmap(np.ndarray): our structure of searchmap
Returns:
set of tuples: set of the crossing positions
"""
searchmap = parse_image(image)
return get_full_adjmatrix_from_npy(searchmap) | 75,547 |
def adjacent(g,node, n):
"""
find all adjacent nodes of input node in g
g: 2D array of numbers, the adjacency matrix
node: int, the node whose neighber you wanna find
return: a list of ints
"""
result = []
for i in range(n):
if g[node][i] != 0:
result.append(i)
... | 75,548 |
def create_dgl_object(graph_name, num_parts, \
schema, part_id, node_data, \
edge_data, nodeid_offset, edgeid_offset):
"""
This function creates dgl objects for a given graph partition, as in function
arguments.
Parameters:
-----------
graph_name... | 75,549 |
def get_version() -> str:
"""
Retrieves version from the flask app.
"""
if 'version' not in g:
g.version = read_version('development')
return g.version | 75,550 |
def create_counter():
"""Returns a prefab which can contain one of any item."""
base_prefab = create_base_prefab("counter")
base_prefab["components"] += [{
"component": "Container",
"kwargs": {
"reward": 0.0
}
}]
return base_prefab | 75,551 |
def GetCyclicThioamide(mol):
"""
Return:
count: int
"""
thioamide = Chem.MolFromSmarts("[CX3](=[SX1])@[NH]")
matches = mol.GetSubstructMatches(thioamide)
return matches | 75,552 |
def cleanBottom(line):
"""Rewrites bottom patterns."""
it = Iterator(line)
while line.find(["CofreeT ", "Identity ", " :< BottomF "], it):
it.element().replaceWith(Structure("⊥", []))
return line | 75,553 |
def createVtkUnstructuredGrid(G):
"""
Creates a tvtk.UnstructuredGrid object from a PRST grid.
Synopsis:
vtkGrid = createVtkUnstructuredGrid(G)
This is currently only used for plotting purposes.
"""
try:
from tvtk.api import tvtk
from mayavi import mlab
from ma... | 75,554 |
def get_side_labelling(node):
"""
Returns side labelling of the given node
:param node: str
:return: list(str)
"""
raise NotImplementedError() | 75,555 |
def dirname(string):
"""
Return the dir name from a full path file.
"""
return os.path.dirname(string) | 75,556 |
def _read_potentials(rotors, spc_dct_i, run_path, cnf_save_path,
ref_ene, mod_tors_ene_info,
tors_model):
""" read out the potentials
"""
_ = run_path
# Convert the rotor objects indexing to be in geoms
increment = spc_dct_i.get('hind_inc', 30.0*phycon.DEG... | 75,557 |
def create_user_profile(userArn=None, displayName=None, emailAddress=None, sshPublicKey=None):
"""
Creates a profile for a user that includes user preferences, such as the display name and email address assocciated with the user, in AWS CodeStar. The user profile is not project-specific. Information in the user... | 75,558 |
def ldns_resolver_defnames(*args):
"""LDNS buffer."""
return _ldns.ldns_resolver_defnames(*args) | 75,559 |
def is_expired(message):
"""Determines if a raid is expired, given its announcement message.
Message accepts the result returned by get_announcement_message (a valid obj or None).
:param message discord.Message: The announcement message associated with the raid.
:returns: True if the message/raid time... | 75,560 |
def generate_backend_suites(backends = []):
"""Generates per-backend test_suites that run all tests for a backend."""
if not backends:
backends = all_backends()
for backend in backends:
native.test_suite(name = "%s_tests" % backend, tags = ["tf_xla_%s" % backend]) | 75,561 |
def gaussbeam(w0 = 1,P = 5,z0 = 5, z = 10):
"""
Generate a gaussbeam
========================================
input
----------------------------------------
w0 Beam Waist
P total power
z0 Rayleigh Range
z Axial Distance
output
----------------------------------------
gaussbeam matrix
""... | 75,562 |
def error_064_link_equal_linktext(text):
"""
Fix the error and return (new_text, replacements_count) tuple.
Also correct links with spaces.
"""
count = 0
def _process_link(match_obj):
"""Deals with founded wiki-link."""
link = match_obj.group(1)
name = match_ob... | 75,563 |
def calc_unit_kinetic_energy(acc_signal):
"""
Calculates the cumulative absolute change in kinetic energy for a unit volume of soil with unit mass
Parameters
----------
acc_signal: eqsig.AccSignal
Returns
-------
"""
kin_energy = 0.5 * acc_signal.velocity * np.abs(acc_signal.veloc... | 75,564 |
def flatten(expression):
"""
A AND (B AND C) -> A AND B AND C
A OR (B OR C) -> A OR B OR C
"""
if isinstance(expression, exp.Connector):
for node in expression.args.values():
child = node.unnest()
if isinstance(child, expression.__class__):
node.replac... | 75,565 |
async def notify_revocation_entry_event(
profile: Profile, rev_reg_id: str, meta_data: dict
):
"""Send notification for a revocation registry event."""
event_id = REVOCATION_EVENT_PREFIX + REVOCATION_ENTRY_EVENT + "::" + rev_reg_id
await profile.notify(
event_id,
meta_data,
) | 75,566 |
def ProxyTraffic():
"""starts proxying traffic."""
global proxied
t = threading.Thread(target=StartCoredns)
t.start()
print('Pointing System DNS to proxy')
SetDnsServerToLocal()
print('DNS Redirected')
proxied = True | 75,567 |
def split_integer(num, parts):
"""
Split number into given number of pars that are as equal as possible
https://stackoverflow.com/questions/55465884/how-to-divide-an-unknown-integer-into-a-given-number-of-even-parts-using-python
"""
quotient, remainder = divmod(num, parts)
lower_elements = [quo... | 75,568 |
def write_to_pir_alignment(pir_alignment_filehandle, seq_type, seq_name, seq):
"""Write the `*.pir` alignment compatible with modeller.
Parameters
----------
seq_type : str
One of: ['sequence', 'structure'], in that order.
seq_name : str
Name to appear in the alignment.
seq : st... | 75,569 |
def lambda_handler(event, context):
"""Lambda function that stores the current step function state token into dynamo.
Parameters
----------
event: dict, required
context: object, required Lambda Context runtime methods and attributes
Context doc: https://docs.aws.amazon.com/lambda/latest/dg/pyt... | 75,570 |
def read_module(f) -> ir.Module:
"""Read an ir-module from file.
Args:
f: A file like object ready to be read in text modus.
Returns:
The loaded ir-module.
"""
return Reader().read(f) | 75,571 |
def chat_guard(func):
"""
Разрешено ли боту работать в этом чате?
"""
@wraps(func)
def decorator(bot: telegram.Bot, update):
chat_id_str = str(update.message.chat_id)
if chat_id_str not in CONFIG["chats"]:
send_chat_access_denied(bot, update)
return
r... | 75,572 |
def _init_db_demo_1():
"""デモ用(最初期)"""
quality_props = QualityDimensionMapper.query.all()
relational_operator = RelationalOperatorMapper.query.all()
meas = [QualityMeasurementMapper(name='Coverage of activated neurons',
version='0.1',
... | 75,573 |
def _init_config_parser(common, subparsers):
"""
Creates parsers for `config` command
:param common: parent parser
:param subparsers: sub-parser for config parser to be added to
"""
config_parser = subparsers.add_parser(
ACTION_CONFIG, parents=[common], description='Config related acti... | 75,574 |
def get_1st_ck_line_from_line( line ):
"""
A check line may contain more than 1 check.
Here we get only the info(line aka string) from the 1st one.
"""
# return line # if there is only 1 check per line
splited = line.split()
ck1 = splited[:4] # in this case, 1st check info is in 1... | 75,575 |
def convert_to_real_ops(ops):
"""
Converts a batch of TensorFlow operators to something that a neural network
can take as input.
Args:
ops (`tf.Tensor`): a 4D tensor (batch_size, N, hilbert_size,
hilbert_size)
of ... | 75,576 |
def validate_twitter_handle(twitter_handle: str) -> Optional[re.Match]:
"""Validate a twitter handle. Optional @, length up to 15 characters"""
return re.match(__match_twitter_handle, twitter_handle) | 75,577 |
def parse_group_benefits(table):
"""
ukparl_groups
Parses the Registrable benefits table
TODO: find an example of one that is actually filled in, so we know
what the headers are.. otherwise can't parse this (this might
not really be a data table though)
"""
return [] | 75,578 |
def update_deployment_template_resource_types(plan_name, resource_types):
"""Retrieve plan_name's environment file from Swift and update the
resource_registry tree according to the values passed in by resource_types.
Then update the environment file in Swift.
"""
pass | 75,579 |
def run_popen_with_timeout(command_string, timeout, cwd):
"""
Run a sub-program in subprocess.Popen, pass it the input_data,
kill it if the specified timeout has passed.
returns a tuple of success, stdout, stderr
"""
kill_check = threading.Event()
def _kill_process_after_a_timeout(pid):
... | 75,580 |
def average_bg_with_rc(bgs):
"""
Average the background frequencies with the reverse complement
----
Parameters:
bgs (dict) : dictionary of the background probabilities
----
Returns:
bgs_avg (dict) : averaged background probabilities
"""
bgs_a... | 75,581 |
def splice_alg(pd_edges):
""" Implementation of the SPLICE algorithm
"""
pickups = pd_edges.keys()
deliveries = pd_edges.values()
# Compute Hungarian matching indices
c_mat = dist.cdist(deliveries, pickups)
# Connect dp_edges according to bipartite matching
dp_edges = {deliveries[d_ind]... | 75,582 |
def copy_group_metadata(input_hdf5, output_hdf5):
"""Copies the attributes between HDF5 files
Args:
input_file (h5py.File): HDF5 file descriptor from which group attributes
should be copied
output_file (h5py.File): HDF5 file descriptor to which group attributes
should be... | 75,583 |
def for_get(uri: str) -> dict:
"""
Extract resource names from a URI for supported AWS services.
Currently, only S3 and SSM are supported.
>>> for_get('s3://abc:xyz@bucket/object.data')
{'Bucket': 'bucket', 'Key': 'object.data'}
>>> for_get('ssm://ABC:XYZ@/path/to/parameter?region_name=us-east-... | 75,584 |
def as_nested_dict(
obj: Union[DictLike, Iterable[DictLike]],
dct_class: type = dict, **kwargs) -> Union[DictLike, Iterable[DictLike]]:
"""
Given a obj formatted as a dictionary, transforms it (and any nested dictionaries)
into the provided dct_class
Args:
- obj (Any): An object... | 75,585 |
def complete_sulci_name(sulci_list, side):
"""Function gathering sulci and side to obtain full name of sulci
It reads suli prefixes from a list and adds a suffix depending on a given
side.
Args:
sulci_list: a list of sulci
side: a string corresponding to the hemisphere, whether 'L' or ... | 75,586 |
def test__export_gz_data_to_csv():
"""Tests function ``_export_gz_data_to_csv()``."""
from dirty_cat.datasets.fetching import _export_gz_data_to_csv, Features
features = Features(["top-left-square",
"top-middle-square",
"top-right-square",
... | 75,587 |
def _gwr(fn: Union[Callable[[float], Any], Callable[[float, int], Any]],
time: float, M: int, precin: int) -> float:
"""
GWR alorithm with memoization.
"""
tau = mp.log(2.0) / mp.mpf(time)
# mypy can't type check the Callable at runtime, we must do it ourselves
sig = signature(fn).para... | 75,588 |
def build(arguments):
"""
Build Kowalski's containers
:param arguments:
:return:
"""
print('Building Kowalski')
cfgs = [
'config.*yaml',
'docker-compose.*yaml'
]
# always use docker-compose.yaml
command = ["docker-compose", "-f", 'docker-compose.yaml', "buil... | 75,589 |
def libsvm_convert_sparse_tensor(array_ids, array_values):
"""Transform the contents into TF understandable formats, which is similar to
sparse_tensor_to_train_batch().
Args:
array_ids: Sparse indices.
array_values: Sparse values.
Returns:
List of the transformed (ids, values).
... | 75,590 |
def initialize_deep_flow_model(h, w, weight):
"""Initialize optical flow network
Args:
h (int): image height
w (int): image width
Returns:
flow_net (nn.Module): optical flow network
"""
flow_net = LiteFlow(h, w)
flow_net.initialize_network_model(
weight_... | 75,591 |
def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(public.views.blueprint)
app.register_blueprint(user.views.blueprint)
return None | 75,592 |
def p_expression_logic_member(p):
"""expression_logic : BOOLEAN
| expression_comp
"""
p[0] = p[1] | 75,593 |
def _read_pretrained_tokens(embeddings_file_uri: str) -> List[str]:
"""
Helper method for loading pretrained tokens from a given file. This is usually
the case for e.g. GloVe files, containing the token and the embedding of that token.
Parameters
----------
embeddings_file_url : ``str`` The pat... | 75,594 |
def has_param(func: Callable, param: str) -> bool:
"""Check if func has a parameter named param.
Parameters
----------
func : Callable
Function to inspect.
param : str
Parameter name.
Returns
-------
bool
True if the parameter is part of func's signature,
... | 75,595 |
def solve_msd_analytically(t):
"""Returns the analytical solution to the differential equation
at the timepoints t.
"""
mass = 100
springk = 50
damping = 1
x0 = 1
#Calculate help variables
zeta = damping/(2*sqrt(mass*springk))
omega0 = sqrt(springk/mass)
#Solve the differen... | 75,596 |
def plot(time_lim=(0., 140.), y_lim=None, x_initial=None, y_initial=None,
plot_data=True, show_plot=True):
"""
Plot the results
"""
x, y, errorbar, xfit, yfit = readdata()
x_rsd, y_rsd, errorbar_rsd = readrsd()
x_raw, y_raw = read_datafile()
f = plt.figure()
plt.subplots_adjust... | 75,597 |
def save_day(paralleled=True):
"""多进程保存日线数据
"""
QA_SU_save_index_list('tdx')
QA_SU_save_index_day('tdx', paralleled=paralleled)
QA_SU_save_etf_list('tdx')
QA_SU_save_etf_day('tdx', paralleled=paralleled)
QA_SU_save_stock_list('tdx')
QA_SU_save_stock_block('tdx')
QA_SU_save_stock_day(... | 75,598 |
def add_additional_bookmark(dataset_folder, bookmark_file_name, bookmark_name,
sources, display_settings,
source_transforms=None, viewer_transform=None,
display_group_names=None, overwrite=False):
""" Add or update a view in a bookm... | 75,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.