content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main_page(request) :
"""Renders main page and gets the n (matrix demension number)"""
if request.method != 'POST' :
form = InputForm()
else :
form = InputForm(data=request.POST)
if form.is_valid() :
return redirect('calculator:set_demensions')
context ... | 20,000 |
def test_import():
"""Check if the app modules can be imported."""
from libpdf import core # pylint: disable=import-outside-toplevel
del core | 20,001 |
def int2fin_reference(n):
"""Calculates a checksum for a Finnish national reference number"""
checksum = 10 - (sum([int(c) * i for c, i in zip(str(n)[::-1], it.cycle((7, 3, 1)))]) % 10)
return "%s%s" % (n, checksum) | 20,002 |
def COLSTR(str, tag):
"""
Utility function to create a colored line
@param str: The string
@param tag: Color tag constant. One of SCOLOR_XXXX
"""
return SCOLOR_ON + tag + str + SCOLOR_OFF + tag | 20,003 |
def get_instance_pricing(instance_types):
"""
Get the spot and on demand price of an instance type
in all the regions at current instant
:param instance_types: EC2 instance type
:return: a pandas DataFrame with columns as
region, spot price and on demand price
"""
all_regions = ... | 20,004 |
def run_origami_bootsteps():
"""
Run bootsteps to configure origamid.
This includes the following
* Configure web server logging
* Configure Database
* Validating origami configs.
"""
logging.info('Running origami bootsteps')
origami_config_dir = os.path.join(os.environ['HOME'], ORI... | 20,005 |
async def get_user_groups(request):
"""Returns the groups that the user in this request has access to.
This function gets the user id from the auth.get_auth function, and passes
it to the ACL callback function to get the groups.
Args:
request: aiohttp Request object
Returns:
If th... | 20,006 |
def plot_bivariate_correlations(df, path=None, dpi=150):
"""
Plots heatmaps of 2-variable correlations to the Target function
The bivariate correlations are assmebled using both the arithmatic and geometric means for
two subplots in the figure.
Parameters
----------
df: dataframe
path: ... | 20,007 |
def create_datastream(dataset_path, **kwargs):
""" create data_loader to stream images 1 by 1 """
from torch.utils.data import DataLoader
if osp.isfile(osp.join(dataset_path, 'calibration.txt')):
db = ETH3DStream(dataset_path, **kwargs)
elif osp.isdir(osp.join(dataset_path, 'image_left')):
... | 20,008 |
def is_contained(target, keys):
"""Check is the target json object contained specified keys
:param target: target json object
:param keys: keys
:return: True if all of keys contained or False if anyone is not contained
Invalid parameters is always return False.
"""
if not target or not key... | 20,009 |
def map(x, in_min, in_max, out_min, out_max):
"""
Map a value from one range to another
:param in_min: minimum of input range
:param in_max: maximum of input range
:param out_min: minimum of output range
:param out_max: maximum of output range
:return: The value scaled ... | 20,010 |
def show(Z, type_restrict, restrict, result, row, col):
"""
[construct and show the functions]
Arguments:
Z {[list]} -- [list Z values]
type_restrict {[int]} -- [<= or >=]
restrict {[list]} -- [list of all restrictions]
result {[list]} -- [list of results from each r... | 20,011 |
def get_points(sess: requests.Session, console: Console, status: Status, projectID: int):
"""
Get all exisiting points in a project
"""
base_url = f"https://mapitfast.agterra.com/api/Points"
resp = sess.get(base_url, params={"projectId": projectID})
points_obj_list = list()
for raw_resp in ... | 20,012 |
def verify_source(
models: List[AOTCompiledTestModel],
accel="ethos-u55-256",
):
"""
This method verifies the generated source from an NPU module by building it and running on an FVP.
"""
interface_api = "c"
test_runner = _create_test_runner(accel)
run_and_check(
models,
... | 20,013 |
def calculate_discounted_returns(rewards):
"""
Calculate discounted reward and then normalize it
(see Sutton book for definition)
Params:
rewards: list of rewards for every episode
"""
returns = np.zeros(len(rewards))
next_return = 0 # 0 because we start at the last timestep
for... | 20,014 |
def mock_tensorboard(logdir, host, port, print_nonsense, print_nothing,
address_in_use, sleep_time):
"""Run fake TensorBoard."""
if logdir is None:
print('A logdir must be specified. Run `tensorboard --help` for '
'details and examples.')
return -1
elif pri... | 20,015 |
def parse_binskim_old(bin_an_dic, output):
"""Parse old version of binskim."""
current_run = output['runs'][0]
if 'results' in current_run:
rules = output['runs'][0]['rules']
for res in current_run['results']:
if res['level'] != 'pass':
if len(res['formattedRuleMe... | 20,016 |
def binary_elementwise_compute(
ifm: te.Tensor,
ifm2: te.Tensor,
lut: te.Tensor,
operator_type: str,
ifm_scale: float,
ifm_zero_point: int,
ifm2_scale: float,
ifm2_zero_point: int,
ofm_scale: float,
ofm_zero_point: int,
ifm_channels: int,
ifm2_channels: int,
reversed_... | 20,017 |
def start_metronome(aux):
"""Function that starts a metronome, with
the beat durations being calculated from the
BPM. If a time signature is given, two different notes
are used to set it."""
global metronome_on
metronome_on = True
seq = sequencers[1][1]
synthID = sequencers[1][2]
start = 0
bpm = aux.get("bpm"... | 20,018 |
def main(ts, fastARG_executable, fa_in, fa_out, nodes_fh, edges_fh, sites_fh, muts_fh):
"""
This is just to test if fastarg produces the same haplotypes
"""
import subprocess
seq_len = ts.get_sequence_length()
ts_to_fastARG_in(ts, fa_in)
subprocess.call([fastARG_executable, 'build', fa_in.na... | 20,019 |
def x_power_dependence(n, dep_keys, ctfs=list(), force_zero=None, **kwargs):
"""Returns a fit function that allows x^n depdendence on the constants
associated with each of the dep_keys
y(x) = (a0 * b0 + a1 * b1 + ...) * x^n
where each of the a's are fit parameters and each of the b's are either
... | 20,020 |
def get_subseqs(s, ops):
"""Returns a list of sequences given when applying the list of (ops)
on them, until a constant one is found, thus:
new[0] = next seq of s with ops[0]
new[i] = next seq of new[i-1] with op[i]
If 'ops' is not a list, then the same operation will be repeated... | 20,021 |
def read_hst_siaf(file=None):#, AperNames=None):
"""Read apertures from HST SIAF file and return a collection.
This was partially ported from Lallo's plotap.f.
Parameters
----------
file : str
AperNames : str list
Returns
-------
apertures: dict
Dictionary of apertures
... | 20,022 |
def upload_model(model_file, name, tags=None):
"""Upload a tflite model file to the project and publish it."""
# Load a tflite file and upload it to Cloud Storage
print('Uploading to Cloud Storage...')
model_source = ml.TFLiteGCSModelSource.from_tflite_model_file(model_file)
# Create the model object
tflit... | 20,023 |
def glyphstr_center(gls, width=100):
""" given a width of an area (such as column heading width) it will adjust the start point of each glyph in a glyphstr_, centering the string
"""
length = glyphstr_length(gls)
glen = len(gls)
#addlen = (width-length)/(glen))
print length
print width - length
hl = (width-leng... | 20,024 |
def update_s(C,k):
"""
Args: C: 2d array
k: 1d array
Return: 1d array
"""
if np.shape(C)[0]==0:
s = np.array([1])
else:
temp = np.dot(C,k)
s = np.append(temp,1)
return s | 20,025 |
def test_handler_callback_failure():
"""Test failure mode for inappropriate handlers."""
class BadHandler(object):
def handler(self, one):
return 'too many'
ob = EventTest()
handler = BadHandler()
with pytest.raises(TypeError):
ob.PublicEvent += handler.handler
... | 20,026 |
def main_stage(game_ongoing: bool = True):
"""
Main function to let the two computer players actively play. This includes drawing cards, playing cards,
and interacting for the specialty cards (7, 8, and J)
Args:
game_ongoing: boolean which changes once the winning condition has been reached to e... | 20,027 |
def test_CenteredParameter_column():
"""Tests probflow.parameters.CenteredParameter w/ center_by=column + 2D"""
# Create the parameter
param = CenteredParameter([5, 6], center_by="column")
# posterior_mean should return mean
sample1 = param.posterior_mean()
sample2 = param.posterior_mean()
... | 20,028 |
def get_chord_type(chord):
"""'Parses' input for a chord and returns the type of chord from it"""
cleaned_chord = chord[1:]
cleaned_chord = cleaned_chord.replace('b', '')
cleaned_chord = cleaned_chord.replace('#', '')
mapping = {
'7': 'seven',
'9': 'nine',
'm7': 'minor7',
... | 20,029 |
def compile_stats(path):
""" combines all items from the given folder of stats arrays """
df = pd.DataFrame()
for item in os.listdir(path):
print(item)
with open(path + '/' + item, 'rb') as file:
df1 = pickle.load(file)
# df1 = df1.loc[df1.pred_var < 1.0]
... | 20,030 |
def transpile(model: Union[SympyOpt, Model]) -> SympyOpt:
"""Transpile optimization problem into SympyOpt model
Only accepts SympyOpt or Docplex model.
:param model: model to be transpiled
:raises ValueError: if the argument is of inappropriate type
:return: transpiled model
"""
if isinsta... | 20,031 |
def definition():
"""View of the finances with subtotals generated."""
return sql.format(source=source) | 20,032 |
def random_mini_batches(X, Y, mini_batch_size = 32, seed = 0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)
Y -- true "label" vector (containing 0 if control, 1 if case), of shape (1, number of examples) (... | 20,033 |
def file_base_features(path, record_type):
"""Return values for BASE_SCHEMA features."""
base_feature_dict = {
"record_id": path,
"record_type": record_type,
# "utc_last_access": os.stat(path).st_atime,
"utc_last_access": 1600000000.0,
}
return base_feature_dict | 20,034 |
def split_ref(ref):
"""
セル参照をセル文字と1ベース行番号文字に分割する。
Params:
ref(str):
Returns:
Tuple[str, str]: 列、行
"""
m = re_cellref.match(ref)
if m:
return m.group(1), m.group(2)
return None, None | 20,035 |
def table_definition(dataset):
"""print an azure synapse table definition for a kartothek dataset"""
index_col = list(dataset.dataset_metadata.index_columns)[
0
] ##works only with one index column
cols = synapse_columns(
dataset.dataset_metadata.table_meta[dataset.table], index_col
... | 20,036 |
def test_home(client, db):
"""
GIVEN a user who wants to visit the home page
WHEN he accesses the page
THEN assert the right page is sent
"""
page = "/"
response = client.get(page)
assert response.status_code == 200
assertTemplateUsed(response, "core/home.html") | 20,037 |
def identify_image_set(imagedir, image_names_pattern):
"""
Find all the images within the *imagedir*.
:param imagedir:
:param image_names_pattern:
:return: a list of image names that are part of the image set
"""
image_names_from_os = sorted(os.listdir(imagedir))
image_names = [re_identi... | 20,038 |
def node_extractor(dataframe, *columns):
"""
Extracts the set of nodes from a given dataframe.
:param dataframe: dataframe from which to extract the node list
:param columns: list of column names that contain nodes
:return: list of all unique nodes that appear in the provided dataset
"""
dat... | 20,039 |
def _get_bag(environ, bag_name):
"""
Get the named bag out of the store.
"""
store = environ['tiddlyweb.store']
bag = Bag(bag_name)
try:
bag = store.get(bag)
except NoBagError as exc:
raise HTTP404('%s not found, %s' % (bag.name, exc))
return bag | 20,040 |
def missing_values_operation(files):
"""Will take iterable file objects and eliminate features or samples with missing values or inputing missing values if necessary"""
for i in files:
with open(i,'rw') as f:
if missing_values(f)==True:
file_data=load_data(i)
... | 20,041 |
def remove_from_repo_history(repo_source: str, drop_files: Sequence[str],
github_token: str, keep_backup: bool = True,
auto_push_remove: bool = False, backup_dir: Optional[str] = None,
follow_renames: bool = True):
"""
Remove... | 20,042 |
def _object_id(value):
"""Return the object_id of the device value.
The object_id contains node_id and value instance id
to not collide with other entity_ids.
"""
object_id = "{}_{}".format(slugify(_value_name(value)),
value.node.node_id)
# Add the instance id if... | 20,043 |
def sentence_length_distribution(trainFile="atec/training.csv"):
"""
分析训练数据中句子长度分布
"""
raw_data = read_cut_file(file_path=trainFile, with_label=True)
df=pd.DataFrame(raw_data)
level=["w","c"]
for l in level:
s1="sent1"+l+"_len"
print(df.loc[df[s1].argmax()])
print(df[... | 20,044 |
def _apply_attention_constraint(
e, last_attended_idx, backward_window=1, forward_window=3
):
"""Apply monotonic attention constraint.
**Note** This function is copied from espnet.nets.pytorch_backend.rnn.attention.py
"""
if e.size(0) != 1:
raise NotImplementedError(
"Batch atten... | 20,045 |
def RetryInvocation(return_handler, exc_handler, max_retry, functor, *args,
**kwds):
"""Generic retry loop w/ optional break out depending on exceptions.
Generally speaking you likely want RetryException or RetryReturned
rather than this; they're wrappers around this and are friendlier for
... | 20,046 |
def parse_reolink(email):
"""Parse Reolink tracking numbers."""
tracking_numbers = []
soup = BeautifulSoup(email[EMAIL_ATTR_BODY], 'html.parser')
links = [link.get('href') for link in soup.find_all('a')]
for link in links:
if not link:
continue
match = re.search('qtc_tLa... | 20,047 |
def main():
"""
Función principal que invoca a los servicios para crear, insertar, actualizar, obtener y eliminar datos de la base de datos
Descomentar para realizar las acciones (en caso de que estén comentadas)
"""
# Crea una instancia de la clase Crud
crud = Crud(DB_FILE)
# =============... | 20,048 |
def BuildObjcDoc(api):
"""Builds documentation for the Objective-C variant of engine."""
checkout = GetCheckoutPath(api)
with api.os_utils.make_temp_directory('BuildObjcDoc') as temp_dir:
objcdoc_cmd = [checkout.join('flutter/tools/gen_objcdoc.sh'), temp_dir]
with api.context(cwd=checkout.join('flutter'))... | 20,049 |
def setting_modules(app, modules):
""" 注册Blueprint模块 """
for module, url_prefix in modules:
app.register_blueprint(module, url_prefix = url_prefix) | 20,050 |
def HMF(state, Delta, N):
"""Computes the result of the MF hamiltonian acting on a given state."""
#kinetic term: sum_i(eps(i)*(n_i,up + n_i,down))
kinetic_state = dict_list_sum(
[dict_prod(eps(i, N), dict_sum(number_op(state, i, 0, N), number_op(state, i, 1, N))) for i in range(N)])
#interaction term: sum_i( ... | 20,051 |
def make_baseline_curve(df,num_iterations):
""" Makes a ROC curve for logistic regression trained on average product rating only,
for comparison with user-specific predictions which use both product avg rating as
well as computed similarity scores. """
factory = lr_wrapper(df,feature_columns=['rating_mean'],y_colu... | 20,052 |
def calculate_probability_of_multicoincidence(ambient_size: int = 0,
set_sizes: tuple = (),
intersection_size: int = 0):
"""
Calculates the probability that subsets of a set of a given size, themselves of
prescribed ... | 20,053 |
def flush_queue(queue):
"""
Flush the queue.
:param queue: queue to flush
:return: Nothing
"""
while True:
try:
queue.get(block=False)
except Empty:
break | 20,054 |
def check_date(option, opt, value):
"""check a file value
return the filepath
"""
try:
return DateTime.strptime(value, "%Y/%m/%d")
except DateTime.Error :
raise OptionValueError(
"expected format of %s is yyyy/mm/dd" % opt) | 20,055 |
def no_cloud_fixture():
"""Multi-realization cloud data cube with no cloud present."""
cloud_area_fraction = np.zeros((3, 10, 10), dtype=np.float32)
thresholds = [0.265, 0.415, 0.8125]
return cloud_probability_cube(cloud_area_fraction, thresholds) | 20,056 |
def main(ctx, endpoint, debug):
""" Command-line Interface for the fortune cookie service
"""
if ctx.obj is None:
ctx.obj = {}
ctx.obj['endpoint'] = endpoint
if ctx.invoked_subcommand is None:
cmd_fortune(ctx) | 20,057 |
def stats_imputation_stats():
"""Get statistics related to missing values"""
seoul_stn_code = 108
station_name = "종로구"
input_dir = Path("/input")
aes_dir = input_dir / "aerosol"
wea_dir = input_dir / "weather" / "seoul"
data_dir = Path("/mnt/data/")
stat_dir = Path("/mnt/data/impute_sta... | 20,058 |
async def download_file(self, Bucket, Key, Filename, ExtraArgs=None,
Callback=None, Config=None):
"""Download an S3 object to a file.
Usage::
import boto3
s3 = boto3.resource('s3')
s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')
Simi... | 20,059 |
def status():
"""
Print the statuses of all datasets in the schema.
"""
max_id_len = SCHEMA["id"].apply(len).max()
for _, dataset in SCHEMA.iterrows():
dataset_id = dataset["id"]
dataset_type = dataset["type"]
downloaded_name = dataset["downloaded_name"]
id_bold... | 20,060 |
def make_slicer_query(
database: Database,
base_table: Table,
joins: Iterable[Join] = (),
dimensions: Iterable[Field] = (),
metrics: Iterable[Field] = (),
filters: Iterable[Filter] = (),
orders: Iterable = (),
):
"""
Creates a pypika/SQL query from a list of slicer elements.
Thi... | 20,061 |
def build_grid_generator(cfg, input_shape):
"""
Built an grid generator from `cfg.MODEL.GRID_GENERATOR.NAME`.
"""
grid_generator = cfg.MODEL.GRID_GENERATOR.NAME
return GRID_GENERATOR_REGISTRY.get(grid_generator)(cfg, input_shape) | 20,062 |
def main_page(request):
"""
This function is used to display the main page of programme_curriculum
@param:
request - contains metadata about the requested page
"""
return render(request, 'programme_curriculum/mainpage.html') | 20,063 |
def nt_recv_capture_rx_test(dut):
"""Test bench main function."""
# start the clock
cocotb.fork(clk_gen(dut.clk, CLK_FREQ_MHZ))
# do not issue software reset
dut.rst_sw <= 0
# reset the dut
yield rstn(dut.clk, dut.rstn)
# instantiate an AXI4-Stream writer, connect and reset it
axi... | 20,064 |
def _write_detailed_dot(graph, dotfilename):
"""Create a dot file with connection info
digraph structs {
node [shape=record];
struct1 [label="<f0> left|<f1> mid\ dle|<f2> right"];
struct2 [label="<f0> one|<f1> two"];
struct3 [label="hello\nworld |{ b |{c|<here> d|e}| f}| g | h"];
struct1:f1... | 20,065 |
def ResidualBlock(name, input_dim, output_dim, filter_size, inputs, resample=None, he_init=True, bn=False):
"""
resample: None, 'down', or 'up'
"""
if resample=='down':
conv_shortcut = MeanPoolConv
conv_1 = functools.partial(lib.ops.conv2d.Conv2D, input_dim=input_dim, output... | 20,066 |
def callback_save_poly():
"""Perform polyfit once regions selected
Globals: cal_fname, data (read-only, so no declaration)
"""
import pylleo
import yamlord
def _check_param_regions(param, regions, cal_dict):
msg = """
<b>{}</b> was not found in the calibration dictionary.... | 20,067 |
def timer(func):
"""Logging elapsed time of funciton (decorator)."""
@wraps(func)
def wrapper(*args, **kwargs):
with timing(func.__name__):
return func(*args, **kwargs)
return wrapper | 20,068 |
def peak_ana(x, y, nb=3, plotpoints_axis=None):
""" nb = number of point (on each side) to use as background"""
## get background
xb = np.hstack((x[0:nb], x[-(nb):]))
yb = np.hstack((y[0:nb], y[-(nb):]))
a = np.polyfit(xb, yb, 1)
b = np.polyval(a, x)
yf = y - b
yd = np.diff(yf)
## d... | 20,069 |
def raisealert(severity, msg, process_name=None):
""" Writes the alert message"""
#timeStr=str(time.ctime())
if process_name is not None:
log = '['+severity +']'+" " + '['+process_name+']' + " " + msg +"\n"
else:
log = '['+severity+']' + " " + msg +"\n"
logging.basicConfig(level=lo... | 20,070 |
def run_benchmarks(benchmark_params, test_root, force=False):
"""Run the benchmarks
For every row in benchmark params, run a trace on the input video
using the params specified.
benchmark_params: DataFrame with columns corresponding to keywords
to pass to pipeline_trace. Should have co... | 20,071 |
def floodPacket(con, inport, packet, buf, bufid=None):
"""Flood a packet on a switch
"""
sendCommand(con, FloodPacketCommand(inport, packet, buf, bufid))
print con, "flooded packet" | 20,072 |
def sample_sep01(nn, xi=1., beta=0.):
"""
Samples from the skew exponential power distribution with location zero and scale one.
Definition
----------
def sample_sep01(nn, xi=1., beta=0.):
Input
-----
nn number of samples
Optional Input
... | 20,073 |
def pandas_from_feather(file: str = None) -> pd.DataFrame:
""" Load a feather file to a pandas DataFrame.
Uses pyarrow to load a csv file into a [pyarrow.Table](https://arrow.apache.org/docs/python/generated/pyarrow.Table.html) and convert to pandas format.
Args:
file (str): the feathe... | 20,074 |
def _get_user_name():
"""
Get the current user.
"""
return pwd.getpwuid(os.getuid())[0] | 20,075 |
async def save_monobank_info(pools, telegram_id, token):
"""Retrieve user's data by his token from monobank API."""
endpoint = f"{MONOBANK_API}/personal/client-info"
headers = {"X-Token": token}
http, postgres = pools["http"], pools["postgres"]
response, status = await http.get(url=endpoint, header... | 20,076 |
def email_coas():
"""
Email certificates of analysis to their recipients.
"""
# Get the certificate data.
# Email links (optional attachments) to the contacts.
return NotImplementedError | 20,077 |
def after_cv_imshow():
"""name
close all the show window if press 'esc'
set after cv2.imshow()
Args:
Returns:
"""
k = cv2.waitKey(0)
if k == 27:
cv2.destroyAllWindows() | 20,078 |
def dropout(x, key, keep_rate):
"""Implement a dropout layer.
Arguments:
x: np array to be dropped out
key: random.PRNGKey for random bits
keep_rate: dropout rate
Returns:
np array of dropped out x
"""
# The shenanigans with np.where are to avoid having to re-jit if
# keep rate changes.
... | 20,079 |
def test_make_all_master_seals(m_single, m_multi, prom_edit):
""" Test the make_all_master_seals method """
prom_edit.make_all_master_seals()
m_single.assert_called_once_with(prom_edit._game_config["items"]["offsets"], 2)
m_multi.assert_called_once_with(prom_edit._game_config["items"]["offsets"], 2) | 20,080 |
def band_spd_spin_polarized(
folder,
output='band_spd_sp.png',
scale_factor=2,
order=['s', 'p', 'd'],
color_dict=None,
legend=True,
linewidth=0.75,
band_color='black',
unprojected_band_color='gray',
unprojected_linewidth=0.6,
fontsize=7,
annotations=['$\\uparrow$ ', '$\\d... | 20,081 |
def initial_queries(bo):
"""
script which explores the initial query points of a BayesianOptimization
instance, reports errors to Slack
Input: instance of a BayesianOptimization
"""
# loop to try a second time in case of error
errcount = 0
for i in range(2):
try:
bo.m... | 20,082 |
def _parse_start_test_log(start_test_log):
"""Parse start_test logfile and return results in python data structure.
:type start_test_log: str
:arg start_test_log: start_test log filename
:rtype: list of dicts
:returns: list of dicts; each dict contains info about a single test case
"""
log... | 20,083 |
def cell2AB(cell):
"""Computes orthogonalization matrix from unit cell constants
:param tuple cell: a,b,c, alpha, beta, gamma (degrees)
:returns: tuple of two 3x3 numpy arrays (A,B)
A for crystal(x) to Cartesian(X) transformations A*x = np.inner(A,x) =X
B (= inverse of A) for Cartesian to c... | 20,084 |
def test_fun_run() -> None:
"""Test running python function."""
cmd = p.python_funsie(
capitalize, inputs={"in": Encoding.blob}, outputs={"in": Encoding.blob}
)
inp = {"in": BytesIO(b"bla bla bla")}
out = p.run_python_funsie(cmd, inp)
assert out["in"] == b"BLA BLA BLA" | 20,085 |
def deploy():
"""Push to GitHub pages"""
env.msg = git.Repo().active_branch.commit.message
clean()
preview()
local("ghp-import {deploy_path} -m \"{msg}\" -b {github_pages_branch}".format(**env))
local("git push origin {github_pages_branch}".format(**env)) | 20,086 |
def _parse_header(line: bytes) -> Tuple[HeaderLine, bytes]:
"""
Parse the header line of the received input.
:param line:
:return: a tuple of the parsed header and the remaining input that is not
part of the header.
"""
end_index = line.find(b"\r\n")
header, remaining = line[:end_in... | 20,087 |
def sendMessage(qry):
"""
Message sending handling, either update if the query suggests it otherwise send the message.
:param qry: current query
:return: Status of Message sending.
"""
try: getUserName()
except: return _skypeError()
if(qry == "skype update"):
_writeFriends()
... | 20,088 |
def scrape_detail_page(response):
"""
get detail page info as dict type
"""
root = lxml.html.fromstring(response.content)
ebook = {
'url': response.url,
'title': root.cssselect('#bookTitle')[0].text_content(),
'price': root.cssselect('.buy')[0].text,
'content': [h3.te... | 20,089 |
def reload_from_numpy(device, metadata, reload_dir):
"""Reload the output of voice conversion model."""
conv_mels = []
for pair in tqdm(metadata["pairs"]):
file_path = Path(reload_dir) / pair["mel_path"]
conv_mel = torch.load(file_path)
conv_mels.append(conv_mel.to(device))
retur... | 20,090 |
def jaccard_similarity_coefficient(A, B, no_positives=1.0):
"""Returns the jaccard index/similarity coefficient between A and B.
This should work for arrays of any dimensions.
J = len(intersection(A,B)) / len(union(A,B))
To extend to probabilistic input, to compute the intersection, use ... | 20,091 |
def get_argument_from_call(call_node: astroid.Call,
position: int = None,
keyword: str = None) -> astroid.Name:
"""Returns the specified argument from a function call.
:param astroid.Call call_node: Node representing a function call to check.
:param int... | 20,092 |
def snake_string(ls):
"""
Question 7.11: Write a string sinusoidally
"""
result = []
strlen = len(ls)
for idx in xrange(1, strlen, 4):
result.append(ls[idx])
for idx in xrange(0, strlen, 2):
result.append(ls[idx])
for idx in xrange(3, strlen, 4):
result.append(l... | 20,093 |
def _prepare_memoization_key(args, kwargs):
"""
Make a tuple of arguments which can be used as a key
for a memoized function's lookup_table. If some object can't be hashed
then used its __repr__ instead.
"""
key_list = []
for arg in args:
try:
hash(arg)
key_li... | 20,094 |
def processing_other_notification(
notification:Notification,
api:Mastodon
) -> None:
"""
Обработка уведомления в остальных случаях
:param notification: Объект с информацией уведомления
:type notification: Notification
:param api: API обращения к Mastodon
:type api: Mastodon
"""
... | 20,095 |
def kl_divergence_with_logits(p_logits = None,
q_logits = None,
temperature = 1.):
"""Compute the KL between two categorical distributions from their logits.
Args:
p_logits: [..., dim] array with logits for the first distribution.
q_logits: [..., ... | 20,096 |
def show_slices(
data3d,
contour=None,
seeds=None,
axis=0,
slice_step=None,
shape=None,
show=True,
flipH=False,
flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None,
kwargs_contour=None,
):
"""
Show slices as til... | 20,097 |
def convert_bosch_datetime(dt: Any = None) -> datetime:
"""Create a datetime object from the string (or give back the datetime object) from Bosch. Checks if a valid number of milliseconds is sent."""
if dt:
if isinstance(dt, str):
if dt.find(".") > 0:
return datetime.strptime... | 20,098 |
def day_log_add_id(day_log):
"""
その日のログにID(day_id)を割り振る
:param day_log:
:return:
"""
for v in range(len(day_log)):
day_log[v]['day_id'] = v + 1
return day_log | 20,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.