content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def lean_left(context: TreeContext, operators: AbstractSet[str]):
"""
Turns a right leaning tree into a left leaning tree:
(op1 a (op2 b c)) -> (op2 (op1 a b) c)
If a left-associative operator is parsed with a right-recursive
parser, `lean_left` can be used to rearrange the tree structure
... | 1,400 |
def _pattern_data_from_form(form, point_set):
"""Handles the form in which the user determines which algorithms
to run with the uploaded file, and computes the algorithm results.
Args:
form: The form data
point_set: Point set representation of the uploaded file.
Returns:
Musical pattern discovery results of... | 1,401 |
def run_proc(*args, **kwargs):
"""Runs a process, dumping output if it fails."""
sys.stdout.flush()
proc = subprocess.Popen(
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
*args,
**kwargs
)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
print("\n%s: exited with %d... | 1,402 |
def test_retries_jitter_single_jrc_down(mock_random):
"""Jitter with single float input and jrc < 1."""
j = pypyr.retries.jitter(sleep=100, jrc=0.1)
assert j(0) == 999
assert j(1) == 999
assert j(2) == 999
assert mock_random.mock_calls == [call(10, 100),
ca... | 1,403 |
def group(help_doc):
"""Creates group options instance in module options instnace"""
return __options.group(help_doc) | 1,404 |
def test_bfgs6(dtype, func_x0):
"""
Feature: ALL TO ALL
Description: test cases for bfgs in PYNATIVE mode
Expectation: the result match scipy
"""
func, x0 = func_x0
x0 = x0.astype(dtype)
x0_tensor = Tensor(x0)
ms_res = msp.optimize.minimize(func(mnp), x0_tensor, method='BFGS',
... | 1,405 |
def convert_pdf_to_txt(path, pageid=None):
"""
This function scrambles the text. There may be values for LAParams
that fix it but that seems difficult so see getMonters instead.
This function is based on convert_pdf_to_txt(path) from
RattleyCooper's Oct 21 '14 at 19:47 answer
edited by Trenton ... | 1,406 |
def get_available_port(preferred_port: Optional[int] = None) -> int:
"""Finds an available port for use in webviz on localhost. If a reload process,
it will reuse the same port as found in the parent process by using an inherited
environment variable.
If preferred_port is given, ports in the range [pre... | 1,407 |
def safe_str(val, default=None):
"""Safely cast value to str, Optional: Pass default value. Returned if casting fails.
Args:
val:
default:
Returns:
"""
if val is None:
return default if default is not None else ''
return safe_cast(val, str, default) | 1,408 |
def mod2():
"""
Create a simple model for incorporation tests
"""
class mod2(mod1):
def __init__(self, name, description):
super().__init__(name, "Model 1")
self.a = self.createVariable("a",dimless,"a")
self.b = self.createVariable("b",dimless,"b")
... | 1,409 |
def plot_numu_hists(events, ev, save_path, energy=r"E (GeV)"):
"""Plot the eff and pur plot vs neutrino energy.
Args:
events (dict): events output
ev (pd.DataFrame): events DataFrame
save_path (str): path to save plot to
"""
fig, axs = plt.subplots(1, 1, figsize=(12, 8))
bin... | 1,410 |
def zero_order(freq,theta,lcandidat,NumTopic):
"""
Calculate the Zero-Order Relevance
Parameters:
----------
freq : Array containing the frequency of occurrences of each word in the whole corpus
theta : Array containing the frequency of occurrences of each word in each topic
lcandidat: Arra... | 1,411 |
def compute_check_letter(dni_number: str) -> str:
"""
Given a DNI number, obtain the correct check letter.
:param dni_number: a valid dni number.
:return: the check letter for the number as an uppercase, single character
string.
"""
return UPPERCASE_CHECK_LETTERS[int(dni_number) % 23] | 1,412 |
def print_properties_as_table(
cmd_ctx, properties, table_format, show_list=None):
"""
Print properties in tabular output format.
The order of rows is ascending by property name.
The spinner is stopped just before printing.
Parameters:
cmd_ctx (CmdContext): Context object of the com... | 1,413 |
def p_boolean_expression(p):
"""boolean_expression : expression
""" | 1,414 |
def uptime_check(delay=1):
"""Performs uptime checks to two URLs
Args:
delay: The number of seconds delay between two uptime checks, optional, defaults to 1 second.
Returns: A dictionary, where the keys are the URL checked, the values are the corresponding status (1=UP, 0=DOWN)
"""
urls =... | 1,415 |
def entropy_column(input):
"""returns column entropy of entropy matrix.
input is motifs"""
nucleotides = {'A': 0, 'T': 0, 'C': 0, 'G': 0}
for item in input:
nucleotides[item] = nucleotides[item]+1
for key in nucleotides:
temp_res = nucleotides[key]/len(input)
if temp_res > 0:... | 1,416 |
def assert_array_almost_equal_nulp(x: numpy.float64, y: numpy.float64):
"""
usage.scipy: 1
"""
... | 1,417 |
def truncate(path, length, **kwargs):
"""
Truncate the file corresponding to path, so that it is at most length bytes in size.
:param path: The path for the file to truncate.
:param length: The length in bytes to truncate the file to.
:param kwargs: Common SMB Session arguments for smbclient.
"... | 1,418 |
def get_partner_from_token(access_token):
"""
Walk the token->client->user->partner chain so we can
connect the the `LinkageEntity` row to a `PartnerEntity`
"""
tok = OauthAccessTokenEntity.query.filter_by(
access_token=access_token).one_or_none()
log.debug("get_partner_from_token found:... | 1,419 |
def sumVoteCount(instance):
""" Returns the sum of the vote count of the instance.
:param instance: The instance.
:type instance: preflibtools.instance.preflibinstance.PreflibInstance
:return: The sum of vote count of the instance.
:rtype: int
"""
return instance.sumVoteCount | 1,420 |
def left_d_threshold_sequence(n,m):
"""
Create a skewed threshold graph with a given number
of vertices (n) and a given number of edges (m).
The routine returns an unlabeled creation sequence
for the threshold graph.
FIXME: describe algorithm
"""
cs=['d']+['i']*(n-1) # cre... | 1,421 |
def write_json(obj, filename):
"""
Write a json file, if the output directory exists.
"""
if not os.path.exists(os.path.dirname(filename)):
return
return write_file(sjson.dump(obj), filename) | 1,422 |
def get_user_solutions(username):
"""Returns all solutions submitted by the specified user.
Args:
username: The username.
Returns:
A solution list.
Raises:
KeyError: If the specified user is not found.
"""
user = _db.users.find_one({'_id': username})
if not user:
... | 1,423 |
def get_terms_kullback_leibler(output_dir):
"""Returns all zero-order TERMs propensities of structure"""
if output_dir[-1] != '/':
output_dir += '/'
frag_path = output_dir + 'fragments/'
designscore_path = output_dir + 'designscore/'
terms_propensities = dict()
terms = [f.split('.')[0] f... | 1,424 |
def add_standard_attention_hparams(hparams):
"""Adds the hparams used by get_standadized_layers."""
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
# hparams used and which should have been defined outside (in
# common_hparams):
# Global flags
# hparams... | 1,425 |
def make_conv2d_layer_class(strides, padding):
"""Creates a `Conv2DLayer` class.
Args:
strides: A 2-tuple of positive integers. Strides for the spatial dimensions.
padding: A Python string. Can be either 'SAME' or 'VALID'.
Returns:
conv2d_layer_class: A new `Conv2DLayer` class that closes over the a... | 1,426 |
def get_df1_df2(X: np.array, y: np.array) -> [DataFrame, DataFrame]:
"""
Get DataFrames for points with labels 1 and -1
:param X:
:param y:
:return:
"""
x1 = np.array([X[:, i] for i in range(y.shape[0]) if y[i] == 1]).T
x2 = np.array([X[:, i] for i in range(y.shape[0]) if y[i] ==... | 1,427 |
def olog_savefig(**kwargs):
"""Save a pyplot figure and place it in tho Olog
The **kwargs are all passed onto the :func savefig: function
and then onto the :func olog" function
:returns: None
"""
fig = save_pyplot_figure(**kwargs)
if 'attachments' in kwargs:
if isinstance(kwargs['a... | 1,428 |
def directory_iterator(source, target):
"""
Iterates through a directory and symlinks all containing files in a target director with the same structure
:param source: Directory to iterate through
:param target: Directory to symlink files to
"""
for file in os.listdir(source):
filename = ... | 1,429 |
def dnsip6encode(data):
"""
encodes the data as a single IPv6 address
:param data: data to encode
:return: encoded form
"""
if len(data) != 16:
print_error("dnsip6encode: data is more or less than 16 bytes, cannot encode")
return None
res = b''
reslen = 0
for i in r... | 1,430 |
def gcm_send_bulk_message(registration_ids, data, encoding='utf-8', **kwargs):
"""
Standalone method to send bulk gcm notifications
"""
messenger = GCMMessenger(registration_ids, data, encoding=encoding, **kwargs)
return messenger.send_bulk() | 1,431 |
def apply_net_video(net, arr, argmax_output=True, full_faces='auto'):
"""Apply a preloaded network to input array coming from a video of one eye.
Note that there is (intentionally) no function that both loads the net and applies it; loading
the net should ideally only be done once no matter how man... | 1,432 |
def Storeligandnames(csv_file):
"""It identifies the names of the ligands in the csv file
PARAMETERS
----------
csv_file : filename of the csv file with the ligands
RETURNS
-------
lig_list : list of ligand names (list of strings)
"""
Lig = open(csv_file,"rt")
lig_aux = []
... | 1,433 |
def chunk_to_rose(station):
"""
Builds data suitable for Plotly's wind roses from
a subset of data.
Given a subset of data, group by direction and speed.
Return accumulator of whatever the results of the
incoming chunk are.
"""
# bin into three different petal count categories: 8pt, 16p... | 1,434 |
def loadKiosk(eventid):
"""Renders kiosk for specified event."""
event = Event.get_by_id(eventid)
return render_template("/events/eventKiosk.html",
event = event,
eventid = eventid) | 1,435 |
def bson_encode(data: ENCODE_TYPES) -> bytes:
"""
Encodes ``data`` to bytes. BSON records in list are delimited by '\u241E'.
"""
if data is None:
return b""
elif isinstance(data, list):
encoded = BSON_RECORD_DELIM.join(_bson_encode_single(r) for r in data)
# We are going to p... | 1,436 |
def _GetTailStartingTimestamp(filters, offset=None):
"""Returns the starting timestamp to start streaming logs from.
Args:
filters: [str], existing filters, should not contain timestamp constraints.
offset: int, how many entries ago we should pick the starting timestamp.
If not provided, unix time ze... | 1,437 |
def main(data_config_file, app_config_file):
"""Print delta table schemas."""
logger.info('data config: ' + data_config_file)
logger.info('app config: ' + app_config_file)
# load configs
ConfigSet(name=DATA_CFG, config_file=data_config_file)
cfg = ConfigSet(name=APP_CFG, config_file=app_config_... | 1,438 |
def porosity_to_n(porosity,GaN_n,air_n):
"""Convert a porosity to a refractive index. using the volume averaging theory"""
porous_n = np.sqrt((1-porosity)*GaN_n*GaN_n + porosity*air_n*air_n)
return porous_n | 1,439 |
def _indexing_coordi(data, coordi_size, itm2idx):
"""
function: fashion item numbering
"""
print('indexing fashion coordi')
vec = []
for d in range(len(data)):
vec_crd = []
for itm in data[d]:
ss = np.array([itm2idx[j][itm[j]] for j in range(coordi_size)])
... | 1,440 |
def plot_precentile(arr_sim, arr_ref, num_bins=1000, show_top_percentile=1.0):
""" Plot top percentile (as specified by show_top_percentile) of best restults
in arr_sim and compare against reference values in arr_ref.
Args:
-------
arr_sim: numpy array
Array of similarity values to evaluate... | 1,441 |
def set_xfce4_shortcut_avail(act_args, key, progs):
"""Set the shortcut associated with the given key to the first available program"""
for cmdline in progs:
# Split the command line to find the used program
cmd_split = cmdline.split(None, 1)
cmd_split[0] = find_prog_in_path(cmd_split[0]... | 1,442 |
def accesscontrol(check_fn):
"""Decorator for access controlled callables. In the example scenario where
access control is based solely on user names (user objects are `str`),
the following is an example usage of this decorator::
@accesscontrol(lambda user: user == 'bob')
de... | 1,443 |
def load_dataset(path):
"""
Load data from the file
:param: path: path to the data
:return: pd dataframes, train & test data
"""
if '.h5' in str(path):
dataframe = pd.read_hdf(path)
elif '.pkl' in str(path):
dataframe = pd.read_pickle(path)
else:
print('Wrong fil... | 1,444 |
def positionPctProfit():
"""
Position Percent Profit
The percentage profit/loss of each position. Returns a dictionary with
market symbol keys and percent values.
:return: dictionary
"""
psnpct = dict()
for position in portfolio:
# Strings are returned from API; convert to floati... | 1,445 |
def _parse_fields(vel_field, corr_vel_field):
""" Parse and return the radar fields for dealiasing. """
if vel_field is None:
vel_field = get_field_name('velocity')
if corr_vel_field is None:
corr_vel_field = get_field_name('corrected_velocity')
return vel_field, corr_vel_field | 1,446 |
def get_species_charge(species):
""" Returns the species charge (only electrons so far """
if(species=="electron"):
return qe
else:
raise ValueError(f'get_species_charge: Species "{species}" is not supported.') | 1,447 |
def orjson_dumps(
obj: Dict[str, Any], *, default: Callable[..., Any] = pydantic_encoder
) -> str:
"""Default `json_dumps` for TIA.
Args:
obj (BaseModel): The object to 'dump'.
default (Callable[..., Any], optional): The default encoder. Defaults to
pydantic_encoder.
Return... | 1,448 |
def KNN_classification(dataset, filename):
"""
Classification of data with k-nearest neighbors,
followed by plotting of ROC and PR curves.
Parameters
---
dataset: the input dataset, containing training and
test split data, and the corresponding labels
for binding- and non-binding ... | 1,449 |
def projection_error(pts_3d: np.ndarray, camera_k: np.ndarray, pred_pose: np.ndarray, gt_pose: np.ndarray):
"""
Average distance of projections of object model vertices [px]
:param pts_3d: model points, shape of (n, 3)
:param camera_k: camera intrinsic matrix, shape of (3, 3)
:param pred_pose: predicted rotation a... | 1,450 |
def test_uploads_listings(client, benchmark_id):
"""Tests uploading and retrieving a file."""
# -- Setup ----------------------------------------------------------------
# Create new user and submission. Then upload a single file.
user_1, token_1 = create_user(client, '0000')
headers = {HEADER_TOKEN... | 1,451 |
def fetch_response(update, context):
"""Echo the user message."""
response = update.message.text
if response.startswith("sleep-"):
update.message.reply_text(response.split('-')[1])
measure_me(update, context, state='body')
elif response.startswith("body-"):
update.message.reply_t... | 1,452 |
def ph_update(dump, line, ax, high_contrast):
"""
:param dump: Believe this is needed as garbage data goes into first parameter
:param line: The line to be updated
:param ax: The plot the line is currently on
:param high_contrast: This specifies the color contrast of the map. 0=regular contrast, 1=heightened c... | 1,453 |
def get_percent_match(uri, ucTableName):
"""
Get percent match from USEARCH
Args:
uri: URI of part
ucTableName: UClust table
Returns: Percent match if available, else -1
"""
with open(ucTableName, 'r') as read:
uc_reader = read.read()
lines = uc_reader.splitline... | 1,454 |
def get_rm_rf(earliest_date, symbol='000300'):
"""
Rm-Rf(市场收益 - 无风险收益)
基准股票指数收益率 - 国库券1个月收益率
输出pd.Series(日期为Index), 'Mkt-RF', 'RF'二元组
"""
start = '1990-1-1'
end = pd.Timestamp('today')
benchmark_returns = get_cn_benchmark_returns(symbol).loc[earliest_date:]
treasury_returns = ge... | 1,455 |
async def detect_custom(model: str = Form(...), image: UploadFile = File(...)):
"""
Performs a prediction for a specified image using one of the available models.
:param model: Model name or model hash
:param image: Image file
:return: Model's Bounding boxes
"""
draw_boxes = False
try:
output = await dl_servi... | 1,456 |
def main():
"""Generate HDL"""
args = parse_args()
# Output file name may have to change
output_hdl = join(args.hdl_root,"{0}.v".format(args.top_module))
# Language should always be verilog, but who knows what can happen
hdl_lang = "verilog"
g = tree(args.width,args.start)
for a in ar... | 1,457 |
def transcribe(audio_path, model_path, transcr_folder="./tmp/piano_env_tmp/",
transcr_filename="transcription.flac", verbose=VERBOSE):
"""Transcribing audio using trained model.
"""
audio, sr = soundfile.read(audio_path, dtype='int16')
audio = torch.FloatTensor([audio]).div_(32768.0)
... | 1,458 |
def _get_top_ranking_propoals(probs):
"""Get top ranking proposals by k-means"""
dev = probs.device
kmeans = KMeans(n_clusters=5).fit(probs.cpu().numpy())
high_score_label = np.argmax(kmeans.cluster_centers_)
index = np.where(kmeans.labels_ == high_score_label)[0]
if len(index) == 0:
i... | 1,459 |
def get_available_configs(config_dir, register=None):
"""
Return (or update) a dictionary *register* that contains all config files in *config_dir*.
"""
if register is None:
register = dict()
for config_file in os.listdir(config_dir):
if config_file.startswith('_') or not config_fil... | 1,460 |
def test_simulated_annealing_for_valid_solution_warning_raised(slots, events):
"""
Test that a warning is given if a lower bound is passed and not reached in
given number of iterations.
"""
def objective_function(array):
return len(list(array_violations(array, events, slots)))
array = ... | 1,461 |
async def find_quote_by_attributes(quotes: Dict[str, Quote], attribute: str, values: List[str]) -> Quote or None:
"""
Find a quote by its attributes
:param quotes: The dict containing all current quotes
:param attribute: the attribute by which to find the quote
:param values: the values of the attri... | 1,462 |
def externals_test_setup(sbox):
"""Set up a repository in which some directories have the externals property,
and set up another repository, referred to by some of those externals.
Both repositories contain greek trees with five revisions worth of
random changes, then in the sixth revision the first repository ... | 1,463 |
def six_bus(vn_high=20, vn_low=0.4, length_km=0.03, std_type='NAYY 4x50 SE', battery_locations=[3, 6], init_soc=0.5,
energy_capacity=20.0, static_feeds=None, gen_locations=None, gen_p_max=0.0, gen_p_min=-50.0,
storage_p_max=50.0, storage_p_min=-50.0):
"""This function creates the network mod... | 1,464 |
def _add_exccess_het_filter(
b: hb.Batch,
input_vcf: hb.ResourceGroup,
overwrite: bool,
excess_het_threshold: float = 54.69,
interval: Optional[hb.ResourceGroup] = None,
output_vcf_path: Optional[str] = None,
) -> Job:
"""
Filter a large cohort callset on Excess Heterozygosity.
The ... | 1,465 |
def _get_config_and_script_paths(
parent_dir: Path,
config_subdir: Union[str, Tuple[str, ...]],
script_subdir: Union[str, Tuple[str, ...]],
file_stem: str,
) -> Dict[str, Path]:
"""Returns the node config file and its corresponding script file."""
if isinstance(config_subdir, tuple):
con... | 1,466 |
def mongodb_get_users():
"""Connects to mongodb and returns users collection"""
# TODO parse: MONGOHQ_URL
connection = Connection(env['MONGODB_HOST'], int(env['MONGODB_PORT']))
if 'MONGODB_NAME' in env and 'MONGODB_PW' in env:
connection[env['MONGODB_DBNAME']].authenticate(env['MONGODB_NAME... | 1,467 |
def macro_china_hk_cpi_ratio() -> pd.DataFrame:
"""
东方财富-经济数据一览-中国香港-消费者物价指数年率
https://data.eastmoney.com/cjsj/foreign_8_1.html
:return: 消费者物价指数年率
:rtype: pandas.DataFrame
"""
url = "https://datainterface.eastmoney.com/EM_DataCenter/JS.aspx"
params = {
"type": "GJZB",
"st... | 1,468 |
def structuringElement(path):
"""
"""
with open(path) as f:
data = json.load(f)
data['matrix'] = np.array(data['matrix'])
data['center'] = tuple(data['center'])
return data | 1,469 |
def ptsToDist(pt1, pt2):
"""Computes the distance between two points"""
if None in pt1 or None in pt2:
dist = None
else:
vx, vy = points_to_vec(pt1, pt2)
dist = np.linalg.norm([(vx, vy)])
return dist | 1,470 |
def init_check(func):
"""
Decorator for confirming the KAOS_STATE_DIR is present (i.e. initialized correctly).
"""
def wrapper(*args, **kwargs):
if not os.path.exists(KAOS_STATE_DIR):
click.echo("{} - {} directory does not exist - first run {}".format(
click.style("W... | 1,471 |
def d6_to_RotMat(aa:torch.Tensor) -> torch.Tensor: # take (...,6) --> (...,9)
"""Converts 6D to a rotation matrix, from: https://github.com/papagina/RotationContinuity/blob/master/Inverse_Kinematics/code/tools.py"""
a1, a2 = torch.split(aa, (3,3), dim=-1)
a3 = torch.cross(a1, a2, dim=-1)
return to... | 1,472 |
def send_mail(subject, email_template_name, context, to_email):
"""
Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
"""
# append context processors, some variables from settings
context = {**context, **context_processors.general()}
# prepend the marketplace name to the settings
... | 1,473 |
def encrypt(key, pt, Nk=4):
"""Encrypt a plain text block."""
assert Nk in {4, 6, 8}
rkey = key_expand(key, Nk)
ct = cipher(rkey, pt, Nk)
return ct | 1,474 |
def upload(filename, url, token=None):
"""
Upload a file to a URL
"""
headers = {}
if token:
headers['X-Auth-Token'] = token
try:
with open(filename, 'rb') as file_obj:
response = requests.put(url, data=file_obj, timeout=120, headers=headers, verify=False)
except... | 1,475 |
def cost(states, sigma=0.25):
"""Pendulum-v0: Same as OpenAI-Gym"""
l = 0.6
goal = Variable(torch.FloatTensor([0.0, l]))#.cuda()
# Cart position
cart_x = states[:, 0]
# Pole angle
thetas = states[:, 2]
# Pole position
x = torch.sin(thetas)*l
y = torch.cos(thetas)*l
posi... | 1,476 |
def check(tc: globus_sdk.TransferClient, files):
"""Tries to find the path in the globus
endpoints that match the supplies file
names, size and last modified attributes"""
tc.endpoint_search(filter_scope="shared-with-me") | 1,477 |
def createGame(data):
"""Create a new Game object"""
gm = Game.info(data['name'])
room = gm.game_id
GAME_ROOMS[room] = gm
emit('join_room', {'room': GAME_ROOMS[room].to_json()})
emit('new_room', {'room': GAME_ROOMS[room].to_json()}, broadcast=True) | 1,478 |
def flatmap(fn, seq):
"""
Map the fn to each element of seq and append the results of the
sublists to a resulting list.
"""
result = []
for lst in map(fn, seq):
for elt in lst:
result.append(elt)
return result | 1,479 |
def the_test_file():
"""the test file."""
filename = 'tests/resources/grype.json'
script = 'docker-grype/parse-grype-json.py'
return {
'command': f'{script} {filename}',
'host_url': 'local://'
} | 1,480 |
def build_stations() -> tuple[dict, dict]:
"""Builds the station dict from source file"""
stations, code_map = {}, {}
data = csv.reader(_SOURCE["airports"].splitlines())
next(data) # Skip header
for station in data:
code = get_icao(station)
if code and station[2] in ACCEPTED_STATION... | 1,481 |
def terminate_process(proc):
"""
Recursively kills a process and all of its children
:param proc: Result of `subprocess.Popen`
Inspired by http://stackoverflow.com/a/25134985/358873
TODO Check if terminate fails and kill instead?
:return:
"""
process = psutil.Process(proc.pid)
for ... | 1,482 |
def vox_mesh_iou(voxelgrid, mesh_size, mesh_center, points, points_occ, vox_side_len=24, pc=None):
"""LeoZDong addition: Compare iou between voxel and mesh (represented as
points sampled uniformly inside the mesh). Everything is a single element
(i.e. no batch dimension).
"""
# Un-rotate voxels to ... | 1,483 |
async def test_response_no_charset_with_iso_8859_1_content(send_request):
"""
We don't support iso-8859-1 by default following conversations
about endoding flow
"""
response = await send_request(
request=HttpRequest("GET", "/encoding/iso-8859-1"),
)
assert response.text() == "Accente... | 1,484 |
def test_forward(device):
"""Do the scene models have the right shape"""
echellogram = Echellogram(device=device)
t0 = time.time()
scene_model = echellogram.forward(1)
t1 = time.time()
net_time = t1 - t0
print(f"\n\t{echellogram.device}: {net_time:0.5f} seconds", end="\t")
assert scene_m... | 1,485 |
def qhxl_attr_2_bcp47(hxlatt: str) -> str:
"""qhxl_attr_2_bcp47
Convert HXL attribute part to BCP47
Args:
hxlatt (str):
Returns:
str:
"""
resultatum = ''
tempus1 = hxlatt.replace('+i_', '')
tempus1 = tempus1.split('+is_')
resultatum = tempus1[0] + '-' + tempus1[1].... | 1,486 |
def _(output):
"""Handle the output of a bash process."""
logger.debug('bash handler: subprocess output: {}'.format(output))
if output.returncode == 127:
raise exceptions.ScriptNotFound()
return output | 1,487 |
def process_row(row, fiscal_fields):
"""Add and remove appropriate columns.
"""
surplus_keys = set(row) - set(fiscal_fields)
missing_keys = set(fiscal_fields) - set(row)
for key in missing_keys:
row[key] = None
for key in surplus_keys:
del row[key]
assert set(row) == set(fisc... | 1,488 |
def DefaultTo(default_value, msg=None):
"""Sets a value to default_value if none provided.
>>> s = Schema(DefaultTo(42))
>>> s(None)
42
"""
def f(v):
if v is None:
v = default_value
return v
return f | 1,489 |
def load_files(file_list, inputpath):
"""
function to load the data from potentially multiple files into one pandas DataFrame
"""
df = None
# loop through files and append
for i, file in enumerate(file_list):
path = f"{inputpath}/{file}"
print(path)
df_i = pd.read_csv(pa... | 1,490 |
def list_all():
"""
List all systems
List all transit systems that are installed in this Transiter instance.
"""
return systemservice.list_all() | 1,491 |
def putText(image: np.ndarray, text: str,
org=(0, 0),
font=_cv2.FONT_HERSHEY_PLAIN,
fontScale=1, color=(0, 0, 255),
thickness=1,
lineType=_cv2.LINE_AA,
bottomLeftOrigin=False) -> np.ndarray:
"""Add text to `cv2` image, with default values.
... | 1,492 |
def gaussFilter(fx: int, fy: int, sigma: int):
""" Gaussian Filter
"""
x = tf.range(-int(fx / 2), int(fx / 2) + 1, 1)
Y, X = tf.meshgrid(x, x)
sigma = -2 * (sigma**2)
z = tf.cast(tf.add(tf.square(X), tf.square(Y)), tf.float32)
k = 2 * tf.exp(tf.divide(z, sigma))
k = tf.divide(k, tf.redu... | 1,493 |
def char_buffered(pipe):
"""Force the local terminal ``pipe`` to be character, not line, buffered."""
if win32 or env.get('disable_char_buffering', 0) or not sys.stdin.isatty():
yield
else:
old_settings = termios.tcgetattr(pipe)
tty.setcbreak(pipe)
try:
yield
... | 1,494 |
def do_something(param=None):
"""
Several routes for the same function
FOO and BAR have different documentation
---
"""
return "I did something with {}".format(request.url_rule), 200 | 1,495 |
def extract_text(
pattern: re.Pattern[str] | str,
source_text: str,
) -> str | Literal[False]:
"""Match the given pattern and extract the matched text as a string."""
match = re.search(pattern, source_text)
if not match:
return False
match_text = match.groups()[0] if match.groups() else ... | 1,496 |
def _checksum_paths():
"""Returns dict {'dataset_name': 'path/to/checksums/file'}."""
dataset2path = {}
for dir_path in _CHECKSUM_DIRS:
for fname in _list_dir(dir_path):
if not fname.endswith(_CHECKSUM_SUFFIX):
continue
fpath = os.path.join(dir_path, fname)
dataset_name = fname[:-len... | 1,497 |
def test_calculate_allocation_from_cash3():
""" Checks current allocation is 0 when spot_price is less than 0 (ie; bankrupt) """
last_cash_after_trade = 30.12
last_securities_after_transaction = 123.56
spot_price = -5.12
out_actual = calculate_allocation_from_cash(last_cash_after_trade, last_securi... | 1,498 |
def get_merged_message_df(messages_df, address_book, print_debug=False):
"""
Merges a message dataframe with the address book dataframe to return a single dataframe that contains all
messages with detailed information (e.g. name, company, birthday) about the sender.
Args:
messages_df: a... | 1,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.