content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def URem(a, b):
"""Create the SMT expression (unsigned) remainder `self % other`.
Use the operator % for signed modulus, and SRem() for signed remainder.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> URem(x, y)
URem(x, y)
>>> URem(x, y).sort()
BitVec(32)
>>> (x % y).sexpr()
... | e37ed84f308e0936880f134344c9563428110059 | 3,619,850 |
import requests
def _make_request(endpoint: str) -> dict:
"""Helper method handles terra fcd api requests. [Source: https://fcd.terra.dev/v1]
Parameters
----------
endpoint: str
endpoint url
Returns
-------
dict:
dictionary with response data
"""
url = f"https://f... | 85617c3fbba2b8bd3624e50837f3f9fecd97555d | 3,619,851 |
import time
def fix_end_now(json):
"""Set end time to the time now if no end time is give"""
if 'end' not in json or json['end'] is None:
json['end'] = int(time.time())
return json | 2c126e00ac293c6a511cb86457d60536f1d690ef | 3,619,852 |
def file_to_bounding_boxes(file_path, output_folder=None, save_images=False, **kwargs):
"""
file_path: path to image file.
"""
# read image using PIL:
image = Image.open(file_path)
# convert to numpy array:
image_numpy = np.asarray(image)
# Predict bounding boxes and store to dictionar... | 60efc4bfb7c5fbe6d97658f4b54888bcb8415091 | 3,619,854 |
def count_parameters(net, trainable=False):
"""Counts the parameters of a given PyTorch model."""
params = trainable_parameters(net) if trainable else net.parameters()
return sum(p.numel() for p in params) | 4fc2b7fe1c40bb60db48270da4b03dcdd8499728 | 3,619,855 |
def prepare_computational_basis(nqubits, number):
"""Encode number as binary and create the circuit"""
# Create empty circuit of requested size
qc = QuantumCircuit(nqubits)
# encode number into a byte array
ba = int2ba(number, nqubits);
# Populate the circuit
for q in range(nqubi... | ca2d1d3ca6b153aa02cedf45a7f80647ef7dbbc0 | 3,619,856 |
def dropout(x, rate, is_training):
"""drop out layer"""
return tf.layers.dropout(x, rate, name='dropout', training = is_training) | 1965781d9b16708e5c0dc8c8b153bd2d24c13395 | 3,619,857 |
def get_cell_inj_span(test_line):
"""
Return the location of %cell in the given line as (start_index,
end_index), or None if %cell does not occur.
"""
if not test_line.strip().startswith(CELL_INJ_TOKEN):
return None
else:
cell_start = test_line.index(CELL_INJ_TOKEN)
cell_... | bd844a139cbd28b697b877c07f094d56094f7460 | 3,619,858 |
def in1u_w(name, shape, seed=None, regu=None):
"""
Convolutional Architecture for Fast Feature Embedding.
FAN_IN, factor=1.0, uniform=True.
"""
init = tf.contrib.layers.variance_scaling_initializer(
factor=1.0, mode="FAN_IN", uniform=True, seed=seed)
return w(name, shape, tf.float32,... | 992d3e19eaa869d3da67d480382f73728918e773 | 3,619,859 |
def topics_to_calldata(topics, bytes_per_topic=3):
"""Converts a list of topics to calldata.
Args:
topics (bytes[]): List of topics.
bytes_per_topic (int): Byte length of each topic.
Returns:
bytes: Topics combined into a single string.
"""
return b''.join(topic.to_bytes(b... | 2d500016963934fdbc60b388632b817624d5ad8d | 3,619,860 |
def read_size(calibxml):
"""
This function extracts the size of an image from the xml file.
.. note::
Usually, it is similar to "AutoCal_[Focal]_[CameraName].xml"
Parameters
----------
calibxml : str
Name of the camera calibration file
Returns
-------
np.ndarra... | 5fb106c54ed63a13c6f8ae312fb2e5b6055a0a20 | 3,619,861 |
import re
def get_packages_names(latex_file):
"""Find all the package name in a file
Args:
latex_file: A pathlib file
Returns:
A list of all the package name found in the latex_file
"""
with latex_file.open('r', encoding='utf-8') as f:
data = f.read()
packages_info ... | 6eb1b1c02ef254fa6e112ecbae960060af3b7405 | 3,619,862 |
def remove_basic_block_assembly(pydot_cfg):
"""
Remove assembly text from the CFG's basic blocks
"""
# Avoid graph and edge nodes, which are the 1st and 2nd nodes
nodes = pydot_cfg.get_nodes()[2:]
for n in nodes:
n.set_label("")
return pydot_cfg | 3ca5d7fcd46dc96bff92aea67b47afbe53accc40 | 3,619,863 |
def CheckNaN(data):
"""
Raise exception if data contains NaN.
Useful to stop training if network doesn't converge and loss function
returns NaN. Example:
samples >> network.train() >> CheckNan() >> log >> Consume()
>>> from nutsflow import Collect
>>> [1, 2, 3] >> CheckNaN() >> Collect()
... | c6d10a034a787e53ef493c755e326bd374131427 | 3,619,865 |
from typing import Any
def build_patch302_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest:
"""Patch true Boolean value in request returns 302. This request should not be automatically
redirected, but should return the received 302 to the caller for evaluation.
See https:/... | 300330aea3a177307e52d77f55df9844f367e39b | 3,619,866 |
def construct_array(nums):
"""
:param nums: array
:return: mul array
"""
l = len(nums)
ans = [1 for _ in range(l)]
p = q = 1
for i in range(l):
ans[i] *= q
ans[-i - 1] *= p
q *= nums[i]
p *= nums[-i - 1]
return ans | 5327945cbb83290af94efcce07e4ae391fb3da45 | 3,619,867 |
def create_col(card: dbc.Card) -> dbc.Col:
"""Pass each card to create a Col element"""
return dbc.Col(
className="mb-2",
children=[card],
width=12,
sm=12,
lg=6,
xl=4
) | 8624d68e7a80cefe6587a614150aed0023412428 | 3,619,868 |
def make_report(subreads, output_dir, dpi=DEFAULT_DPI):
"""
Create a basic subread metrics report. Since this may be run either as an
independent tool or as part of the barcoding report, it handles the .pbi
file reading flexibly.
"""
pbi_stream = get_pb_index_streamed(subreads)
dists, uniqu... | 469f22291ff591aeaf6219a97eb09aa4d4ad966c | 3,619,870 |
def return_point(m, n, p):
"""
m is the index number of the Hammersley point to calculate
n is the maximun number of points
p is the order of the Hammersley point, 1,2,3,4,... etc
l is the power of x to go out to and is hard coded to 10 in this example
:return type double
"""
if p == 1:... | 73b1c75d6b4ebdc6a0616d9a7b2d6207a4728316 | 3,619,871 |
def select2_css_url():
"""
Return the full url to the Select2 CSS file.
"""
return get_select2_setting('css_url') or \
select2_url('css/select2.min.css') | ea9cac6f9e687620ed3cc8d4c45d33e551df3dbe | 3,619,872 |
def GetQuasiSequenceOrder(ProteinSequence, maxlag=30, weight=0.1):
"""
###############################################################################
Computing quasi-sequence-order descriptors for a given protein.
[1]:Kuo-Chen Chou. Prediction of Protein Subcellar Locations by
Incorporating Quasi... | 99b0d6129f2693893382493a3de241cd00f75b68 | 3,619,873 |
def OverscanTrim(d,ds):
"""
Overscan correct and Trim a refurbished HIRES image
"""
ds = ds.split(',')
dsy = ds[0][1:]
dsx = ds[1][:-1]
dsy = dsy.split(':')
dsx = dsx.split(':')
x0 = int(dsx[0])-1
x1 = int(dsx[1])
y0 = int(dsy[0])-1
y1 = int(dsy[1])
newdata = d[x0:x1]... | ceb434ca75f458c43137b73b89c0f0242bfe7e93 | 3,619,874 |
import requests
def requests_put(url, expected_sc=200, **kwargs):
"""
Calls our above requests wrapper for a PUT request, and sets the default expected status code to 200.
"""
return do_request_with_auth_retry(url=url, method=requests.put, expected_sc=expected_sc, **kwargs) | 3c5aa69d8b21e67960cfff76820ccf2b64a6f879 | 3,619,875 |
def calculate_decomposition(data, model=MODEL_ADDITIVE, frequency=2):
"""
Calculate time series decomposition
Args:
data (list[float]): Input time series values
model (str): Seasonal component type
frequency (int): Seasonal component frequency
Returns:
dict: Calculation... | 444e05c5f36479f7c1ddbd8c7fbb3d6785d6bf2f | 3,619,876 |
from typing import List
from typing import Dict
def add_funders_relationships(funders: List, funders_by_key: Dict) -> List:
""" Adds any children/parent relationships to funder instances in the funders list.
:param funders: List of funders
:param funders_by_key: Dictionary of funders with their id as key... | 4411094812ae3932453f4cbb33f8c845fca6f800 | 3,619,877 |
import re
def __tokenize(syntax) -> list:
"""
Validate and tokenize the syntax.
Valid syntax: snake_case_words, integers, plus, minus.
"""
if not re.match(r"^[\w\d\s\+-]+$", syntax):
raise SyntaxError("Invalid syntax.")
syntax = re.sub(r"\s*([+-])\s*", r" \g<1> ", syntax)
return ... | 68e79222987771d964ac0d39e38c425d710d3765 | 3,619,878 |
import copy
def reducer(state, action):
"""Screen specific reducer
Given :func:`screen.set_position` action adds "position" data
to state
:param state: data structure representing current state
:type state: dict
:param action: data structure representing action
:type action: dict
"""... | 2c918ee2b9ae40689f1df4de6b48a1da951716de | 3,619,879 |
def see_model_list():
"""
Get's the data about all models in the DB to put on a table:
- name
- organism
- strain
Returns:
render_template to see_data with tab_status set to models.
"""
tab_status = {"enzymes": "#", "metabolites": "#", "models": "active", "organisms": "#", "... | 1edcdc1382d3a6d26f22e8e5ffcb9a5f1c294742 | 3,619,880 |
def localsys_get_login():
"""Retrieves the login credentials from the computer you are on.
Good for command line tools"""
try:
sid = local_credentials.get_password('minervaclient_sid','minerva')
pin = local_credentials.get_password('minervalcient_pin','minerva')
if sid is None or pin... | d3c6a5870680f8688816e158015260d598c001fe | 3,619,881 |
def GetOrigFn( module, fnName ):
"""Return the original function."""
return DictGet( orig_fns, ( module, fnName ), getattr( module, fnName ) ) | cb36ff0baa63abd08ac9651a251cd6feb2e7913b | 3,619,882 |
import platform
def host_toolchain(xcrun_toolchain='default', tools=None, suffixes=None):
"""
Return a Toolchain with the first available versions of all
specified tools, plus clang and clang++, searching in the order of the
given suffixes.
If no matching executables are found, return None.
"... | d385dc97ea2051282b5d096fb1243783d067c46a | 3,619,883 |
def transcribe_audio(audio_stream, model: str, language_code: str):
"""
Transcribe the given audio chunks
"""
global client
encoding = RecognitionConfig.AudioEncoding.LINEAR16
try:
audio = RecognitionAudio(content=audio_stream)
config = RecognitionConfig(
s... | 0c2c0c7c5455cdb79965bd38108a6e71ddde41a9 | 3,619,884 |
def indent(yaml: str):
"""Add indents to yaml"""
lines = yaml.split("\n")
def prefix(line):
return " " if line.strip() else ""
lines = [prefix(line) + line for line in lines]
return "\n".join(lines) | 815babb29378f1cfac6ada8258322df92235fc9e | 3,619,885 |
def smooth_pr(prec, rec):
"""
Smooths precision recall curve according to TREC standards. Evaluates max precision at each 0.1 recall. Makes the curves look nice and not noisy
"""
n = len(prec)
m = 11
p_smooth = np.zeros((m), dtype=np.float)
r_smooth = np.linspace(0.0, 1.0, m)
for i in range(m):
j = np.argmi... | 6129cb1348446df2f56eb5601cac585c498d5311 | 3,619,886 |
def get_rbac_role_assigned(self) -> dict:
"""Get list of accessible menus based on the current session
permissions
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - rbacRole
- GET
- /rbac/role/menuAssigned
.. no... | 91d0dcbded36b857a0dc0ddfeaa2815516d162f6 | 3,619,887 |
def close_session(module_session):
"""Closes the Shell Interactive Session
Args:
module_session (object): The module session object that should be closed
Returns:
A dict holding the result message
"""
module_session.close()
return Response.ok("The Shell Interactive session has be... | 45bc4a094e8d33320efb1b5738ee59fddc344f46 | 3,619,888 |
def Xfact(m):
"""Xfact(m)
Computes (2m-1)!!/sqrt((2m)!)
"""
res = 1.
for i in xrange(1,2*m+1):
if i % 2: res *= i # (2m-1)!!
res /= np.sqrt(i) # sqrt((2m)!)
return res | 23653360ef3f8f5d4e5b9cdb16e8ab58835960cf | 3,619,889 |
import requests
def stacks_list(credentials):
"""
List the stacks accessible to the currently logged in user.
"""
url = _urljoin(credentials["host"], "api/a0.1/stacks/")
headers = {"Authorization": "Token {}".format(credentials["token"])}
resp = requests.get(_ensure_protocol(url), headers=head... | 9a63b7a402104f41f6a7c1f9c023b979428b088f | 3,619,891 |
from typing import List
def get_dev_requirements() -> List[str]:
"""Fetch requirements for library development."""
with open(_DEV_REQUIREMENTS, mode="r") as f:
return f.readlines() | b0f9a4a958d64ff3da0c7622fb6dcea69dd95de5 | 3,619,894 |
def wait_result(ref):
"""
Waits for the referenced agent to finish, whereupon its latest result will
be returned.
Args:
ref (uuid.UUID): The UUID of the agent. Usually received when a window
is created.
Raises:
KeyError: When an agent with the given UUID could not be fo... | afa95f1378813da5bedeea3d2e9aa2c3a5b7108b | 3,619,895 |
import torch
from typing import Tuple
def mask_tokens(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, args) -> Tuple[torch.Tensor, torch.Tensor]:
""" Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. """
if tokenizer.mask_token is None:
raise ... | 7f633b0c08de12655b406c852dd038aca3dd64d4 | 3,619,896 |
def _has_sectors(tax_name: str, ignore_sectors: bool) -> bool:
"""Determine whether we are doing a sector-based forecast."""
return tax_name in ["birt", "sales", "wage", "rtt"] and not ignore_sectors | 5725693c514937988b4e668c699606cb3ab46d10 | 3,619,897 |
import tqdm
def merge_modules(pose_graph, module_corners, observations,
image_width, image_height, merge_threshold, max_module_depth, max_num_modules,
max_combinations, reproj_thres, min_ray_angle_degrees):
"""Merge duplicate modules by projecting each module into each keyframe
and finding overlapp... | d228530251074b39abf5234be0418818f224c867 | 3,619,898 |
def KK_RC23_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | fab416c023a215c62e51c6cc2e5857be8e85a063 | 3,619,899 |
def normalize_dates(df,col):
"""Normalize the DF using min/max"""
scaler = MinMaxScaler(feature_range=(-1, 1))
df_values= df[col].values.reshape(-1,1)
dates_scaled = scaler.fit_transform(df_values)
return pd.DataFrame(dates_scaled) | 017e643c1536cb7b39546515aed7d5a303614a7f | 3,619,900 |
def discretize_instationary_cg(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None,
grid=None, boundary_info=None, num_values=None, time_stepper=None, nt=None,
preassemble=True):
"""Discretizes an |InstationaryProblem| with an |Sta... | db6c1bab4fc592e628e5059333d1bea061f98d62 | 3,619,901 |
def index():
"""List parties."""
parties = party_service.get_all_parties_with_brands()
parties.sort(key=lambda party: party.starts_at, reverse=True)
active_parties, archived_parties = partition(
parties, lambda party: not party.archived
)
brands = brand_service.get_all_brands()
bra... | fd95b27dcc32021239ca8320382bf9c8518e234a | 3,619,903 |
def parse_doi(iso_xml):
"""Get the DOI from an ISO XML doc"""
tree = ET.parse('iso.xml')
root = tree.getroot()
doi_el = root.findall(
'.gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/'
'gmd:CI_Citation/gmd:identifier/gmd:MD_Identifier/gmd:code/'
'gco:CharacterString', NS_DICT
)[0]
... | dcd322984f0cd1fda7ddf6e8763251e92e1856d6 | 3,619,904 |
def ajax_instagram_confirm(request):
"""
View called by an ajax function, it confirms that a user saw the Instagram modal.
"""
user = request.user
user.instagram = False
user.save()
return JsonResponse({"ok", True}) | 1c1a52034c3f3ae35327496bb959936dea59a253 | 3,619,905 |
from typing import Optional
def get_migration_from_new_config_key(new_config_key: str) -> Optional[AbstractPropertyMigration]:
"""
Get a migration from new config key.
"""
return _history_from_new_config_key_dict.get(new_config_key) | bfd0252c98bcf82d4d4dcefbaa2ad85d2a4db703 | 3,619,906 |
def _build_array_type(var, property_path=None):
""" Builds schema definitions for array type values.
:param var: The array type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The built s... | e7c4de84e7410010c1e9ff799e46f644a1be9ef7 | 3,619,907 |
def td_processor(df):
""" Process dataframe for TD trial types """
onset_new, duration_orig, trial_type, delay, response, rt, onset_orig = [
df[name].copy() for name in
['onset', 'duration', 'trial_type',
'delay_time_days',
'response_button',
'reaction_time',
... | 5dda7c2281be12accee7db028521906073fa703a | 3,619,908 |
import binascii
def des_descrypt(s):
"""
DES 解密
:param s: 加密后的字符串,16进制
:return: 解密后的字符串
"""
secret_key = '20171117'
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
return de | 67eb89af8eb47a7d735aa054770797a2386b9ec6 | 3,619,909 |
def _kirkwood_muller_dispersion_ads(p_ads, m_ads):
"""Calculate the dispersion constant for the adsorbate.
p and m stand for polarizability and magnetic susceptibility
"""
return (1.5 * constants.electron_mass * constants.speed_of_light**2 * p_ads * m_ads) | 58766d18dcd5eb82e14751f2dbbc15ad57c947f9 | 3,619,910 |
from typing import List
def connect_mol_from_frags(frags: List[Chem.rdchem.Mol], fragmentor: FragmentorBase) -> Chem.rdchem.Mol:
"""
Given a list of fragments (RDKit mol objects) with attachment points [*] marked by integer pairs (attachment_idx)
Return a new mol object
Atom properties are maintained... | b3215551122603e5a1f56cd0131b1bc4c980fcfa | 3,619,911 |
from typing import Sequence
from typing import List
def get_all_lists() -> Sequence[List]:
"""Return all lists."""
lists = db.session.query(DbList).all()
return [_db_entity_to_list(list_) for list_ in lists] | 71f5360f6a2c47811eea03f03b8def984d6f70d0 | 3,619,912 |
def annotate_FayAndWusH(T, lineage_uid, df_seqs, fit_params_kingman, fit_params_BSC, seq_string_uid_to_uid):
""" Traverse tree, calculate Fay and Wu's H for each node, and calculate significance """
annotations = []
# Condition for stopping traversal
def stop(node):
if node.name == "germli... | 54605d0cfdc23a598e8310b0019a4e339cdfecf1 | 3,619,913 |
def include_jquery():
"""
Return whether to include jquery
Setting could be False, True|'full', or 'slim'
"""
return get_bootstrap_setting("include_jquery") | a9bfcf07ee9f9523721561e50dd14821df4852fb | 3,619,914 |
import torch
def isample_from_lineseg(z_vals, weights, N_importance,
det=False, pytest=False, is_only=False,
alpha_base=0.01):
"""
Importance sampling on the line segments
--
z_vals: original sample points to center on
weights: weighted distributio... | 72a92e023bde4a6bb83a06041c206b7fab1b5861 | 3,619,915 |
import itertools
def read_mf_scans(filename_list=None, # type: ['str']
ub_matrix=None, intensity_matrix=None, processes=1, a3_offset=None, a4_offset=None):
"""
# type: (...) -> ['Scan']
Reads TASMAD scan files.
:param filename_list: A list of TASMAD file names to read. User will be ... | 3f818e91747631a51677f04d2a6533cf3c653876 | 3,619,916 |
def get_current_tpc():
"""
Returns: The current TargetPlatformCapabilities that is being used and accessed.
"""
return _current_tpc.get() | ee9a074982fe67eed85abc3d4cbf123b50b03f96 | 3,619,917 |
def concatenate_state_matrices(G):
"""
Takes a State() model as input and returns the A, B, C, D matrices
combined into a full matrix. For static gain models, the feedthrough
matrix D is returned.
Parameters
----------
G : State
Returns
-------
M : ndarray
"""
if not is... | 5c260fe0d97b8472a7aa3925f922854fc80eb654 | 3,619,920 |
def load_fossil():
"""Fossil"""
return _load_local('fossil') | 0922049db08170082b97c0ecc0d0e34f287d8557 | 3,619,921 |
from typing import Counter
def main(args=None, **kwargs):
"""Main function of the Counter module."""
# PROTECTED REGION ID(Counter.main) ENABLED START #
return run((Counter,), args=args, **kwargs)
# PROTECTED REGION END # // Counter.main | 03011ff55cc179fbdf2e63e8f4d2300045f55947 | 3,619,923 |
import numpy
def _link_local_maxima_by_velocity(
current_local_max_dict, previous_local_max_dict,
max_velocity_diff_m_s01):
"""Does velocity-matching for local maxima at successive times.
N_c = number of maxima at current time
N_p = number of maxima at previous time
:param current_lo... | e36e914588a60d012fa4a1ddf47c1f13cfe29e62 | 3,619,924 |
def exp(x : float,iterations : int = 100,taylor_exapnsion=False):
"""Calulates the exponential function,\n
if taylor_exapnsion is set to True it will do what it says,\n
use the taylor expansion of the exp function for calculations,\n
else it will use the stored constant e and raise it to the... | 7bc57ad994ef3f6adafd0c12c902660ea2f59a4b | 3,619,926 |
def numPointsInSpans(spans):
"""
ARC112B
>>> numPointsInSpans([(1, 3)])
3
>>> numPointsInSpans([(1, 3), (5, 7)])
6
>>> numPointsInSpans([(1, 3), (3, 5)])
5
>>> numPointsInSpans([(1, 3), (2, 5)])
5
"""
timeline = []
for start, end in spans:
assert start <= end
... | e1ffecb3a1d4147f4b15256278f398c5213df200 | 3,619,927 |
def load_notebook_template(**kwargs):
"""
kwargs: the parameters to be replaced in the yaml
Reads the yaml for the web app's custom resource, replaces the variables
and returns it as a python dict.
"""
return helpers.load_param_yaml(NOTEBOOK_TEMPLATE_YAML, **kwargs) | a33d1616064f9385e010a9d496635fd4e3a7f2b8 | 3,619,928 |
def grab_data(conn, schema, table, columns):
""" Obtain data from Postgres.
:param schema: name of schema in db
:param table: name of table in schema
:param columns: list of column names (not working yet)
:type schema: str
:type table: str
:return: data from data
:rtype: two-dimensional... | 1d4aae5ef1cc1446215165cefb532a42b0f9e6ba | 3,619,929 |
def merge_import_policies(value, order=""):
"""
Merges and returns policy list for import.
If duplicates are found, only the most specific one will be kept.
"""
if not hasattr(value, "merged_import_policies"):
raise AttributeError("{value} has not merged import policies")
return value.... | adaaf5626e09022b36b69b332fb85788665c114e | 3,619,930 |
import copy
def _fix_xlink_ns(tree):
"""Fix xlink namespace problems.
If there are xlink temps, add namespace and fix temps.
If we declare xlink but don't use it then remove it.
"""
xlink_nsmap = {"xlink": xlinkns()}
if "xlink" in tree.nsmap and not len(
tree.xpath("//*[@xlink:href]",... | 0df54d7c6e12f4ef9afb3cde356a8528d45c1a1b | 3,619,931 |
def run_ldd(ldd, binary):
"""Runs `ldd` and gets the combined stdout/stderr output as a list of lines."""
if not detect_elf_binary(resolve_binary(binary)):
raise InvalidElfBinaryError('The "%s" file is not a binary ELF file.' % binary)
process = Popen([ldd, binary], stdout=PIPE, stderr=PIPE)
st... | 7a3ee428941d0f4594b1b2bff6b71ce74a4944ee | 3,619,932 |
def wind_ms(wind_ms):
"""Checks units for wind_ms"""
return check_array_bounds(
arr=wind_ms, lims=(0, 50), action="warn", name="Wind speed (m/s)"
) | 9829892705177f4bb0ff2f43ca335ffbf757e155 | 3,619,933 |
def disqus_dev(context):
"""
No longer supported by Disqus
"""
return {} | 9d823582b4ddc4e3bed992ef203642641ef83486 | 3,619,934 |
def multivariableode(t,x):
"""Function containing the ODE x_1' = -x_1 + x_2
x_2' = -x_2 .
"""
xprime = np.empty([2], float);
xprime[0] = -x[0] + x[1];
xprime[1] = -x[1];
return xprime; | d80958809a5c493566e84f0dcf19bbeb48ffb0b8 | 3,619,935 |
def plot_factor_contribution_to_perf(
perf_attrib_data,
ax=None,
title="Cumulative common returns attribution",
):
"""
Plot each factor's contribution to performance.
Parameters
----------
perf_attrib_data : pd.DataFrame
df with factors, common returns, and specific returns as c... | c2f063e0dddb6ffde568d53048034d6a8341ac0b | 3,619,936 |
from typing import Dict
def dict_to_nice_string(control_dict: Dict) -> str:
"""
Converts a dictionary of options (like template_control_dict)
to a more human readable format. Which can then be printed to a text file,
which can be manually modified before submiting analysis jobs.
Parameters
... | 10d09f0468356f0c0252e58c98efcfad39a243e4 | 3,619,937 |
def min_sentence_set():
""" minimum query """
return {'hello', 'world'} | 6ec3b76f47c9596422c473b4401ce4124806ec1c | 3,619,938 |
def _sort_student(name: str) -> str:
"""
Return the given student name in a sortable format.
Students are sorted by last name (i.e., last space-split chunk).
"""
return name.lower().split()[-1] | 92747346e0e6ded9715761b8907ccb8ab33da742 | 3,619,939 |
def XYZ_to_Hunter_Lab(
XYZ: ArrayLike,
XYZ_n: ArrayLike = TVS_ILLUMINANTS_HUNTERLAB[
"CIE 1931 2 Degree Standard Observer"
]["D65"].XYZ_n,
K_ab: ArrayLike = TVS_ILLUMINANTS_HUNTERLAB[
"CIE 1931 2 Degree Standard Observer"
]["D65"].K_ab,
) -> NDArray:
"""
Converts from *CIE XY... | 28c9260e32effd24703f36d372a171a47549e819 | 3,619,940 |
def inverse_transform(w, Jmin=2):
"""
Compute the wavelet inverse transform of w
"""
return perform_wavelet_transf(w, Jmin, -1) | 6e364c774aa08c2feb2694440817ac0d5a940f38 | 3,619,941 |
from typing import Union
from typing import Tuple
def split_element_id(element_id: Union[str, bytes]) -> Tuple[str, int]:
"""
Splits a combined element_id into the collection_string and the id.
"""
if isinstance(element_id, bytes):
element_id = element_id.decode()
collection_str, id = elem... | 9f94dc6d5e2f7eadca0d069987321039def2fcc0 | 3,619,943 |
import re
def is_gcd_file(filename: str) -> bool:
"""Checks whether `filename` is a GCD file."""
if re.search('(gcd|geo)', filename.lower()):
return True
return False | 3022bd165683cde609d1f866c3ce655e84561dc4 | 3,619,944 |
def overlap_coeff(arr1, arr2):
"""
This function computes the overlap coefficient between the two input
lists/sets.
Args:
arr1,arr2 (list or set): The input lists or sets for which the overlap
coefficient should be computed.
Returns:
The overlap coefficient if both the ... | 3396f28f2e6b21af5dd7bcb00fc07632181c5346 | 3,619,946 |
def _clean_to_gce_name(identifier):
"""
GCE requires the names of all resources to comply with RFC1035. This
function takes an identifier which might not comply with RFC1035 and
attempts to map it into the logical equivalent identifier that does match
RFC1035.
:param unicode identifier: The inp... | b9ffe1a83abe3206b1d57c726f6eb8e95397fc28 | 3,619,947 |
def get_incompatible_fields(ga_ads_service):
"""
Return list of incompatible fields for the metrics and segments
here - we can't directly get incompatible fields, we received list of selectable fields for each fields.
- Hence, to get incompatible fields, we remove selectable from all_fields.
""... | 00752e4b0ae3704fc88e602bb354aba7895501c0 | 3,619,948 |
def update_user(username, infos):
""" Update a user by its username
arg infos: Dict
return True if deleted or False if not found
"""
with session_scope() as session:
user = session.query(User)
ret = user.filter_by(username=username).update(infos)
return bool(ret) | f763a9c75df45b163a3fe72e1b96e1e867d7b74b | 3,619,949 |
def rectplot(x,xpos,ylim=[],**kwargs):
""" plot rectangles on an axis
Parameters
----------
x : ndarray
range of x
xpos : ndarray (nbrect,2)
[[start indice in x rectangle 1, end indice in x rectangle 1],
[start indice in x rectangle 2, end indice in x rectangle 2],
... | ae9f6f1f2d96d3d3e31e4a3c32dec1ddbc940b40 | 3,619,950 |
def del_course_package():
"""
swagger-doc: 'schedule'
required: []
req:
course_id:
description: '课程id'
type: 'string'
type:
description: '1:一级,2:二级,3:三级,4:课包'
type: 'string'
res:
verify_code:
description: 'id'
type: ''
"""
cou... | 4f3dddb610b4b12d606535b983bb0d0e8b47f882 | 3,619,951 |
def run_isfa(img_X, img_Y):
"""
Wrapper of the Slow Feature Analysis algorithm.
:param img_X: First image.
:param img_Y: Second image.
:return:
bcm: Binary change matrix between both images
"""
channel, img_height, img_width = img_X.shape
sfa = ISFA(img_X, img_Y)
# when max... | 7fe37d68d311e523d7b7534044cdad2f71905d7d | 3,619,952 |
import requests
import json
def polling_locations_import_from_master_server(request, state_code):
"""
Get the json data, and either create new entries or update existing
:return:
"""
# Request json file from We Vote servers
messages.add_message(request, messages.INFO, "Loading Polling Location... | 7be3f8acb609103c43591cfbdd40ee231075b28f | 3,619,954 |
def pactfile() -> str:
"""
A sample Pact file as a string.
"""
with open(
PROJECT_ROOT / "test_app" / "pactfiles" / "LibraryClient-Library-pact.json",
"r",
) as f:
return f.read() | c0281fbf065d783f26c63592eb66a8be980056a1 | 3,619,955 |
def grig2dataset(grbs, params_of_interest):
"""
Parameters
----------
grbs : TYPE
DESCRIPTION.
params_of_interest : TYPE
DESCRIPTION.
Returns
-------
ds : TYPE
DESCRIPTION.
"""
params_df = params_of_interest.copy()
# get lat and lon
grb = g... | 4befc23501cb9e0c44dfb8e777f933899524dc08 | 3,619,956 |
import re
def search_song(df, query):
"""
search_song: Fetches the closest matching song from the database
- If multiple are found, return a list of potential songs
:param df: DataFrame object to obtain info of search result
:param query: A query in string format, usually the name ... | cd072523c965dd187c04d2f4901a82dd491c1b75 | 3,619,957 |
from pathlib import Path
def _test_path(fn):
"""Leads to files saved in the data folder
Parameters
----------
fn: str
The whole filename.
Returns
-------
The path of the file in the current working system.
"""
return Path(__file__).parent / "data" / fn | 2f6d7e6b952c40e8fe8cefd1c0c8f0c000e02fdd | 3,619,958 |
def mirror_axis(cube,axis=-2):
"""Mirror one axis of an n-cube.
Parameters
----------
cube : array
Expected shape of cube: (...,nx,...).
axis : int
axis index to be mirrored. Default: -2. Mirroring assumes a
central columns of elements. See 'Returns' section.
Returns
... | dd6519ac49e05d90e58eceb99827c6ac6c044bb9 | 3,619,959 |
def lw(W, Wref=1.0e-12):
"""
Sound power level :math:`L_{w}` for sound power :math:`W` and reference power :math:`W_{ref}`.
:param W: Sound power :math:`W`.
:param Wref: Reference power :math:`W_{ref}`. Default value is :math:`10^{12}` watt.
"""
if type(W) is list:
W = np.array(W)
... | 88b0f41aaccd39629f5cff9a2b825f857b37a9de | 3,619,960 |
def calc_hydrogen_bond_interactions(protein, mol, key_inters_defs, mol_key_inters,
filter_strict=False, exact_protein=False, exact_ligand=False):
""" Calculate H-bond interactions
Parameters:
protein (Molecule): The protein
mol (Molecule): The ligand to test
key_... | 3c6dbfddc631dbbd6f02a57c928bfaaec5ed5ae3 | 3,619,961 |
def yes_or_no(msg, *params, yes=True, certain=False, third_choice=False):
"""Query yes, no or display with message.
Args:
msg (str): Message to be printed out.
yes (bool): Indicates whether the default answer is yes or no.
"""
choices = " [Y/n]?" if yes else " [yes/N]" if certain else ... | 42058dd0ed2fb606444233e13551d6d5f11a90a7 | 3,619,962 |
import pyhees.section4_1_Q
def calc_Q_T_H_rad_d_t_i(Q_max_H_d_t_i, L_H_d_t_i):
"""1時間当たりの暖冷房区画iに設置された放熱器の処理暖房負荷
Args:
Q_max_H_d_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの1時間当たりの暖冷房区画𝑖に設置された放熱器の最大暖房出力
L_H_d_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの1時間当たりの暖房負荷(MJ/h)
Returns:
ndarray: 1時間当たりの暖冷房区画iに設置された放熱... | 2f5bb796ee3c002684db4ab6da225e33cd890e65 | 3,619,963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.