content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_gcsfetchstrategy_without_url(_fetch_method):
"""Ensure constructor with no URL fails."""
with spack.config.override('config:url_fetch_method', _fetch_method):
with pytest.raises(ValueError):
spack.fetch_strategy.GCSFetchStrategy(None) | 12,300 |
def combine_dataframes(dfs: [pd.DataFrame]) -> pd.DataFrame:
"""
Receives a list of DataFrames and concatenates them. They must all have the same header.
:param dfs: List of DataFrames
:return: Single concatenated DataFrame
"""
df = pd.concat(dfs, sort=False)
return df | 12,301 |
def reduce_company_info_file(
ticker_symbols_file, company_info_input_file, company_info_output_file):
"""Reduce the company info file."""
if not ticker_symbols_file:
raise click.BadParameter(
'--ticker-symbols-file option is required')
if not company_info_input_file:
rai... | 12,302 |
def df_to_hdf5(df, key, dir_path):
"""
Save the DataFrame object as an HDF5 file. The file is stored
in the directory specified and uses the key for the filename
and 'h5' as the extension.
:param df: DataFrame to save as a file
:param key: ID for storage and retrieval
:param dir_path: Direct... | 12,303 |
def _switch_default_role(db, obj, admin):
"""Switch between default user/service and admin roles for users/services"""
user_role = orm.Role.find(db, 'user')
admin_role = orm.Role.find(db, 'admin')
def add_and_remove(db, obj, current_role, new_role):
if current_role in obj.roles:
str... | 12,304 |
def _bound_accumulated_rotations(robot_name, command_dicts):
"""
Checks axes whose rotations have been accumulated to ensure they've not
exceeded the stated limits. If they have, this function attempts to slide
the commands by +/- 360 degrees. If the limits are still exceeded, this
function return... | 12,305 |
def train_genomes(genomes, dataset):
"""Train each network.
Args:
networks (list): Current population of networks
dataset (str): Dataset to use for training/evaluating
"""
pbar = tqdm(total=len(genomes))
for genome in genomes:
genome.train(dataset)
genome.print_... | 12,306 |
def get_email_manager(config: CFG, session: Session):
"""
:return: EmailManager instance
"""
# TODO: Find a way to import properly without cyclic import
smtp_config = SmtpConfiguration(
config.EMAIL__NOTIFICATION__SMTP__SERVER,
config.EMAIL__NOTIFICATION__SMTP__PORT,
config... | 12,307 |
def test_list_g_month_enumeration_3_nistxml_sv_iv_list_g_month_enumeration_4_3(mode, save_output, output_format):
"""
Type list/gMonth is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/gMonth/Schema+Instance/NISTSchema-SV-IV-list-gMonth-enumeration-4.xsd",
in... | 12,308 |
def _approx_sp(salt,pres):
"""Approximate TDl at SP.
Approximate the temperature and liquid water density of sea-ice with
the given salinity and pressure.
:arg float salt: Salinity in kg/kg.
:arg float pres: Pressure in Pa.
:returns: Temperature and liquid water density (both in SI uni... | 12,309 |
def test_close_with_heartbeatTimer(caplog):
"""Test close() with heartbeatTimer"""
iface = MeshInterface(noProto=True)
anode = Node('foo', 'bar')
radioConfig = RadioConfig()
radioConfig.preferences.phone_timeout_secs = 10
anode.radioConfig = radioConfig
iface.localNode = anode
assert ifa... | 12,310 |
def recharge_polybar():
"""Command to restart polybar"""
os.system("polybar-msg hook pomobar 1 &> /dev/null") | 12,311 |
def test_get_4x4_determinant_method():
"""tests get 4x4 determinant method"""
matrix = Matrix([
[4, 5, 2, -1],
[5, 8, 7, 6],
[3, 7, -4, -2],
[-1, 6, -2, 5]
])
det = matrix.get_determinant()
assert det == 378 | 12,312 |
def test_can_parse_alias_file():
"""
Make sure aliases.json file can be parsed.
This is to make sure an edit doesn't accidentally corrupt it.
"""
# We'll have to hardcode this.
alias_file_path = os.path.join(
config.DEFAULT_EXAMPLES_DIR,
util.ALIAS_FILE_NAME
)
alias_file... | 12,313 |
def test():
"""A little test suite."""
import io
testtext = 'Netstrings rule'
inf = io.StringIO()
outf = io.StringIO()
print("Writing a Netstring ... ", end=' ')
f = NetStringIO(outf)
f.write(testtext)
print(outf.getvalue(), end=' ')
inf = io.StringIO(outf.getvalue())
f.c... | 12,314 |
def init_config_dirs():
"""Creates .tiflash base folder as well as any configuration subfolders
inside of it.
Note:
Typically only used by setup.py when pip installing package
"""
base = get_base_dir()
custom = get_custom_dir()
if not os.path.exists(base):
os.mkdir(base)
... | 12,315 |
def createToolBar():
"""Creates the toolbar containing the action to open the Settings Dialog
"""
Data.toolbar = sbsui.add_toolbar("Megscan Link", "megascanlink")
qicon = QtGui.QIcon()
qicon.addPixmap(icon.getIconAsQPixmap("megascan_logo_idle.png"))
qicon.addPixmap(icon.getIconAsQPixmap("megascan_logo.png"),... | 12,316 |
def _get_connection_params(resource):
"""Extract connection and params from `resource`."""
args = resource.split(";")
if len(args) > 1:
return args[0], args[1:]
else:
return args[0], [] | 12,317 |
def download_archive(url, out_path):
"""Downloads a file from the specified URL to the specified path on disk."""
return subprocess.call(['curl', url, '-o', out_path]) | 12,318 |
def listdata(
resp: Union[requests.Response, List[Dict[str, Any]]],
*keys: Union[str, Callable[[], bool]],
sort: Union[bool, str] = True,
full: bool = False, # returns dicts instead of tuples
) -> List[tuple]:
"""Return data from a given requests.Response object.
Only non reserved fields are r... | 12,319 |
def create_chart_data(start_path, excluded_dashboards=excluded_dashboards):
"""Read chart names and SQL code from the repository.
Args:
start_path (str): "./dashboards"
excluded_dashboards (list): list of dashboards to exclude from testing (e.g. WIP, Untitled, etc)
Returns:
cha... | 12,320 |
def get_current_pkg():
"""
Returns:
パッケージ名 (str): 常に大文字表記で返ってくる
"""
return eval_foreign_vm_copy("(send *package* :name)") | 12,321 |
def _normalise_trigger(value: float) -> float:
"""
Helper function used to normalise the controller trigger values into a common range.
:param value: Value to be normalised
:raises: ValueError
:return: Normalised value
"""
return _normalise(value, _HARDWARE_TRIGGER_MIN, _HARDWARE_TRIGGER_MA... | 12,322 |
def full_process(s):
"""Process string by
-- removing all but letters and numbers
-- trim whitespace
-- force to lower case"""
if s is None:
return ""
#Here we weill force a return of "" if it is of None, empty, or not valid
#Merged from validate_string
try:
... | 12,323 |
def ldexp(space, x, i):
"""ldexp(x, i) -> x * (2**i)
"""
return math2(space, math.ldexp, x, i) | 12,324 |
def menu():
"""
Print a menu with all the functionalities.
Returns:
The choice of the user.
"""
print "=" * 33 + "\nMENU\n" + "=" * 33
descriptions = ["Load host from external file",
"Add a new host",
"Print selected hosts",
"C... | 12,325 |
async def objects_get(bucket: Optional[str] = None,
index: Index = Depends(Provide[Container.index]),
buckets: Buckets = Depends(Provide[Container.buckets])) -> List[Object]:
"""
searches for objects
"""
if not bucket:
return index.get_all()
bucke... | 12,326 |
def test_node_can_be_loaded_simple():
# type: () -> None
"""Test loading a single node with "simple" representation.
The "simple" representation should return the same structure that would
be created if the '!gryaml.node' tag were absent or the implicit type.
"""
gryaml.register_simple()
s... | 12,327 |
def thumbnail_create(request, repo_id):
"""create thumbnail from repo file list
return thumbnail src
"""
content_type = 'application/json; charset=utf-8'
result = {}
repo = get_repo(repo_id)
if not repo:
err_msg = _(u"Library does not exist.")
return HttpResponse(json.dump... | 12,328 |
def initialize_event_loop():
"""Attempt to use uvloop."""
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
return asyncio.get_event_loop() | 12,329 |
def _setup_pgops(multi_actions=False,
normalise_entropy=False,
sequence_length=4,
batch_size=2,
num_mvn_actions=3,
num_discrete_actions=5):
"""Setup polices, actions, policy_vars and (optionally) entropy_scale_op."""
t = sequence_l... | 12,330 |
async def definition_delete(hub, ctx, name, **kwargs):
"""
.. versionadded:: 1.0.0
Delete a policy definition.
:param name: The name of the policy definition to delete.
CLI Example:
.. code-block:: bash
azurerm.resource.policy.definition_delete testpolicy
"""
result = False... | 12,331 |
def run(setup: Callable[[BaseScene], None] = None, *, log_level=logging.WARNING,
starting_scene=BaseScene, title="PursuedPyBear", **engine_opts):
"""
Run a small game.
The resolution will 800 pixels wide by 600 pixels tall.
setup is a callable that accepts a scene and returns None.
log_le... | 12,332 |
def agent_environment(test_config, agent_env_settings_fields):
"""
Set essential environment variables for test function and unset the after.
"""
agent_settings = test_config.get("agent_settings", dict())
for name in agent_env_settings_fields:
value = compat.os_environ_unicode.get(name, agen... | 12,333 |
def test_bootstrap_random_seed():
"""Test that we can get reproducible resamples by seeding the RNG."""
data = rs.randn(50)
seed = 42
boots1 = algo.bootstrap(data, random_seed=seed)
boots2 = algo.bootstrap(data, random_seed=seed)
assert_array_equal(boots1, boots2) | 12,334 |
def test_simplex_project():
"""Test simplex project"""
res = utils.simplex_project(np.array([0, 0, 0]))
assert np.allclose(res, [1 / 3] * 3), \
"projecting [0, 0, 0] didn't result in uniform"
res = utils.simplex_project(np.array([1.2, 1.4]))
assert np.allclose(res, [.4, .6]), \
"sim... | 12,335 |
def demo(numsamples=6, numoutcomes=500):
"""
A demonstration of frequency distributions and probability
distributions. This demonstration creates three frequency
distributions with, and uses them to sample a random process with
``numsamples`` samples. Each frequency distribution is sampled
``n... | 12,336 |
def parse_options(argv):
"""Parses and checks the command-line options.
Returns:
A tuple containing the options structure and a list of categories to
be traced.
"""
usage = 'Usage: %prog [options] [category1 [category2 ...]]'
desc = 'Example: %prog -b 32768 -t 15 gfx input view sched freq'
parser =... | 12,337 |
def open_excel(path):
"""context generator to open and close excel sheets"""
spreadsheet = Spreadsheet(path)
yield spreadsheet
spreadsheet.close() | 12,338 |
def test_fix_nothing():
"""Ensures that fix works for Nothing container."""
assert Nothing.fix(lambda _: None) == Nothing
assert Nothing.fix(lambda _: 1) == Some(1) | 12,339 |
def get_data_for_file(folder, ports):
"""Parses the pcap files in the specified folder, and outputs data for the specified ports
"""
# Load private keys and port->provider mappings
keys, providers, nodes = read_keys(os.path.join(folder, 'keys'))
print 'Loading packets'
# Load packets
... | 12,340 |
async def create_channel_in_db(
context: 'Context',
game_config: 'GameConfig',
channel_id: str,
finished: bool = False
) -> Channel:
"""Utility function to create a channel in the database
:param context: The Discord Context.
:param game_config: The GameConfig to use for extra info.
:pa... | 12,341 |
def error(msg):
""" Print message to stderr, can't use print because of Python 2/3
incompatibility """
sys.stderr.write(u'error: {}\n'.format(msg)) | 12,342 |
def retry(times, func, *args, **kwargs):
"""Try to execute multiple times function mitigating exceptions.
:param times: Amount of attempts to execute function
:param func: Function that should be executed
:param args: *args that are passed to func
:param kwargs: **kwargs that are passed to func
... | 12,343 |
def _apply_prediction(G, func, ebunch=None):
"""Applies the given function to each edge in the specified iterable
of edges.
`G` is an instance of :class:`networkx.Graph`.
`ebunch` is an iterable of pairs of nodes. If not specified, all
non-edges in the graph `G` will be used.
"""
if ebunc... | 12,344 |
def import_class(class_object):
"""
Import a class given a string with its name in the format module.module.classname
"""
d = class_object.rfind(".")
class_name = class_object[d + 1:len(class_object)]
m = __import__(class_object[0:d], globals(), locals(), [class_name])
return getattr(m, clas... | 12,345 |
def anonymous_fun_0_(empty_closure_0_):
"""
empty_closure_0_: ()
"""
def anonymous_fun_1_(par_map_input_1_):
"""
par_map_input_1_: Double
"""
def anonymous_fun_2_(par_map_input_0_):
"""
par_map_input_0_: Double
"""
def anonymous_fun_3_(fused_input_0_):
"""
... | 12,346 |
def test_version():
"""Test there is a version string"""
assert {{ cookiecutter.project_slug }}.__version__ == '{{ cookiecutter.version }}' | 12,347 |
def fromrecords(recList: List[List[int]], names: List[Literal["c", "b", "a"]]):
"""
usage.matplotlib: 1
"""
... | 12,348 |
def get_examples(mode='train'):
"""
dataset[0][0] examples
"""
examples = {
'train':
({'id': '0a25cb4bc1ab6f474c699884e04601e4', 'title': '', 'context': '第35集雪见缓缓张开眼睛,景天又惊又喜之际,长卿和紫萱的仙船驶至,见众人无恙,'
'也十分高兴。众人登船,用尽合力把自身的真气和水分输给她。雪见终于醒过来了,但却一脸木然,全无反应。众人向常胤求助,却发现人世界竟没有雪见的身世纪录。长卿询问清微的身世,... | 12,349 |
def finished(ignored):
"""
Callback invoked when both logins and method calls have finished to shut
down the reactor so the example exits.
"""
reactor.stop() | 12,350 |
def launch_external_program(path):
"""Launches an application with a predefined CSV to open.
Args:
path (str):
Returns:
None.
"""
OS = sys.platform
log.info('Identified OS : '+OS)
if OS == 'linux':
os.system('libreoffice ' + path)
elif OS == 'win32':
os... | 12,351 |
def display_tables(tables, max_rows=10, datetime_fmt='%Y-%m-%d %H:%M:%S', row=True):
"""Display mutiple tables side by side on a Jupyter Notebook.
Args:
tables (dict[str, DataFrame]):
``dict`` containing table names and pandas DataFrames.
max_rows (int):
Max rows to show... | 12,352 |
def get_visible_enemy_units(observation, as_list=False, as_dict=True):
"""
This function takes an observation and returns a list of the enemy units that are
on screen and are visible.
A unit is considered visible if is either visible (in the protos sense) or if it
is snapshotted and finished.
The definition... | 12,353 |
def prepare_default_result_dict(key, done, nodes):
"""Prepares the default result `dict` using common values returned by any
operation on the DHT.
Returns:
dict: with keys `(k, d, n)` for the key, done and nodes; `n` is a list
of `dict` with keys `(i, a, x)` for id, address, and expirat... | 12,354 |
def MatchScorer(match, mismatch):
"""Factory function that returns a score function set to match and mismatch.
match and mismatch should both be numbers. Typically, match should be
positive and mismatch should be negative.
Resulting function has signature f(x,y) -> number.
"""
def scorer(x, y... | 12,355 |
def random_choice(context: RuntimeContext, *choices):
"""Template helper for random choices.
Supports structures like this:
random_choice:
- a
- b
- <<c>>
Or like this:
random_choice:
- choice:
pick: A
probability: 50%
- choice:
... | 12,356 |
def _compute_paddings(height_pad_amt, width_pad_amt, patch_axes):
"""Convert the total pad amounts to the format needed by tf.pad()."""
top_pad = height_pad_amt // 2
bottom_pad = height_pad_amt - top_pad
left_pad = width_pad_amt // 2
right_pad = width_pad_amt - left_pad
paddings = [[0, 0] for _ in range(4... | 12,357 |
def tab_size(computer, name, value):
"""Compute the ``tab-size`` property."""
if isinstance(value, int):
return value
else:
return length(computer, name, value) | 12,358 |
def match_complete(user_id=""):
"""Switch 'complete' to true in matches table for user, return tallies."""
print("match_complete", user_id)
user = sm.get_user(user_id)
# Note: 0/1 used for 'complete' b/c Booleans not allowed in SimpleObjects
this_match, i = current_match_i(user)
temp = this_match['complete'... | 12,359 |
def compute_range_map(flow,
downsampling_factor=1,
reduce_downsampling_bias=True,
resize_output=True):
"""Count how often each coordinate is sampled.
Counts are assigned to the integer coordinates around the sampled coordinates
using weights from ... | 12,360 |
def get_wer(refs: List[str], hyps: List[str]):
"""
args:
refs (list of str): reference texts
hyps (list of str): hypothesis/prediction texts
"""
n_words, n_errors = 0, 0
for ref, hyp in zip(refs, hyps):
ref, hyp = ref.split(), hyp.split()
n_words += len(ref)
n... | 12,361 |
def quad_sim(x_c, y_c, z_c):
"""
Calculates the necessary thrust and torques for the quadrotor to
follow the trajectory described by the sets of coefficients
x_c, y_c, and z_c.
"""
x_pos = -5
y_pos = -5
z_pos = 5
x_vel = 0
y_vel = 0
z_vel = 0
x_acc = 0
y_acc = 0
z... | 12,362 |
def get_first(somelist, function):
""" Returns the first item of somelist for which function(item) is True """
for item in somelist:
if function(item):
return item
return None | 12,363 |
def np_cross(a, b):
"""
Simple numba compatible cross product of vectors
"""
return np.array([
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]) | 12,364 |
def get_process_output(process, encoding=None):
"""Get the output from the process."""
output = process.communicate()
returncode = process.returncode
if not encoding:
try:
encoding = sys.stdout.encoding
except Exception:
encoding = locale.getpreferredencoding()
... | 12,365 |
def augment_model_with_bundled_inputs(
model: torch.jit.ScriptModule,
inputs: Optional[Sequence[Tuple[Any, ...]]] = None,
_receive_inflate_expr: Optional[List[str]] = None, # For debugging.
info: Optional[List[str]] = None, # Optional argument to provide info about forward or its input... | 12,366 |
def check(ctx):
"""Check the consistency of documentation, coding style and a few other things."""
with chdir(BASE_FOLDER):
log.write("Pep517 check")
ctx.run("python -m pep517.check .")
log.write("Running all pre-commit hooks on whole repository.")
ctx.run("pre-commit run --all-... | 12,367 |
def test_one_hot_encoder_not_sparse():
"""
Tests whether the monkey patching of ('sklearn.preprocessing._encoders', 'OneHotEncoder') with dense output
"""
test_code = cleandoc("""
import pandas as pd
from sklearn.preprocessing import label_binarize, OneHotEncoder
... | 12,368 |
def dct_2d(pixel_blocks: np.ndarray, verbose: int = 0) -> np.ndarray:
"""
Does 8x8 2D DCT on an image represented by pixel blocks.
:param pixel_blocks:
A np.ndarray of shape AxBx8x8x3, where A = H/8, B = W/8.
:param verbose:
An int; if greater than 0 will print out a tqdm progress bar.
... | 12,369 |
def set_task_status(
bucket: Bucket,
job_id: str,
task_id: str,
state: TaskState,
worker: Optional[str] = _LOCAL_FQDN,
):
"""Set the status of a task.
Uploads the JSON serialization of a TaskStatus into a bucket, recording its
present state.
Parameters
----------
bucket : B... | 12,370 |
def remove_duplicates(llist):
"""
Removes any and all duplicate entries in the specified list.
This function is intended to be used during dataset merging and
therefore must be able to handle list-of-lists.
:param llist: The list to prune.
:return: A list of unique elements only.
"""
i... | 12,371 |
def images_in_bbox(bbox: dict, **filters) -> str:
"""
Gets a complete list of images with custom filter within a BBox
:param bbox: Bounding box coordinates
Format::
>>> {
... 'west': 'BOUNDARY_FROM_WEST',
... 'south': 'BOUNDARY_FROM_SOUTH',
... | 12,372 |
def find_start_time_from_afl(project_base_dir):
"""
Finds the start time of a project from afl directories.
This time is taken from the fuzzer_stats entry of
the first config iteration's fuzzer.
"""
try:
first_main_dir = main_dirs_for_proj(project_base_dir)[0]
except:
#if fu... | 12,373 |
def set_password(user, passwd):
""" set the users password """
# execute all commands from config file
for rcmd in conf("commands.setPassword"):
cmdlog = rcmd.replace("$1", user).replace("$2", "*****")
cmd = rcmd.replace("$1", user).replace("$2", passwd)
run(cmd, cmdlog) | 12,374 |
def filter_none_values(d, recursive=True):
"""
Returns a filtered copy of a dict, with all keys associated with 'None' values removed.
adapted from: http://stackoverflow.com/q/20558699
adapted from: http://stackoverflow.com/a/20558778
:param d: a dict-like object.
:param recursive: If True, pe... | 12,375 |
def nonseq():
""" Return non sequence """
return 1 | 12,376 |
def handler(settings, orch, output, signum=None, frame=None):
"""Signal handler
This function is called when the simulator receive SIGTERM, SIGHUP, SIGKILL
or SIGQUIT from the OS.
Its function is simply to write on a file the partial results.
Parameters
----------
settings : Settings
... | 12,377 |
def load_image(path, color_space = None, target_size = None):
"""Loads an image as an numpy array
Arguments:
path: Path to image file
target_size: Either, None (default to original size)
or tuple of ints '(image height, image width)'
"""
img = io.imread(path)
if... | 12,378 |
def kubernetes_node_label_to_dict(node_label):
"""Load Kubernetes node label to Python dict."""
if node_label:
label_name, value = node_label.split("=")
return {label_name: value}
return {} | 12,379 |
def get_category_user_problem(cat_name, username):
"""
获取直接在指定目录下的用户AC的题目、尚未AC的题目和尚未做过的题目的情况
:param cat_name:
:param username:
:return:
"""
cat = __Category.objects.filter(name=cat_name).first()
user = __User.objects.filter(username=username).first()
if user is None or cat is None:
... | 12,380 |
def write_list_content(log_writer, key, list_value, level, **kwargs):
"""
Writes list content to HTML. For example, the fields content of an event.
The html_wrapper decorator puts a start and end tag
(possibly specified in kwargs) around the content written by this function.
- log_writer:
... | 12,381 |
def floatToJson(x):
"""Custom rule for converting non-finite numbers to JSON as quoted strings: ``"inf"``, ``"-inf"``, and ``"nan"``. This avoids Python's bad habit of putting literal ``Infinity``, ``-Infinity``, and ``NaN`` in the JSON (without quotes)."""
if x in ("nan", "inf", "-inf"):
return x
e... | 12,382 |
def get_datafiles(datadir, prefix = ""):
"""
Scan directory for all csv files
prefix: used in recursive call
"""
datafiles = []
for fname in os.listdir(datadir):
fpath = os.path.join(datadir, fname)
datafile = os.path.join(prefix, fname)
if os.path.isdir(fpath):
... | 12,383 |
def auto_delete_file_on_change(sender, instance, **kwargs):
"""
Deletes old file from filesystem
when corresponding `MediaFile` object is updated
with new file.
"""
if not instance.pk:
return False
try:
old_file = sender.objects.get(pk=instance.pk).url_banner
except send... | 12,384 |
def systematic_uncertainties():
"""tabulates sources of uncertainty and sums them in quadrature"""
result_m = [
0.066, # [0.07-0.12] 0.066 ± 0.019
0.019, # [0.12-0.20] 0.019 ± 0.009
0.002, # [0.20-0.30] 0.002 ± 0.009
-0.006, # [0.30-0.45] -0.006 ± 0... | 12,385 |
def extract_metamap(json_, key):
"""
Task function to parse and extract concepts from json_ style dic, using
the MetaMap binary.
Input:
- json_ : dic,
json-style dictionary generated from the Parse object related
to the specific type of input
- key : str,
string d... | 12,386 |
def get_testinfo_by_reference(ref_name, ref_type):
""" get test content by reference name
@params:
ref_name: reference name, e.g. api_v1_Account_Login_POST($UserName, $Password)
ref_type: "api" or "suite"
"""
function_meta = parse_function(ref_name)
func_name = function_meta["func_na... | 12,387 |
def game_info(uuid: str) -> dict:
"""
return info about game by uuid
:param uuid:
:return: message
"""
logging.info(uuid)
logging.info(games.keys())
if UUID(uuid) in games.keys():
select_game: Game = games.get(UUID(uuid))
return {
"uuid": uuid,
"st... | 12,388 |
def main(genome_accession_file, project_dir, lsf=True):
"""
Parses a file of genome accessions and downloads genomes from ENA. Genomes
are downloaded in fasta format. It is a requirement that genome_accession
file containes a GCA or WGS accession per genome
genome_accession_file: A file with a lis... | 12,389 |
def miller_rabin(n, a):
"""
Miller-Rabin Primality Test
Returns true if n is a (probable) prime
Returns false if n is a composite number
"""
s = 0
d = n - 1
while d % 2 == 0:
s = s + 1
d = d >> 1
x = square_and_multiply(a, d, n)
if x != 1 and x + 1 != n:
f... | 12,390 |
def luhn_sum_v1(num):
"""
First version of luhn_sum; uses a list which it modifies in-place.
"""
nums = [int(i) for i in reversed(str(num))]
for i in xrange(1, len(nums), 2):
nums[i] *= 2
return sum(sum(divmod(i, 10)) for i in nums) | 12,391 |
def build(c):
"""Build"""
c.run(f"{sys.executable} setup.py sdist bdist_wheel") | 12,392 |
def get_rate_discounted_rate(item_code, customer, company, so_number = None):
""" This function is use to get discounted rate and rate """
item_group = frappe.get_value("Item", item_code, 'item_group')
# parent_item_group = frappe.get_value("Item Group", item_group, 'parent_item_group')
count = frappe.db.sql(f"""
... | 12,393 |
def lambda_handler(event: Dict[str, Any], context: Dict[str, Any]) -> str:
"""
Lambda function to parse notification events and forward to Slack
:param event: lambda expected event object
:param context: lambda expected context object
:returns: none
"""
if os.environ.get("LOG_EVENTS", "Fals... | 12,394 |
def sum_obs_np(A):
"""summation over axis 0 (obs) equivalent to np.sum(A, 0)"""
return np.einsum("ij -> j", A) if A.ndim > 1 else np.sum(A) | 12,395 |
def _macos_command_line_infoplist_impl(ctx):
"""Implementation of the internal `macos_command_line_infoplist` rule.
This rule is an internal implementation detail of
`macos_command_line_application` and should not be used directly by clients.
It merges Info.plists as would occur for a bundle but then p... | 12,396 |
def get_custom_data_format(*args):
"""
get_custom_data_format(dfid) -> data_format_t
Get definition of a registered custom data format.
@param dfid: data format id (C++: int)
@return: data format definition or NULL
"""
return _ida_bytes.get_custom_data_format(*args) | 12,397 |
def memory(info, func, expr):
"""
checks if the function has been called with the same argument previously and
if so, returns the same results instead of running the function again
args:
-
"""
rows=None
if info:
if func in info.evaluated:
if expr in info.evaluated[func]:
rows = info... | 12,398 |
def install_common_tool():
"""
Install many of the tool that I use for my day to day work. Other might want to
modify this function.
"""
config_bashrc()
install_apt_pkg()
install_nvtop()
install_pip_dependencies()
install_gdrive_rclone()
install_iterm_shell_integration()
inst... | 12,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.