content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load(csv, sep=';'):
"""
Load data into dataframe
:param csv:
:param sep:
:return:
"""
data = pd.read_csv(csv, sep=sep)
return data | 12,200 |
def get_docs(request):
"""
вернуть список
[
{doc_id, doc_name},
{doc_id, doc_name},
]
"""
doc_set_id = request.GET["doc_set_id"]
docs = Document.objects.filter(doc_set_id=doc_set_id)
response_data = []
for doc in docs:
filename, file_exten... | 12,201 |
def count_lost_norm4(matrix):
"""calculate 4th lost points: Proportion of dark modules in entire symbol:
50 + (5 + k) or 50 - (5 + k), return k * 10
Args:
matrix ([type]): [description]
Returns:
[int]: [description]
"""
dark_sum = np.sum(matrix)
modules_num = ma... | 12,202 |
def sumaDigits(s):
"""assumes s is a string and returns the sum of the
decimal digits in s. For example if s is 'a2b3c' it returns 5"""
suma = 0
for c in s:
try:
suma+=int(c)
except ValueError:
continue
return suma | 12,203 |
def test_incorrectly_sized_pixel_ticks():
"""BinaryMaskCollection.from_label_array_and_ticks with 2D data and some pixel ticks provided,
albeit of the wrong cardinality."""
label_array, physical_ticks = label_array_2d()
pixel_ticks = {
Axes.X: [2, 3, 4, 5, 6, 7, 8],
}
with pytest.raises... | 12,204 |
def f5_list_policy_file_types_command(client: Client, policy_md5: str) -> CommandResults:
"""
Get a list of all policy file types.
Args:
client (Client): f5 client.
policy_md5 (str): MD5 hash of the policy.
"""
result = client.list_policy_file_types(policy_md5)
table_name = 'f5... | 12,205 |
def recurrent_layer(input,
act=None,
bias_attr=None,
param_attr=None,
name=None,
reverse=False,
layer_attr=None):
"""
Simple recurrent unit layer. It is just a fully connect layer through both... | 12,206 |
def add_replicas(rse, files, issuer, ignore_availability=False):
"""
Bulk add file replicas.
:param rse: The RSE name.
:param files: The list of files.
:param issuer: The issuer account.
:param ignore_availability: Ignore the RSE blacklisting.
:returns: True is successful, False otherwise
... | 12,207 |
def mean_center(X):
"""
@param X: 2-dimensional matrix of number data
@type X: numpy array
@return: Mean centered X (always has same dimensions as X)
"""
(rows, cols) = shape(X)
new_X = zeros((rows, cols), float)
_averages = average(X, 0)
f... | 12,208 |
def inventory_report(products, show_all=False):
"""Prints a list of ACME objects into a report."""
print("\nACME CORPORATION OFFICIAL INVENTORY REPORT")
totalPrice = 0
totalWeight = 0
totalFlammability = 0
all_product_titles = []
for _ in products:
"""Prints all the generat... | 12,209 |
def updateTransformMatrixFromArray(transformNode, narray, toWorld=False):
"""Set transformation matrix from a numpy array of size 4x4 (toParent).
:param world: if set to True then the transform will be set so that transform
to world matrix will be equal to narray; otherwise transform to parent will be
set... | 12,210 |
def csv_to_json(order_sentence_file: str, order_comment_file: str, os_filter_file: str=None) -> dict:
"""
Conversion of CSV to dictionary/JSON for sequenced PowerPlans and clinical
category
:param order_sentence_file:
:param order_comment_file:
:return:
"""
output_dict = collections.de... | 12,211 |
def process_xlsform(xls, default_name):
"""
Process XLSForm file and return the survey dictionary for the XLSForm.
"""
# FLOW Results package is a JSON file.
file_object = None
if xls.name.endswith('csv'):
# a csv file gets closed in pyxform, make a copy
xls.seek(0)
file... | 12,212 |
def unflatten(X: np.ndarray, Y: np.ndarray, shape: tuple):
""" Unflattens images with shape defined by list of tuples s
X is an array (1D), unflattened to 2D
Y is an array (1D) of flattened mask (flattened 2D label) array
Not that X and Y are not compatible dimensions
s denotes dimensions ... | 12,213 |
def collate_features(model_config: Dict[str, Any], dummy_features: List[str]) -> List[str]:
"""Saves and returns final list of simple and dummy features."""
simple_features = list(model_config.get("simple_features", {}).keys())
features = simple_features + dummy_features
logging.info(
f"Model us... | 12,214 |
def test_get_event_consumer(local, provide_loop, topic, sub, consumer_config,
exp_topic, auth_client, exp_sub, subscriber_client,
emulator, monkeypatch, event_loop, metrics):
"""Happy path to initialize an Event Consumer client."""
success_chnl, error_chnl... | 12,215 |
def new_dga(*, key_mo=None, pred=None, deg_diff=None) -> Type[DgaGb]:
"""Return a dynamically created subclass of GbDga.
When key_mo=None, use revlex ordering by default."""
class_name = f"GbDga_{DgaGb._index_subclass}"
DgaGb._index_subclass += 1
if deg_diff is not None:
deg_diff = Vector(d... | 12,216 |
def is_xarray(array):
"""Return True if array is a xarray.DataArray
Parameters
----------
array : array-like
Returns
-------
test : bool
"""
return isinstance(array,xr.DataArray) | 12,217 |
def set_variable(type, value):
""" Setter for dynamic variable (a.k.a. dependency).
@param type: The type of the dynamic variable.
@type type: Str
@param value: The value to assign to the dynamic vairable.
@type type: Str
@return: None
@rtype : None
"""
global object_creations
... | 12,218 |
def _check_duplicate_gnames(block_id, block_dict, extra_args):
"""
Return False if any duplicate group names exist in /etc/group file, else return True
"""
gnames = _execute_shell_command("cat /etc/group | cut -f1 -d\":\"", python_shell=True).strip()
gnames = gnames.split('\n') if gnames != "" else ... | 12,219 |
def test_combine_same_shape(span):
"""Test _combine with same shape of cubes."""
len_data = 3
num_cubes = 5
cubes = []
for i in range(num_cubes):
cube = generate_cube_from_dates('monthly',
'360_day',
fill_val=i,... | 12,220 |
def join_nonempty(l):
"""
Join all of the nonempty string with a plus sign.
>>> join_nonempty(('x1 + x2 + x1:x2', 'x3 + x4'))
'x1 + x2 + x1:x2 + x3 + x4'
>>> join_nonempty(('abc', '', '123', ''))
'abc + 123'
"""
return ' + '.join(s for s in l if s != '') | 12,221 |
def accumulateProduct(src1, src2, dst, mask=None):
""" accumulateProduct(src1, src2, dst[, mask]) -> dst """
pass | 12,222 |
def send_file_to_euler(username, local_file):
""" Send a local file to the ETHZ Euler cluster (home folder).
Parameters
----------
username (str): Username.
local_file (str): Path of local file to send.
Returns
-------
None
"""
ssh.send_file(username=username, local... | 12,223 |
def correct_msa_restypes(protein):
"""Correct MSA restype to have the same order as rc."""
new_order_list = rc.MAP_HHBLITS_AATYPE_TO_OUR_AATYPE
new_order = torch.tensor(
[new_order_list] * protein["msa"].shape[1],
device=protein["msa"].device,
).transpose(0, 1)
protein["msa"] = torc... | 12,224 |
def test_update_user_ensures_request_data_id_matches_resource_id(
client, auth, example_users
):
"""If request data contains an (optional) "id" then it has to match the resource id."""
auth.login("user1@example.com", "password1")
url_update_user = url_for("api.update_user", user_id=auth.id)
json = {... | 12,225 |
def results(event, update):
"""
Find all available results for a given event.
"""
server, repository = connect_gitlab()
events = gitlab.find_events(repository, milestone=config.get("olivaw", "milestone"), subset=[event], update=update, repo=False)
for event in events:
click.secho(f"{even... | 12,226 |
def plot_bootstrap_lr_grp(dfboot, df, grp='grp', prm='premium', clm='claim',
title_add='', force_xlim=None):
""" Plot bootstrapped loss ratio, grouped by grp """
count_txt_h_kws, mean_txt_kws, pest_mean_point_kws, mean_point_kws = _get_kws_styling()
if dfboot[grp].dtypes != ... | 12,227 |
def ajax_user_search(request):
"""
returns the user search result. currently this is not used since search user feature changed to form post.
"""
if request.method=='POST':
username=request.POST.get('username','')
users=User.objects.filter(username__contains=username)
try:
... | 12,228 |
def shortest_path(start, end):
"""
Using 2-way BFS, finds the shortest path from start_position to
end_position. Returns a list of moves.
You can use the rubik.quarter_twists move set.
Each move can be applied using rubik.perm_apply
"""
if start == (7, 8, 6, 20, 18, 19, 3, 4, 5, 16, 17, 15... | 12,229 |
def pytest_unconfigure(config: pytest.Config) -> None:
"""
Called before test process is exited.
:param config: The pytest config object.
"""
with logger.contextualize(task="teardown".rjust(10, " ")):
logger.debug("Unregistering kiru plugins")
from sel4.core.plugins.directory_mana... | 12,230 |
def prep_param_lists(model, flat_master=False):
"""
Creates a list of FP32 master parameters for a given model, as in
`Training Neural Networks with Mixed Precision: Real Examples`_.
Args:
model (torch.nn.Module): Existing Pytorch model
flat_master (bool, optional, default=False): Fla... | 12,231 |
def to_matrix_vector(transform):
"""
Code from nilearn module, available at: https://github.com/nilearn/nilearn/blob/master/nilearn/image/resampling.py
Split an homogeneous transform into its matrix and vector components.
The transformation must be represented in homogeneous coordinates.
It is ... | 12,232 |
def game(var, wrapper, message):
"""Vote for a game mode to be picked."""
if message:
vote_gamemode(var, wrapper, message.lower().split()[0], doreply=True)
else:
wrapper.pm(messages["no_mode_specified"].format(_get_gamemodes(var))) | 12,233 |
def sieveEr(N):
"""
input: positive integer 'N' > 2
returns a list of prime numbers from 2 up to N.
This function implements the algorithm called
sieve of erathostenes.
"""
# precondition
assert isinstance(N,int) and (N > 2), "'N' must been... | 12,234 |
def validate_fields(item, fields=None):
"""
Check that all requested fields were returned
:param item: comment or submission
:param fields: list[str]
:return: list[str]
"""
actual_fields = item.d_.keys()
if fields is None:
requested_fields = actual_fields
else:
requ... | 12,235 |
def chunks(l, n, cnt):
"""Yield successive n-sized chunks from l first cnt elements."""
for i in range(0, cnt, n):
if i + n > cnt:
yield l[i:cnt]
else:
yield l[i:i + n] | 12,236 |
def _parallel_build_trees(tree, forest, X, y, sample_weight, tree_idx, n_trees,
verbose=0, class_weight=None, target_imbalance_ratio=None):
"""Private function used to fit a single tree in parallel."""
if verbose > 1:
print("building tree %d of %d" % (tree_idx + 1, n_trees))
... | 12,237 |
def test_get_backend_invalid_custom_name():
"""Test that loading backend fails with specific error if name is invalid
"""
with pytest.raises(ValueError):
storage.get_storage('ckanext.asset_storage.storage.local.LocalStorage',
{'storage_path': '/tmp'})
with pytest.rai... | 12,238 |
def remove_nones(sequence: Iterable) -> list:
"""Removes elements where bool(x) evaluates to False.
Examples
--------
Normal usage::
remove_nones(['m', '', 'l', 0, 42, False, True])
# ['m', 'l', 42, True]
"""
# Note this is redundant with it.chain
return [x for x in sequenc... | 12,239 |
def writeSConscript(dirpath, profile, pkeys):
""" Create a SConscript file in dirpath.
"""
# Activate modules
mods, defines = collectModules(dirpath, pkeys)
if validKey('CONFIG', pkeys) and isComplicated(pkeys['CONFIG'][0]):
return False
qrcname = ""
if not validKey('SOURCES', ... | 12,240 |
def retrieve(passed: List[str]) -> List[str]:
"""
Retrieves all items that are able to be
converted, recursively, from the passed list.
Parameters
----------
passed: List[str]
The items to search.
Returns
-------
List[str]:
All found items.
"""
ret = []
... | 12,241 |
def test_response_parsing():
"""
Should have properly formed payload if working.
"""
eoo = EdxOrgOAuth2(strategy=load_strategy())
result = eoo.get_user_details(
{
"id": 5,
"username": "darth",
"email": "darth@deathst.ar",
"name": "Darth Vader",... | 12,242 |
def get_out_of_sample_best_point_acqf(
model: Model,
Xs: List[Tensor],
X_observed: Tensor,
objective_weights: Tensor,
mc_samples: int = 512,
fixed_features: Optional[Dict[int, float]] = None,
fidelity_features: Optional[List[int]] = None,
target_fidelities: Optional[Dict[int, float]] = N... | 12,243 |
def removeBots(gdf, bot_list):
"""
A Function for removing Twitter bots.
Parameters
----------
gdf: <gpd.GeoDataFrame>
A GeoDataFrame from which Twitter bots should be removed.
bot_list: <list>
Input either 'home_unique_days' or 'home_unique_weeks'
... | 12,244 |
def getinput(prompt):
""">> getinput <prompt>
Get input, store it in '__input__'.
"""
local_dict = get_twill_glocals()[1]
inp = input(prompt)
local_dict['__input__'] = inp
return inp | 12,245 |
def plot_qualitative_with_kde(
named_trainer,
dataset,
named_trainer_compare=None,
n_images=8,
percentiles=None, # if None uses uniform linspace from n_images
figsize=DFLT_FIGSIZE,
title=None,
seed=123,
height_ratios=[1, 3],
font_size=12,
h_pad=-3,
x_lim={},
is_small... | 12,246 |
def test_df_multiple_aggfuncs():
"""Test output when ``aggfunc`` is more than one."""
df_frame = pd.DataFrame(
[
{"A": "foo", "B": "one", "C": "small", "D": 1, "E": 2},
{"A": "foo", "B": "one", "C": "large", "D": 2, "E": 4},
{"A": "foo", "B": "one", "C": "large", "D"... | 12,247 |
def get_git_doc_ref():
"""Return the revision used for linking to source code on GitHub."""
global _head_ref
if not _head_ref:
try:
branch = git_get_nearest_tracking_branch('.')
_head_ref = _run_git(['rev-parse', branch]).strip()
except subprocess.CalledProcessError:... | 12,248 |
def test_rename_columns_bad_column_name():
"""Test column renamin with bad column name."""
cars = {
"Brand": ["Chevrolet Bel Air", "Lotus Esprit"],
"Price": [49995, 59950],
"Year": [1957, 1977],
"Sign": ["Rooster", "Snake"],
}
original_list = ["Brand", "Price", "Year", "f... | 12,249 |
def check_call_demo():
"""
执行命令,返回结果和状态,正常为0,执行错误则抛出异常
"""
ret = subprocess.check_call(["lm", "l"])
print(ret) | 12,250 |
def update_trails(force=False, offline=False):
"""
Update trails from feeds
"""
success = False
trails = {}
duplicates = {}
try:
if not os.path.isdir(USERS_DIR):
os.makedirs(USERS_DIR, 0755)
except Exception, ex:
exit("[!] something went wrong during creatio... | 12,251 |
def bq_to_rows(rows):
"""Reformat BigQuery's output to regular pnguin LOD data
Reformat BigQuery's output format so we can put it into a DataFrame
Args:
rows (dict): A nested list of key-value tuples that need to be converted into a list of dicts
Returns:
list: A list of dictionaries ... | 12,252 |
def _write_impropers(lmp_file: IO, openff_sys: Interchange):
"""Write the Impropers section of a LAMMPS data file."""
from openff.interchange.components.mdtraj import (
_iterate_impropers,
_store_bond_partners,
)
_store_bond_partners(openff_sys.topology.mdtop)
lmp_file.write("\nImp... | 12,253 |
def draw_border(img, pt1, pt2, color, thickness, r, d, label='Unknown'):
"""Fancy box drawing function for detected faces."""
x1, y1 = pt1
x2, y2 = pt2
# Top left drawing
cv2.line(img, (x1 + r, y1), (x1 + r + d, y1), color, thickness)
cv2.line(img, (x1, y1 + r), (x1, y1 + r + d), color, thick... | 12,254 |
def network_config(session, args):
"""network config functions"""
cmd = pluginlib.exists(args, 'cmd')
if not isinstance(cmd, basestring):
msg = "invalid command '%s'" % str(cmd)
raise pluginlib.PluginError(msg)
return
if cmd not in ALLOWED_NETWORK_CMDS:
msg = "Dom0 execut... | 12,255 |
def count_pred_result(args, file_name, logit_id, class_num=2, max_seq_length=128):
"""
support two method to calc f1 sore, if dataset has two class, suggest using BF1,
else more than two class, suggest using MF1.
Args:
args: param of config.
file_name: label file name.
logit_id: ... | 12,256 |
def persistent_property(name,default_value=0.0):
"""A propery object to be used inside a class"""
def get(self):
class_name = getattr(self,"name",self.__class__.__name__)
if not "{name}" in name:
if class_name: dbname = class_name+"."+name
else: dbname = name
els... | 12,257 |
def album_id(items, sp_album):
"""Iterate through results to find correct Discogs album id."""
try:
artist = sp_album['artists'][0].lower().replace(" ", "")
except IndexError:
artist = ""
owners = -1
discogs_id = -1
similarity = 0
title = sp_album['name'].lower().replace(" "... | 12,258 |
def css_defaults(name, css_dict):
"""Находит первое значение по-умолчанию
background -> #FFF
color -> #FFF
content -> ""
"""
cur = css_dict.get(name) or css_dict.get(name[1:-1])
if cur is None:
return None
default = cur.get('default')
if default is not None:
return de... | 12,259 |
def yn_zeros(n,nt):
"""Compute nt zeros of the Bessel function Yn(x).
"""
return jnyn_zeros(n,nt)[2] | 12,260 |
def get_chebi_parents(chebi_ent):
"""
Get parents of ChEBI entity
:param chebi_ent:
:return:
"""
if hasattr(chebi_ent, 'OntologyParents'):
return [ent.chebiId for ent in chebi_ent.OntologyParents if
(ent.type == 'is a')]
else:
return [] | 12,261 |
def test_validate_api_key_valid(client, mocker):
"""Tests the validate api key route with a valid form."""
mocked_api_key_form = mocker.patch('app.routes.ApiKeyForm')
mocked_api_key_form.return_value.validate_on_submit.return_value = True
mocked_api_key_form.return_value.organization.data = 1
with c... | 12,262 |
def average_saccades_time(saccades_times):
"""
:param saccades_times: a list of tuples with (start_time_inclusive, end_time_exclusive)
:return: returns the average time of saccades
"""
return sum([saccade_time[1] - saccade_time[0] for saccade_time in saccades_times]) / len(saccades... | 12,263 |
def set_api_key(api_key):
"""Sets an environment variable :code:`"DC_API_KEY"` to given :code:`api_key`.
Users may supply an API key to the Python API, which simply passes it on to
the REST API for handling. The API key can be provided to the API after
importing the library, or set as an environment variable... | 12,264 |
def solve_tsp_local_search(
distance_matrix: np.ndarray,
x0: Optional[List[int]] = None,
perturbation_scheme: str = "two_opt",
max_processing_time: Optional[float] = None,
log_file: Optional[str] = None,
) -> Tuple[List, float]:
"""Solve a TSP problem with a local search heuristic
Parameter... | 12,265 |
def split(self, split_size_or_sections, dim=0, copy=True):
"""Return the split chunks along the given dimension.
Parameters
----------
split_size_or_sections : Union[int, Sequence[int]
The number or size of chunks.
dim : int, optional, default=0
The dimension to split.
copy : bo... | 12,266 |
def HighFlowSingleInletTwoCompartmentGadoxetateModel(xData2DArray, Ve: float,
Kbh: float, Khe: float,
dummyVariable):
"""This function contains the algorithm for calculating how concentration varies with ti... | 12,267 |
def create_db_directories(db_path: str = DB_PATH, not_a_book: str = NO_BOOK_NAME) -> None:
"""create DB if not existing"""
db_directory = full_db_path(db_path)
if not os.path.exists(db_directory):
print('Make directory: ' + db_directory)
os.makedirs(db_directory)
db_not_a_book_directory ... | 12,268 |
def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize):
"""Read CZ_LSMINFO tag from file and return as dict."""
assert byteorder == '<'
magic_number, structure_size = struct.unpack('<II', fh.read(8))
if magic_number not in (50350412, 67127628):
raise ValueError('invalid CZ_LSMINFO structur... | 12,269 |
def mi_alignment(
alignment,
mi_calculator=mi,
null_value=DEFAULT_NULL_VALUE,
excludes=DEFAULT_EXCLUDES,
exclude_handler=None,
):
"""Calc mi over all position pairs in an alignment
alignment: the full alignment object
mi_calculator: a function which calculated MI from two entropies and
... | 12,270 |
def Jaccard3d(a, b):
"""
This will compute the Jaccard Similarity coefficient for two 3-dimensional volumes
Volumes are expected to be of the same size. We are expecting binary masks -
0's are treated as background and anything else is counted as data
Arguments:
a {Numpy array} -- 3D array ... | 12,271 |
def jaccard_distance() -> None:
"""
Calculates the Jaccard distances for all the repos, save the pre-calculated distances
as a NumPy file.
:return: None.
"""
reqs = read_dependencies()
matrix = np.zeros((len(reqs), len(reqs)))
print(f"The shape of the matrix is {matrix.shape}")
for i... | 12,272 |
def get_pod_obj(name, namespace=None):
"""
Returns the pod obj for the given pod
Args:
name (str): Name of the resources
Returns:
obj : A pod object
"""
ocp_obj = OCP(api_version='v1', kind=constants.POD, namespace=namespace)
ocp_dict = ocp_obj.get(resource_name=name)
p... | 12,273 |
def _input_password() -> str:
"""
Get password input by masking characters.
Similar to getpass() but works with cygwin.
"""
sys.stdout.write("Password :\n")
sys.stdout.flush()
subprocess.check_call(["stty", "-echo"])
password = input()
subprocess.check_call(["stty", "echo"])
retu... | 12,274 |
def config_pymatgen(psp_dir=None, def_fun="PBE", mapi=None, path_to_store_psp="psp_pymatgen", aci=False,
vasp_cmd="vasp_std", template="vaspjob.pbs", queue_type="pbs"):
"""
Config pymatgen.
If the key is exists in ~/.pmgrc.yaml and not empty, skip
Parameter
psp_dir: str (path-like)
... | 12,275 |
def file_size(file_path):
"""Return the file size."""
if os.path.isfile(file_path):
file_info = os.stat(file_path)
return convert_bytes(file_info.st_size) | 12,276 |
def median_rank(PESSI_SORT, OPTI_SORT, A):
"""
Calculates the median rank of each action.
:param PESSI_SORT: Dictionary containing the actions classified according to the pessimistic procedure.
:param OPTI_SORT: Dictionary containing the actions classified according to the optimistic procedure.
:pa... | 12,277 |
def get_token(
event: ApiGatewayEvent,
_context: LambdaContext,
node_api: Optional[NodeApi] = None
) -> dict:
"""Get token details given a token uid.
*IMPORTANT: Any changes on the parameters should be reflected on the `cacheKeyParameters` for this method.
"""
node_api = node_api or Nod... | 12,278 |
def create_video(input_file, line_count, video_name, visible_obstacles):
"""
Given an input file which logs an agent's movements,
create a video file which records the sequence of movements.
"""
obstacle_plots = []
# convert obstacles into lists of tuples so matplotlib can
# understand them... | 12,279 |
def update_dictionary_entries(old_entries, need_to_add):
"""
Expects dictionary of species entries and
unique list of species (as SMILES) that need to be added
Creates new entries for the species that need to be added
Returns old and new entries
"""
list(set(need_to_add))
for j, species... | 12,280 |
def ParseOptions():
"""Parses the options passed to the program.
@return: Options and arguments
"""
parser = optparse.OptionParser(usage="%prog [--no-backup]",
prog=os.path.basename(sys.argv[0]))
parser.add_option(cli.DEBUG_OPT)
parser.add_option(cli.VERBOSE_OPT)
parser.... | 12,281 |
def test_parse_through_basic(monkeypatch):
"""Checks prismify directive "parse_through" """
mock_XlTemplateReader_from_excel(
{"ws1": [["#preamble", "propname", "propval"]]}, monkeypatch
)
xlsx, errs = XlTemplateReader.from_excel("workbook")
assert not errs
template_schema = {
... | 12,282 |
def join_customer_script(customer_code_process : multiprocessing.Process):
"""
Joins the process running the customer code.
Args:
customer_code_process (Process): the process running the customer code.
"""
try:
customer_code_process.join()
except Exception as e:
log_fail... | 12,283 |
def four_rooms(dims, doorway=1.):
"""
Args:
dims: [dimx, dimy] dimensions of rectangle
doorway: size of doorway
Returns:
adjmat: adjacency matrix
xy: xy coordinates of each state for plotting
labels: empty []
"""
half_x, half_y = (dims[0]*.5, dims[1]*.5)
quarter_x,... | 12,284 |
def get_verse_url(verse: str) -> str:
"""Creates a URL for the verse text."""
node = CONNECTIONS[verse]
volume = scripture_graph.VOLUMES_SHORT[node['volume']].lower()
if volume == 'bom':
volume = 'bofm'
elif volume == 'd&c':
volume = 'dc-testament'
elif volume == 'pogp':
... | 12,285 |
def get_ws_dependency_annotation(state: GlobalState) -> WSDependencyAnnotation:
""" Returns the world state annotation
:param state: A global state object
"""
annotations = cast(
List[WSDependencyAnnotation],
list(state.world_state.get_annotations(WSDependencyAnnotation)),
)
i... | 12,286 |
def test_ga_tap_standard_tests(ga_config: Optional[dict]):
"""Run standard tap tests against Google Analytics tap."""
tests = get_standard_tap_tests(SampleTapGoogleAnalytics, config=ga_config)
for test in tests:
test() | 12,287 |
def get_report_df(get_devreport_df, chemdf_dict, dev_args):
"""
Grab a default devreport under the expected conditions
which can be used for downstream testing
"""
dataset_list = dev_args.d
raw_bool = dev_args.raw
target_naming_scheme = dev_args.local_directory
offline_folder = f'./{ta... | 12,288 |
def get_gin_confg_strs():
"""
Obtain both the operative and inoperative config strs from gin.
The operative configuration consists of all parameter values used by
configurable functions that are actually called during execution of the
current program, and inoperative configuration consists of all p... | 12,289 |
def L(x, c, gamma):
"""Return c-centered Lorentzian line shape at x with HWHM gamma"""
return gamma / (np.pi * ((x - c) ** 2 + gamma ** 2)) | 12,290 |
def request_data_from_weather_station():
"""
Send a command to the weather station to get current values.
Returns
-------
bytes
received data, 0 if error occurred
"""
sock = socket.create_connection((WEATHER_HOST, WEATHER_PORT), GRAPHITE_TIMEOUT)
sock.setsockopt(socket.SOL_SOCKE... | 12,291 |
def solution2(arr):
"""improved solution1 #TLE """
if len(arr) == 1:
return arr[0]
max_sum = float('-inf')
l = len(arr)
for i in range(l):
local_sum = arr[i]
local_min = arr[i]
max_sum = max(max_sum, local_sum)
for j in range(i + 1, l):
local_sum... | 12,292 |
def change_test_dir_and_create_data_path(request):
""" The fixture required to change the root directory where from pytest runs the tests.
Root is set to the directory whene this file is located, so relative paths work fine. """
os.chdir(request.fspath.dirname) # <- Changes pytest root to this director... | 12,293 |
def hillas_parameters_4(pix_x, pix_y, image, recalculate_pixels=True):
"""Compute Hillas parameters for a given shower image.
As for hillas_parameters_3 (old Whipple Fortran code), but more Pythonized
MP: Parameters calculated as Whipple Reynolds et al 1993 paper:
http://adsabs.harvard.edu/abs/1993ApJ... | 12,294 |
def create_intrusion_set(
name: str,
aliases: List[str],
author: Identity,
primary_motivation: Optional[str],
secondary_motivations: List[str],
external_references: List[ExternalReference],
object_marking_refs: List[MarkingDefinition],
) -> IntrusionSet:
"""Create an intrusion set."""
... | 12,295 |
def key_up(handle: HWND, key: str):
"""放开指定按键
Args:
handle (HWND): 窗口句柄
key (str): 按键名
"""
vk_code = get_virtual_keycode(key)
scan_code = MapVirtualKeyW(vk_code, 0)
# https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keyup
wparam = vk_code
lparam = (s... | 12,296 |
def broadcast_to(tensor, shape):
"""Broadcast an tensor to a new shape.
Parameters
----------
tensor : array_like
The tensor to broadcast.
shape : tuple
The shape of the desired array.
Returns
-------
broadcast : Tensor
Raises
------
ValueError
If t... | 12,297 |
def admin_required(handler_method):
"""Require that a user be an admin.
To use it, decorate your method like this::
@admin_required
def get(self):
...
"""
@wraps(handler_method)
def check_admin(*args, **kwargs):
"""Perform the check."""
if current_user.... | 12,298 |
def get(path):
"""Get."""
verify()
resp = requests.get(f"{URL}{path}", headers=auth)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
error_msg(str(e))
return
return resp.json() | 12,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.