content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def PlistValueToPlainValue(plist):
"""Takes the plist contents generated by binplist and returns a plain dict.
binplist uses rich types to express some of the plist types. We need to
convert them to types that RDFValueArray will be able to transport.
Args:
plist: A plist to convert.
Returns:
A simp... | 5,316,700 |
def columns_not_to_edit():
"""
Defines column names that shouldn't be edited.
"""
## Occasionally unchanging things like NIGHT or TILEID have been missing in the headers, so we won't restrict
## that even though it typically shouldn't be edited if the data is there
return ['EXPID', 'CAMWORD', 'O... | 5,316,701 |
def cat_dog(s):
"""Solution of problem at http://codingbat.com/prob/p164876
>>> cat_dog('catdog')
True
>>> cat_dog('catcat')
False
>>> cat_dog('1cat1cadodog')
True
"""
last_3_chars = deque(maxlen=3)
cat = deque('cat')
dog = deque('dog')
count = 0
for c in s:
... | 5,316,702 |
def CanCreateGroup(perms):
"""Return True if the given user may create a user group.
Args:
perms: Permissionset for the current user.
Returns:
True if the user should be allowed to create a group.
"""
# "ANYONE" means anyone who has the needed perm.
if (settings.group_creation_restriction ==
... | 5,316,703 |
def quad_corner_diff(hull_poly, bquad_poly, region_size=0.9):
"""
Returns the difference between areas in the corners of a rounded
corner and the aproximating sharp corner quadrilateral.
region_size (param) determines the region around the corner where
the comparison is done.
"""
bquad_corne... | 5,316,704 |
def setup_logging():
"""
Setup logging configuration.
"""
configuration_path = "deployment/sysconf/logging.yaml"
logging_configuration = file_handler.load_yaml_config(configuration_path)
logging.config.dictConfig(logging_configuration) | 5,316,705 |
def _context_deleteserver(ip, port, server_name, config=None, disabled=None):
"""Delete a server context.
"""
if config is None or ('_isdirty' in config and config['_isdirty']):
config = loadconfig(APACHECONF, True)
scontext = _context_getserver(ip, port, server_name, config=config, disabled=dis... | 5,316,706 |
def CreateStyleFromConfig(style_config):
"""Create a style dict from the given config.
Arguments:
style_config: either a style name or a file name. The file is expected to
contain settings. It can have a special BASED_ON_STYLE setting naming the
style which it derives from. If no such setting is fo... | 5,316,707 |
def test_train_loss_loader():
"""Should return randum subset of training set."""
for loader in loaders:
mnist = loader(1000, 10)
samples = 0
for (_, labels) in mnist.train_loss_loader():
samples += labels.size()[0]
assert samples == mnist.test_set_size | 5,316,708 |
def build_weighted_matrix(corpus, tokenizing_func=basic_tokenizer,
mincount=300, vocab_size=None, window_size=10,
weighting_function=lambda x: 1 / (x + 1)):
"""Builds a count matrix based on a co-occurrence window of
`window_size` elements before and `window_size` elements after the
focal wo... | 5,316,709 |
def checksum_data_16bit(data):
"""Calculate 16 bit checksum (really just summing up shorts) over a chunk."""
return reduce(lambda r, x: (r + x) & 0xFFFF, map(lambda (x, y): (ord(y) << 8) | ord(x), zip(*[iter(data)] * 2)), 0) | 5,316,710 |
def test_lower_upper_case():
"""test if case is ignored for queries and for indexed terms"""
# clean up everything first
clean_database()
# initialize the database with example content
new_db = _get_indexer(DATABASE)
create_example_content(new_db)
# use upper case search terms for lower case... | 5,316,711 |
def substitute_variables(model_params_variables, model_data_raw):
"""
:param model_params_variables:
:param model_data_raw:
:return:
"""
model_data_list = []
for argument_raw in model_data_raw:
argument_split_raw = argument_raw.split(",")
argument_split = []
for par... | 5,316,712 |
def test_syntax(event=None):
"""Run all testss in test_syntax.py."""
g.run_unit_tests('leo.unittests.test_syntax.TestSyntax') | 5,316,713 |
def getFirstDay(curDate, curWeek):
"""get first day of the first week"""
assert(curWeek >= 1)
curDate -= timedelta(weeks=curWeek-1)
curDate -= timedelta(days=curDate.weekday())
return curDate | 5,316,714 |
def select_from_list(data: List[T], name: Callable[[T], str], prompt: str) -> Optional[T]:
"""Interactively selects named entity from given list"""
names: List[str] = list(map(name, data))
prompt = f'{prompt}: [0-{len(names)}]'
while True:
print_selection_list(names)
pos: int = click.pr... | 5,316,715 |
def gram_matrix(features, normalize=True):
"""
Compute the Gram matrix from features.
Inputs:
- features: Tensor of shape (1, H, W, C) giving features for
a single image.
- normalize: optional, whether to normalize the Gram matrix
If True, divide the Gram matrix by the number of n... | 5,316,716 |
def yield_in_except_throw_instance():
"""
>>> g = yield_in_except_throw_instance()
>>> next(g)
>>> g.throw(TypeError())
Traceback (most recent call last):
TypeError
>>> next(g)
Traceback (most recent call last):
StopIteration
"""
try:
raise ValueError
except Value... | 5,316,717 |
def project_path(*relative_paths):
"""Full path corresponding to 'relative_paths' components"""
return os.path.join(MetaDefs.project_dir, *relative_paths) | 5,316,718 |
def get_html_docker(url: str) -> str:
"""Returns the rendered HTML at *url* as a string"""
cmd = ['docker',
'container',
'run',
'--rm',
'zenika/alpine-chrome',
'--no-sandbox',
'--dump-dom',
str(url)
]
with tempfile.Named... | 5,316,719 |
def convert_from_pj_fat_choice(py_json):
"""
Convert the given py_json into a PlayerFeedVegetarian
:param py_json: the PyJSON to convert
:type py_json: PyJSON
:return: the equivalent PlayerFeedVegetarian
:rtype: PlayerFeedVegetarian
"""
[species_index, fat_to_store] = py_json
if not ... | 5,316,720 |
def marshal(data, fields, envelope=None):
"""Takes raw data (in the form of a dict, list, object) and a dict of
fields to output and filters the data based on those fields.
:param data: the actual object(s) from which the fields are taken from
:param fields: a dict of whose keys will make up the final s... | 5,316,721 |
def _generator2(path):
"""
Args:
path: path of the dataframe
Returns:
yield outputs of X and Y pairs
"""
args = init_args()
catalog = load_catalog(path)
def preprocess(x):
zero = False
if not np.any(x):
zero = True
img = (x - avg_x) / std_... | 5,316,722 |
def main():
"""
Get the urls from receita website (to see structure of dict -- see tests)
:return: dict with urls from files as well as last modified date and size in bytes
"""
# get page content
page = requests.get(CORE_URL_FILES)
# BeautifulSoup object
soup = BeautifulSoup(... | 5,316,723 |
def dropDuplicatedResponses(dfResponses, dupIdColumns=None, returnDups=False):
"""
Take a parsed response data frame, returns a data frame after dropping duplications
:param dfResponses: data frame with responses
:param dupIdColumns: a list of column names to keep track when we identify duplications.
... | 5,316,724 |
def load(model_name):
"""Loads and returns pickle File
"""
return load_file(model_name) | 5,316,725 |
def get_policy_acc(graph, values):
""" compute the accuracy of policy predictions (per graph averaged manner)
:param graph: dgl.graph; possibly batched
:param values: (predicted) state values
:return:
"""
policy = get_policy(graph, values)
with graph.local_scope():
graph.ndata['corre... | 5,316,726 |
def domain_domain_pair_association(domain_type_dict, opposite_type_dict={'T': 'AT', 'AT': 'T'}):
"""
Compute domain domain association.
domain_type_dict is a {domain_name:{T:[gene_ids], AT:[gene_ids]} ... }
"""
domain_domain_dict = {}
for domain, type2genes in domain_type_dict.items():
... | 5,316,727 |
def SDIV(cpu_context: ProcessorContext, instruction: Instruction):
"""Signed divide"""
logger.debug("%s instruction not currently implemented.", instruction.mnem) | 5,316,728 |
def pull_jhu_data(base_url: str, metric: str, pop_df: pd.DataFrame) -> pd.DataFrame:
"""Pulls the latest Johns Hopkins CSSE data, and conforms it into a dataset
The output dataset has:
- Each row corresponds to (County, Date), denoted (FIPS, timestamp)
- Each row additionally has a column `new_counts`... | 5,316,729 |
def tensorflow2mnn():
"""
./MNNConvert -f TF --modelFile XXX.pb --MNNModel XXX.mnn --bizCode biz
"""
pass | 5,316,730 |
def sendmail(
image_filename=IMAGE_FILENAME, host='localhost', port=PORT,
username=None, password=None, addrs_from=FROM,
addrs_to=TO, addrs_cc=[], preamble="", subject=''):
"""
SSL is used if username is not None
"""
# Create the container (outer) email message.
msg ... | 5,316,731 |
def dict_from_graph_attr(graph, attr, array_values=False):
"""
Parameters
----------
graph : networkx.Graph
attr : str, iterable, or dict
If str, then it specifies the an attribute of the graph's nodes.
If iterable of strings, then multiple attributes of the graph's nodes
ar... | 5,316,732 |
def _filter_attenuation(h, frequencies, gains):
""" Compute minimum attenuation at stop frequency.
Args:
h (array): Filter coefficients.
frequencies (list): Transition frequencies normalized.
gains (array): Filter gain at frequency sampling points.
Returns:
att_db: Minim... | 5,316,733 |
def about1():
"""
Name : about1 function
Module : routes
Description : This function loads about1.html page.
Parameters: None
Returns : This function returns the About-us tab of the Web app.
Written By : Abhishek Mestry ,Ninad Kadam ,Viresh Dhuri
Version : 1.... | 5,316,734 |
def main():
""" Create the evaluated standards files
"""
biblio = Biblio(BIBLIOGRAPHY)
curated_standards = CuratedStandards(CURATED_STANDARDS_FILE, biblio)
curated_standards.check_all_titles()
curated_standards.enrich_with_bib_key()
curated_standards.enrich_with_survey_data()
curated_sta... | 5,316,735 |
def execute_barrbap(organism, dna_file, con):
"""determines the 16sRNA sequences using barrnap tool"""
# barrnap output file name e.g. barrnap.NC_000913
barrnap_out = cwd + "/barrnap." + organism
# > /dev/null 2>&1 is to disable stdout from displaying on terminal
barrnap_cmd = "barrnap " + str(dna_f... | 5,316,736 |
def local_adv_sub1_adv_inc_sub1(fgraph, node):
"""Optimize the possible AdvSub1(AdvSetSub1(...), ...).
AdvancedSubtensor1(AdvancedSetSubtensor1(x, y, idx), idx) -> y
Notes
-----
This opt add AssertOp. Otherwise, it would remove shape and
index error. If you want to get rid of them, see the
... | 5,316,737 |
def __split0_r_calc(r_tiles, q_dict, q_dict_waits, col_num, diag_pr, not_completed_prs):
"""
Function to do the QR calculations to calculate the global R of the array `a`.
This function uses a binary merge structure in the global R merge.
Parameters
----------
r_tiles : tiling.SquareDiagTiles
... | 5,316,738 |
def mock_coro(return_value=None, exception=None):
"""Return a coro that returns a value or raise an exception."""
fut = asyncio.Future()
if exception is not None:
fut.set_exception(exception)
else:
fut.set_result(return_value)
return fut | 5,316,739 |
def convert_to_classes(data: MoleculeDataset, num_bins: int = 20) -> Tuple[MoleculeDataset,
np.ndarray,
MoleculeDataset]:
"""
Converts regression data to classifi... | 5,316,740 |
def construct_lambda_schedule(num_windows):
"""Generate a length-num_windows list of lambda values from 0.0 up to 1.0
Notes
-----
manually optimized by YTZ
"""
A = int(.35 * num_windows)
B = int(.30 * num_windows)
C = num_windows - A - B
# Empirically, we see the largest variance ... | 5,316,741 |
def subset(client, report_xml):
"""
Parse an XML file produced from NUnit --explore option to list up all the viable test cases
"""
def on_element(e: Element):
build_path(e)
if e.name == "test-case":
client.test_path(e.tags['path'])
SaxParser([], on_element).parse(repor... | 5,316,742 |
def test_make_parser_for_final() -> None:
"""Test make parser on Final types."""
final = getattr(t, "Final") # pylint: disable=no-member
assert infer_parser(final[int]) == infer_parser(int) | 5,316,743 |
def compute_face_normals_and_areas(vertices: torch.Tensor, faces: torch.Tensor):
"""
:params
vertices (B,N,3)
faces (B,F,3)
:return
face_normals (B,F,3)
face_areas (B,F)
"""
ndim = vertices.ndimension()
if vertices.ndimension() == 2 and faces.ndim... | 5,316,744 |
def der_Cquat_by_v(q,v):
"""
Being C=C(quat) the rotational matrix depending on the quaternion q and
defined as C=quat2rotation(q), the function returns the derivative, w.r.t. the
quanternion components, of the vector dot(C,v), where v is a constant
vector.
The elements of the resulting derivat... | 5,316,745 |
def calc_BMDs(Tcpl,BMR=dict(E=[10,20,30],Z=[1,2,3]),
ret='dict',add_info=False,
dbg=False):
"""
Calculate benchmark doses corresponding to bmrs:-
E: fractional efficacy (top)
Z: number of standard deviations (assumes response is in units of Z)
"""
BF = Tcpl['bes... | 5,316,746 |
def request_records(request_params):
"""
Download utility rate records from USURDB given a set of request
parameters.
:param request_params: dictionary with request parameter names as
keys and the parameter values
:return:
"""
records = requests.get(
"https://api.openei.org/utili... | 5,316,747 |
def _handle_sort_key(model_name, sort_key=None):
"""Generate sort keys according to the passed in sort key from user.
:param model_name: Database model name be query.(alarm, meter, etc.)
:param sort_key: sort key passed from user.
return: sort keys list
"""
sort_keys_extra = {'alarm': ['name', ... | 5,316,748 |
def view_clear_pages_cache(self, request, form):
""" Clears the pages cache. """
layout = DefaultLayout(self, request)
if form.submitted(request):
request.app.pages_cache.flush()
request.message(_("Cache cleared."), 'success')
return redirect(layout.manage_link)
return {
... | 5,316,749 |
def cyan_on_red(string, *funcs, **additional):
"""Text color - cyan on background color - red. (see sgr_combiner())."""
return sgr_combiner(string, ansi.CYAN, *funcs, attributes=(ansi.BG_RED,)) | 5,316,750 |
def test_tse2(n):
""" Test TSE for giant bit distributions """
d = D(['0'*n, '1'*n], [1/2, 1/2])
tse = TSE(d)
assert tse == pytest.approx((n-1)/2) | 5,316,751 |
def calc_glass_constants(nd, nF, nC, *partials):
"""Given central, blue and red refractive indices, calculate Vd and PFd.
Args:
nd, nF, nC: refractive indices at central, short and long wavelengths
partials (tuple): if present, 2 ref indxs, n4 and n5, wl4 < wl5
Returns:
... | 5,316,752 |
def git_status_check(cwd):
"""check whether there are uncommited changes in current dir
Parameters
----------
cwd : str
current working directory to check git status
Returns
-------
bool
indicating whether there are uncommited changes
"""
pipe = subprocess.Popen(["... | 5,316,753 |
def light_rgb_schema(gateway, child, value_type_name):
"""Return a validation schema for V_RGB."""
schema = {"V_RGB": cv.string, "V_STATUS": cv.string}
return get_child_schema(gateway, child, value_type_name, schema) | 5,316,754 |
def macro_timedelta(start_date, years=0, months=0, days=0):
"""Since datetime doesn't provide timedeltas at the year or month level,
this function generates timedeltas of the appropriate sizes.
"""
delta = datetime.timedelta(days=days)
new_month = start_date.month + months
while new_month > 12:... | 5,316,755 |
def test_download_failure(mock_sdk, tmp_path):
"""If the skin download fails, an error is raised."""
# Mock a valid user response.
mock_sdk.command.input.return_value = "new-emulator"
# Mock a failure downloading the skin
mock_sdk.command.download_url.side_effect = requests_exceptions.ConnectionErr... | 5,316,756 |
def chomp_keep_single_spaces(string):
"""This chomp cleans up all white-space, not just at the ends"""
string = str(string)
result = string.replace("\n", " ") # Convert line ends to spaces
result = re.sub(" [ ]*", " ", result) # Truncate multiple spaces to single space
result = result.replace(" ",... | 5,316,757 |
def index():
"""Displays the main page"""
user = get_user()
# XXX
return redirect('/login')
# Render template
render = render_template('main.html', lang=lang, user=user)
return make_response(render) | 5,316,758 |
def merge_rr_graphs(filename, out_filename):
"""Merges the RR-graphs into a wafer.
Parameters
----------
filename : str
Name of the RR-graph file.
out_filename : str
Name of the file in which to store the wafer.
Returns
-------
None
"""
with open(filename, "r")... | 5,316,759 |
def plot_particle_level_spectra_agreement(difference: Hist, absolute_value_of_difference: Hist,
output_info: analysis_objects.PlottingOutputWrapper) -> None:
""" Plot the agreement of the particle level spectra between the inclusive and sum of all EP orientations.
Args... | 5,316,760 |
def update_ssh_config(sshurl, user, dryrun=False):
"""
Add a new entry to the SSH config file (``~/.ssh/config``).
It sets the default user login to the SSH special remote.
Parameters
-----------
sshurl : str
SSH URL of the git-annex special remote in the form
`ssh://server.exa... | 5,316,761 |
def test_Smoothing2D(par):
"""Dot-test for smoothing
"""
# 2d kernel on 2d signal
if par['dir'] < 2:
D2op = Smoothing2D(nsmooth=(5, 5), dims=(par['ny'], par['nx']),
dtype='float32')
assert dottest(D2op, par['ny']*par['nx'], par['ny']*par['nx'], tol=1e-3)
... | 5,316,762 |
def _unhumanize(human_time_interval):
"""Converts human_time_interval (e.g. 'an hour ago') into a
datetime.timedelta.
"""
munged = human_time_interval.strip()
for needle in _SINGULARS:
munged = munged.replace(needle, '1 ')
interval_re = '|'.join(_DELTAS.keys())
sre = re.match(r'[. ]... | 5,316,763 |
def earth_utc_to_mars_aat(utc_inp):
"""converts utc time on earth to aat time on mars
"""
return | 5,316,764 |
def parase_pbs_script(filename = "emtojob.pbs"):
"""
Parse the exe part of pbs file
Parameter
filename: str (filename-like)
The filename of the pbs script
Return
param_dict: dict
The dict of parameters.
"""
s = {"-q": "queue", "-A": "account", "-N": "job_... | 5,316,765 |
async def handle_errors(request: Request, exception: Exception):
"""
Handles exceptions raised by the API.
Parameters
----------
exception : Exception
Returns
-------
str
"""
return JSONResponse(
status_code=exception.code,
content={"message": exception.message}... | 5,316,766 |
def immortal():
""" Make target (if 400+) or self (if 399-) immortal. """
av = spellbook.getTarget() if spellbook.getInvokerAccess() >= 400 else spellbook.getInvoker()
av.setImmortalMode(not av.immortalMode)
return 'Toggled immortal mode %s for %s' % ('ON' if av.immortalMode else 'OFF', av.getName()) | 5,316,767 |
def backup(fname):
"""Function that backups the file fname adding the "-backup" string at the
end of the file name."""
shutil.copy(fname, fname + '-backup') | 5,316,768 |
def singletask():
"""Run requests one by one. Slower but safer."""
global population
for order, chromosome in enumerate(population):
result = call(chromosome.genes)
chromosome.result = result
chromosome.objective = 1 / (
(CONS["LOAD_MAGNITUDE"] / result["objective"]) - C... | 5,316,769 |
def read_command_line_branch(input_path=None, output_path=None):
"""
Read arguments from commandline and return all values in a dictionary.
If input_path and output_path are not None, then do not parse command line, but
only return default values.
Args:
input_path (str): Input file path, po... | 5,316,770 |
def build_patch_list(patch_list,
nr_row=None, nr_col=None, border=None,
max_width=1000, max_height=1000,
shuffle=False, bgcolor=255,
viz=False, lclick_cb=None):
"""
Generate patches.
:param patch_list: bhw or bhwc images in [0,255]
:param border: defaults to 0.1 * min(ima... | 5,316,771 |
def predict_fr(dst_path, ref_path):
"""
用于FR的预测函数
:param dst_path:
:param ref_path:
:return:
"""
assert ref_path is not None
if utils.is_img(dst_path):
img_dst = cv2.imread(dst_path)
img_dst = utils.transform(img_dst, config.input_process)[np.newaxis, ...]
img_ref... | 5,316,772 |
def disk_example():
"""Create an example of disk element.
This function returns an instance of a simple disk. The purpose is to make available
a simple model so that doctest can be written using it.
Returns
-------
disk : ross.DiskElement
An instance of a disk object.
Examples
... | 5,316,773 |
def build_optim(
model,
optim="adam",
lr=0.002,
max_grad_norm=0,
beta1=0.9,
beta2=0.999,
decay_method="noam",
warmup_steps=8000,
):
""" Build optimizer """
optim = Optimizer(
optim,
lr,
max_grad_norm,
beta1=beta1,
beta2=beta2,
decay... | 5,316,774 |
async def _async_report_telegram_handler(
*,
report: Report,
token: str,
chat_id: Union[int, List[int]],
api_url: Optional[str],
filename: Optional[str],
disable_notification: bool,
disable_web_page_preview: bool,
):
"""Send report.
Args:
report (Report): instance of rea... | 5,316,775 |
def bst(height=4):
"""Generate a random binary search tree and return its root.
:param height: the height of the tree (default: 4)
:return: the root of the generated binary search tree
"""
values = _generate_values(height)
root = _new_node(values[0])
for index in range(1, len(values)):
... | 5,316,776 |
def rotate_labels(which_ax='both', rot=0, axfs=6):
"""
Rotate the ticks labels to rot.
Also sets it fontsize to axfs
"""
if which_ax in ('x', 'both'):
_, labels = plt.xticks()
plt.setp(labels, rotation=rot, fontsize=axfs)
if which_ax in ('y', 'both'):
_, labels = plt.yti... | 5,316,777 |
def test_one_variant():
"""
Test the vcf_parser
"""
vcf_lines = [
'##fileformat=VCFv4.1\n',
'##INFO=<ID=MQ,Number=1,Type=Float,Description="RMS Mapping Quality">\n',
'##contig=<ID=1,length=249250621,assembly=b37>\n',
'##reference=file:///humgen/gsa-hpprojects/GATK/bundle'... | 5,316,778 |
def get_model_info(model: str, repo: str = "onnx/models:master", opset: Optional[int] = None) -> ModelInfo:
"""
Get the model info matching the given name and opset.
@param model: The name of the onnx model in the manifest. This field is case-sensitive
@param repo: The location of the model repo in for... | 5,316,779 |
def byprotocolobj(protocolobj):
""" Returns the Session for an instance of :class:`Protocol` given
as *protocolobj*. Keys will match when *protocolobj* is an
instance of the respective key class. """
for key in sessions.keys():
if isinstance(protocolobj, key):
return sessions[key]
... | 5,316,780 |
def trace_numpy_function(
function_to_trace: Callable, function_parameters: Dict[str, BaseValue]
) -> OPGraph:
"""Trace a numpy function.
Args:
function_to_trace (Callable): The function you want to trace
function_parameters (Dict[str, BaseValue]): A dictionary indicating what each input of... | 5,316,781 |
def random_crop(arr, new_h=224, new_w=224):
"""Crop an image of shape (dim, dim, channels) to (new_h, new_w, channels)."""
height = len(arr)
width = len(arr[0])
assert height >= new_h
assert width >= new_w
if height > new_h or width > new_w:
height_sample_pt = np.random.randint(height-ne... | 5,316,782 |
def bilingual(obj, field, attr=None):
""" This is a quick and dirty way to define bilingual content in a single field. """
field_locale = '%s_%s' % (field, get_language())
value = None
try:
value = getattr(obj, field_locale)
except AttributeError:
pass
if not value:
tr... | 5,316,783 |
def get_available_quantity(variant: "ProductVariant", country_code: str) -> int:
"""Return available quantity for given product in given country."""
try:
stock = Stock.objects.get_variant_stock_for_country(country_code, variant)
except Stock.DoesNotExist:
return 0
return stock.quantity_a... | 5,316,784 |
def in_range(x, a1, a2):
"""Check if (modulo 360) x is in the range a1...a2. a1 must be < a2."""
a1 %= 360.
a2 %= 360.
if a1 <= a2: # "normal" range (not including 0)
return a1 <= x <= a2
# "jumping" range (around 0)
return a1 <= x or x <= a2 | 5,316,785 |
def _dark_parse_accept_lang_header(accept):
"""
The use of 'zh-cn' for 'Simplified Chinese' and 'zh-tw' for 'Traditional Chinese'
are now deprecated, as discussed here: https://code.djangoproject.com/ticket/18419.
The new language codes 'zh-hans' and 'zh-hant' are now used since django 1.7.
Although... | 5,316,786 |
async def test_zeroconf_add_mrp_device(hass, mrp_device, pairing):
"""Test add MRP device discovered by zeroconf."""
unrelated_result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_ZEROCONF},
data=zeroconf.ZeroconfServiceInfo(
ho... | 5,316,787 |
def trip_direction(trip_original_stops, direction_stops):
"""
Guess the trip direction_id based on trip_original_stops, and
a direction_stops which should be a dictionary with 2 keys: "0" and "1" -
corresponding values should be sets of stops encountered in given dir
"""
# Stops for each directi... | 5,316,788 |
def unf_pb_Valko_MPaa(rsb_m3m3, gamma_oil=0.86, gamma_gas=0.6, t_K=350):
"""
bubble point pressure calculation according to Valko McCain (2002) correlation
:param rsb_m3m3: solution ration at bubble point, must be given, m3/m3
:param gamma_oil: specific oil density (by water)
:param gamma_gas: ... | 5,316,789 |
def disasm(file, objdump_or_gdb, symbol, start, finish):
"""
Disassemble binary file.
"""
if objdump_or_gdb:
out = _run(['objdump', '-d', file])
elif symbol is not None:
out = _run(['gdb', '-batch', '-ex', f'disassemble {symbol}', file])
else:
out = _run(['gdb', '-batch',... | 5,316,790 |
def gaussian_on_simplex(mu, sigma, npoints):
"""
This function provides npoints i.i.d. points on the simplex, normally
distributed according to sigma around :math:`mu`.
Parameters
----------
mu : 1D-numpy-array
expectation value on the simplex
sigma : 2D-numpy-array
covarian... | 5,316,791 |
def add_common_arguments(parser):
"""Populate the given argparse.ArgumentParser with arguments.
This function can be used to make the definition these argparse arguments
reusable in other modules and avoid the duplication of these definitions
among the executable scripts.
The following arguments a... | 5,316,792 |
def is_valid_path_and_ext(fname, wanted_ext=None):
"""
Validates the path exists and the extension is one wanted.
Parameters
----------
fname : str
Input file name.
wanted_ext : List of str, optional
Extensions to check
Return
------
bool
"""
if not os.path.... | 5,316,793 |
async def async_setup(bot: commands.Bot):
"""
The async setup function defining the jishaku.cog and jishaku extensions.
"""
await bot.add_cog(CacheCog(bot=bot)) | 5,316,794 |
def main():
"""
Prints the result of the case (3,1,5) using first coor, then coor_2
"""
print coor(3,1,5) | 5,316,795 |
async def test_check_settings_license_exemption_present():
"""
Test to make sure having an exemption in repo_license_exemptions results in change of license in all_results dict
"""
all_results = {MODULE_DICT_KEY: {}}
github_repo_mock = Mock()
test_repo = "test_repo"
test_org = "test_org"
... | 5,316,796 |
def test_escape_argument_simple_path():
"""
Test to make sure we encode simple path arguments correctly
"""
encoded = win_functions.escape_argument("C:\\some\\path")
assert encoded == "C:\\some\\path" | 5,316,797 |
def callWMplayer(chemin):
""" procedure qui lance Windows Media Player en plein ecran
parametre chemin vers l'image ou la video
"""
""" 'CALL' est une instruction windows qui lanc e un programme
le premier chemin est celui vers windows media player
le second est le chemin vari... | 5,316,798 |
def circuit(params, a, m1, m2, cutoff):
"""Runs the constrained variational circuit with specified parameters,
returning the output fidelity to the requested ON state, as well as
the post-selection probability.
Args:
params (list): list of gate parameters for the constrained
variati... | 5,316,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.