content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def logger():
"""
Setting upp root and zeep logger
:return: root logger object
"""
root_logger = logging.getLogger()
level = logging.getLevelName(os.environ.get('logLevelDefault', 'INFO'))
root_logger.setLevel(level)
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.... | 29,800 |
def some_function(t):
"""Another silly function."""
return t + " python" | 29,801 |
def build_model(args):
"""
Function: Build a deep learning model
Input:
args: input parameters saved in the type of parser.parse_args
Output:
"""
if args['debug_mode'] is True:
print("BUILDING MODEL......")
model = Sequential()
# Normalize
model.add(Lambda(lambda x:... | 29,802 |
def add_context_for_join_form(context, request):
""" Helper function used by view functions below """
# If the client has already joined a market
if 'trader_id' in request.session:
# If trader is in database
if Trader.objects.filter(id=request.session['trader_id']).exists():
tr... | 29,803 |
def create_list(inner_type_info: CLTypeInfo) -> CLTypeInfoForList:
"""Returns CL type information for a list.
:param CLTypeInfo inner_type_info: Type information pertaining to each element within list.
"""
return CLTypeInfoForList(
typeof=CLType.LIST,
inner_type_info=inner_type_inf... | 29,804 |
def get_baseline(baseline_filename, plugin_filenames=None):
"""
:type baseline_filename: string
:param baseline_filename: name of the baseline file
:type plugin_filenames: tuple
:param plugin_filenames: list of plugins to import
:raises: IOError
:raises: ValueError
"""
if not basel... | 29,805 |
def del_ind_purged(*args):
"""
del_ind_purged(ea)
"""
return _ida_nalt.del_ind_purged(*args) | 29,806 |
def hash_password(password, salthex=None, reps=1000):
"""Compute secure (hash, salthex, reps) triplet for password.
The password string is required. The returned salthex and reps
must be saved and reused to hash any comparison password in
order for it to match the returned hash.
The s... | 29,807 |
def create_scheduled_job_yaml_spec(
descriptor_contents: Dict, executor_config: ExecutorConfig, job_id: str, event: BenchmarkEvent
) -> str:
"""
Creates the YAML spec file corresponding to a descriptor passed as parameter
:param event: event that triggered this execution
:param descriptor_contents: ... | 29,808 |
def isCameraSet(cameraSet):
"""
Returns true if the object is a camera set. This is simply
a wrapper objectType -isa
"""
pass | 29,809 |
def _parse_args():
"""
Parse arguments for the CLI
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--fovs',
type=str,
required=True,
help="Path to the fov data",
)
parser.add_argument(
'--exp',
type=str,
required=True,
... | 29,810 |
def ArgMin(iterable, key=None, default=None, retvalue=False):
"""
iterable >> ArgMin(key=None, default=None, retvalue=True)
Return index of first minimum element (and minimum) in input
(transformed or extracted by key function).
>>> [1, 2, 0, 2] >> ArgMin()
2
>>> ['12', '1', '123'] >> Arg... | 29,811 |
def localize_peaks_monopolar_triangulation(traces, local_peak, contact_locations, neighbours_mask, nbefore, nafter, max_distance_um):
"""
This method is from Julien Boussard see spikeinterface.toolki.postprocessing.unit_localization
"""
peak_locations = np.zeros(local_peak.size, dtype=dtype_localize_by_... | 29,812 |
def test_broadcast_receive_short(feeder):
"""Test the receivement of a normal broadcast message
For this test we receive the GFI1 (Fuel Information 1 (Gaseous)) PGN 65202 (FEB2).
Its length is 8 Bytes. The contained values are bogous of cause.
"""
feeder.accept_all_messages()
feeder.can_messag... | 29,813 |
def format_dict_with_indention(data):
"""Return a formatted string of key value pairs
:param data: a dict
:rtype: a string formatted to key='value'
"""
if data is None:
return None
return jsonutils.dumps(data, indent=4) | 29,814 |
def get_logger(name, info_file, error_file, raw=False):
"""
Get a logger forwarding message to designated places
:param name: The name of the logger
:param info_file: File to log information less severe than error
:param error_file: File to log error and fatal
:param raw: If the output should be... | 29,815 |
def _Rx(c, s):
"""Construct a rotation matrix around X-axis given cos and sin.
The `c` and `s` MUST satisfy c^2 + s^2 = 1 and have the same shape.
See https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations.
"""
o = np.zeros_like(c)
i = np.ones_like(o)
return _tailstack2([[i, o, o],... | 29,816 |
def is_fraud(data):
"""
Identifies if the transaction was fraud
:param data: the data in the transaction
:return: true if the transaction was fraud, false otherwise
"""
return data[1] == 1 | 29,817 |
def EvalBinomialPmf(k, n, p):
"""Evaluates the binomial pmf.
Returns the probabily of k successes in n trials with probability p.
"""
return scipy.stats.binom.pmf(k, n, p) | 29,818 |
def add_prospect(site_id, fname, lname, byear, bmonth, bday, p_type, id_type='all'):
"""
Looks up a prospets prospect_id given their first name (fname) last name (lname), site id (site_id), site (p_type), and birthdate (byear, bmonth, bday).
If no prospect is found, adds the player to the professional_prosp... | 29,819 |
def reformat_icd_code(icd_code: str, is_diag: bool = True) -> str:
"""Put a period in the right place because the MIMIC-III data files exclude them.
Generally, procedure ICD codes have dots after the first two digits, while diagnosis
ICD codes have dots after the first three digits.
Adopted from: https... | 29,820 |
def parse_parent(self):
"""Parse enclosing arglist of self"""
gtor_left = tokens_leftwards(self.begin)
gtor_right = tokens_rightwards(self.end)
enc = Arglist()
enc.append_subarglist_right(self) # _left could have worked equally well
try:
parse_left(enc, gtor_left)
parse_right(... | 29,821 |
def gradthickellipserot(bmp: array,
x: int, y: int, b: int, a: int,
degrot: float, penradius: int,
lumrange: list[int, int],
RGBfactors: list[float, float, float]):
"""Draws an thick ellipse
with a gradient fill
and a defined pen radius
with centerpoin... | 29,822 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the Zigbee Home Automation cover from config entry."""
entities_to_create = hass.data[DATA_ZHA][Platform.COVER]
unsub = async_dispatcher_connect(
ha... | 29,823 |
def dump_annotation(ribo_handle):
"""
Returns annotation of a ribo file in bed format
in string form.
Parameters
----------
ribo_handle : h5py.File
hdf5 handle for the ribo file
Returns
-------
A string that can be output directly as a bed file.
"""
boundaries ... | 29,824 |
def save_stl10(db):
"""Save STL-10 to HDF5 dataset.
Parameters
----------
db : h5py.File
file object for HDF5 dataset.
"""
folder_name = "stl10_binary"
stl10_ds = db.create_dataset("STL10", (10, 32, 32, 3),
maxshape=(None, 32, 32, 3),
... | 29,825 |
def encode_snippets_with_states(snippets, states):
""" Encodes snippets by using previous query states instead.
Inputs:
snippets (list of Snippet): Input snippets.
states (list of dy.Expression): Previous hidden states to use.
TODO: should this by dy.Expression or vector values?
"""... | 29,826 |
def get_openshift_console_url(namespace: str) -> str:
"""Get the openshift console url for a namespace"""
cmd = (
"oc get route -n openshift-console console -o jsonpath='{.spec.host}'",
)
ret = subprocess.run(cmd, shell=True, check=True, capture_output=True)
if ret.returncode != 0:
r... | 29,827 |
def extract_phrases(line, pron):
"""Finds candidate phrases in iambic pentameter from a given line and its
pronunciation."""
# First, extract the stress pattern and scan for iambic pentameter
stress, bound, wordidx = get_stress_and_boundaries(pron)
words, phon_by_word = None, None
for match in ... | 29,828 |
def calculate_ani(blast_results, fragment_length):
"""
Takes the input of the blast results, and calculates the ANI versus the reference genome
"""
sum_identity = float(0)
number_hits = 0 # Number of hits that passed the criteria
total_aligned_bases = 0 # Total of DNA bases that passed the cri... | 29,829 |
def _save_state_from_in_memory_checkpointer(
save_path, experiment_class: experiment.AbstractExperiment):
"""Saves experiment state to a checkpoint."""
logging.info('Saving model.')
for (checkpoint_name,
checkpoint) in pipeline_utils.GLOBAL_CHECKPOINT_DICT.items():
if not checkpoint.history:
... | 29,830 |
def process_line(line: str, conditional_chain: List[str],
fields: Dict[str, str]):
""" Processes a line in the template, i.e. returns the output html code
after evaluating all if statements and filling the fields. Since we
oftentimes are in the middle of several if statements, we need to pa... | 29,831 |
def aasgui(ctx, name):
"""
Display AAS graph from AWR
"""
dblist = get_db_list(name)
for db in dblist:
dbobj = get_db_obj(ctx, db)
dbobj.getAAS((db, ctx.obj["database_list"][db]), GUI=True) | 29,832 |
def get_groundstation_code(gsi):
"""
Translate a GSI code into an EODS domain code.
Domain codes are used in dataset_ids.
It will also translate common gsi aliases if needed.
:type gsi: str
:rtype: str
>>> get_groundstation_code('ASA')
'002'
>>> get_groundstation_code('HOA')
... | 29,833 |
def checkmember(value, values, msg=""):
"""Check value for membership; raise ValueError if fails."""
if value not in values:
raise ValueError(f"ERROR {msg}: {value} should be in {values}") | 29,834 |
def concatenate(*data_frames: DataFrame,
**data_points_or_frames: Union[DataFrame, DataPoint]) \
-> DataFrame:
"""
Concatenate DataFrame's objects or DataPoint's into one DataFrame.
Example:
if one DataFrame represents as:
df1 -> {'a': 1, 'b': 2}
another as:
... | 29,835 |
def mixed_social_welfare(game, mix):
"""Returns the social welfare of a mixed strategy profile"""
return game.expected_payoffs(mix).dot(game.num_role_players) | 29,836 |
def bdh(
tickers, flds=None, start_date=None, end_date='today', adjust=None, **kwargs
) -> pd.DataFrame:
"""
Bloomberg historical data
Args:
tickers: ticker(s)
flds: field(s)
start_date: start date
end_date: end date - default today
adjust: `all`, `dvd`, `nor... | 29,837 |
def isValid(text):
"""
"Play Blackjack"
"""
return bool(re.search(r'\bblackjack\b', text, re.IGNORECASE)) | 29,838 |
def init_app(app):
"""init the flask application
:param app:
:return:
"""
return app | 29,839 |
def bounds(geometry, **kwargs):
"""Computes the bounds (extent) of a geometry.
For each geometry these 4 numbers are returned: min x, min y, max x, max y.
Parameters
----------
geometry : Geometry or array_like
**kwargs
For other keyword-only arguments, see the
`NumPy ufunc doc... | 29,840 |
def test_build_mechfile_entry_ftp_location_with_other_values():
"""Test if mechfile_entry is filled out."""
expected = {
'box': 'bbb',
'box_version': 'ccc',
'name': 'aaa',
'provider': 'vmware',
'windows': False,
'shared_folders': [{'host_path': '.', 'share_name': ... | 29,841 |
def getRidgeEdge(distComponent, maxCoord, direction):
"""
最大値〜最大値-1の範囲で、指定された方向から見て最も遠い点と近い点を見つける。
緑領域からの距離が最大値近辺で、カメラから見て最も遠い点と近い点を見つけるための関数。
これにより、石の天面の中心と底面の中心を求める
"""
# 最大値
maxValue = distComponent[maxCoord]
# 最大値-1以上の点の座標群
ridge = np.array(np.where(distComponent >= maxValue - 1)... | 29,842 |
def map_vL(X, w):
"""
Maps a random sample drawn from vector Langevin with orientation u = [0,...,0,1] to
a sample that follows vector Langevin with orientation w.
"""
assert w.shape[0] == X.shape[0]
#assert np.linalg.norm(w) == 1.
#print('Orientation vector length : ' + str(np.linalg.norm(w)))
d = w.shape[0]
... | 29,843 |
def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1):
"""
Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate
increases linearly between 0 and the initial lr set in the optimizer.
Args:
op... | 29,844 |
def slid_window_avg(a, wi):
""" a simple window-averaging function, centerd on the current point """
# TODO: replace with pandas rolling average. - rth
acopy = np.array(a).copy()
a_smoothed = np.zeros(acopy.shape)
wi_half = wi // 2
wi_other_half = wi - wi_half
for i in range(acopy.shape[0]):... | 29,845 |
def sepg(env, policy,
horizon,
batchsize = 100,
iterations = 1000,
gamma = 0.99,
rmax = 1.,
phimax = 1.,
safety_requirement = 'mi',
delta = 1.,
confidence_schedule = None,
clip_at = 100,
... | 29,846 |
def find_bigrams(textdict, threshold=0.1):
"""
find bigrams in the texts
Input:
- textdict: a dict with {docid: preprocessed_text}
- threshold: for bigrams scores
Returns:
- bigrams: a list of "word1 word2" bigrams
"""
docids = set(textdict.keys())
# to identify bigra... | 29,847 |
def test_thresholdOn():
"""
Testing export movie with different values of mv_thresholdOn
"""
threshold_on_vals = {"foto1": [("a1000", "a400"), ("r50", "r30")],
"raw1": [("a1000", "a400"), ("r60", "r10")],
"sig1": [("a0.75", "a0.65"), ("r60", "r10")]}
... | 29,848 |
def test_not_existing_inv_file(monkeypatch):
"""Test if the inventory path is valid
"""
monkeypatch.setenv('SQ_CONTROLLER_POLLER_CRED', 'dummy_key')
monkeypatch.setenv('SQ_INVENTORY_PATH', 'not_existing')
with pytest.raises(InventorySourceError, match=r'No inventory found at *'):
StaticManag... | 29,849 |
def _rec_filter_to_info(line):
"""Move a DKFZBias filter to the INFO field, for a record.
"""
parts = line.rstrip().split("\t")
move_filters = {"bSeq": "strand", "bPcr": "damage"}
new_filters = []
bias_info = []
for f in parts[6].split(";"):
if f in move_filters:
bias_inf... | 29,850 |
def token_mapper(token):
"""
Token Mapper
"""
try:
if type(token) is m.FieldDeclaration:
try:
parse_field_declaration(token)
except Exception as e:
common.logger.error("Problem in findMethods.py parsing token type: " + str(type(token)) + ". " +str(e))
elif type(token) is m.MethodInvocation:
try... | 29,851 |
def find_files(config, file_to_find, exact_filename=False):
"""finds all the files in config.diag_dir that matches the prefix or will use
the config.files string (split on ,) if present and not use a prefix but a full
file name match.
Example:
files = [my.log], diag_dir = "" => only matches my.l... | 29,852 |
def ast_node_to_source(ast_node: ast.AST) -> str:
"""
Uses astor package to produce source code from ast
Also handles low-level ast functions, such as wrapping in a module if necessary,
and fixing line numbers for modified/extracted ast
Args:
ast_node:
Returns:
"""
# Must be... | 29,853 |
def read(*parts):
"""
returns contents of file
"""
with codecs.open(os.path.join(PROJECT, *parts), "rb", "utf-8") as file:
return file.read() | 29,854 |
def _get_base(*, name: str, schemas: oa_types.Schemas) -> typing.Type:
"""
Retrieve the base class of a schema considering inheritance.
If x-inherits is True, retrieve the parent. If it is a string, verify that the
parent is valid. In either case, the model for that schema is used as the base
inste... | 29,855 |
def stopUuidAdvertise(INTERFACE = 'hci0'):
""" This method gets called to stop the advertisement. """
print("Stopping advertising")
subprocess.call(
"sudo hcitool -i "+ INTERFACE + " cmd 0x08 0x000a 00", shell=True, stdout=DEVNULL
) | 29,856 |
def classNumber(A):
""" Returns the number of transition classes in the matrix A """
cos = 0
if type(A[0][0]) == list:
cos = len(A)
else:
cos = 1
return cos | 29,857 |
def lz4_decompress_c(src, dlen, dst=None):
"""
Decompresses src, a bytearray of compressed data.
The dst argument can be an optional bytearray which will have the output appended.
If it's None, a new bytearray is created.
The output bytearray is returned.
"""
if dst is None:
dst = by... | 29,858 |
def format_coordinates(obj, no_seconds=True, wgs_link=True):
"""Format WGS84 coordinates as HTML.
.. seealso:: https://en.wikipedia.org/wiki/ISO_6709#Order.2C_sign.2C_and_units
"""
def degminsec(dec, hemispheres):
_dec = abs(dec)
degrees = int(floor(_dec))
_dec = (_dec - int(flo... | 29,859 |
def batch_info(test_x, args):
"""display some relevant infos about the dataset format and statistics"""
if args.model_type == "diagnosis":
print(test_x[args.perspectives[0]].shape)
print(torch.min(test_x[args.perspectives[0]]))
print(torch.max(test_x[args.perspectives[0]]))
else:
... | 29,860 |
def _defaultGromacsIncludeDir():
"""Find the location where gromacs #include files are referenced from, by
searching for (1) gromacs environment variables, (2) for the gromacs binary
'pdb2gmx' or 'gmx' in the PATH, or (3) just using the default gromacs
install location, /usr/local/gromacs/share/gromacs/... | 29,861 |
def test_get_starfile_metadata_names():
"""Check if the names returned have the right instance."""
class Config:
"""Class to instantiate the config object."""
shift = True
ctf = True
names = get_starfile_metadata_names(Config)
for name in names:
assert isinstance(name,... | 29,862 |
def delete_keys_on_selected():
"""
deletes set driven keys from selected controllers.
:return: <bool> True for success.
"""
s_ctrls = object_utils.get_selected_node(single=False)
if not s_ctrls:
raise IndexError("[DeleteKeysOnSelectedError] :: No controllers are selected.")
selected_... | 29,863 |
def scan_continuation(curr, prompt_tag, look_for=None, escape=False):
"""
Segment a continuation based on a given continuation-prompt-tag.
The head of the continuation, up to and including the desired continuation
prompt is reversed (in place), and the tail is returned un-altered.
The hint value |l... | 29,864 |
def reloadATSConfigs(conf:Configuration) -> bool:
"""
This function will reload configuration files for the Apache Trafficserver caching HTTP
proxy. It does this by calling ``traffic_ctl config reload`
:param conf: An object representing the configuration of :program:`traffic_ops_ort`
:returns: whether or not the... | 29,865 |
def run_for_duration(func, duration, num_runs, sleep_after_count):
"""
Args:
sleep_after_count (int, int): Tuple of (count to sleep at, time to sleep)
"""
count = 0
start = time.time()
elapsed = 0
if sleep_after_count:
sleep_after_count_random = randomize_sleep_after_count(sl... | 29,866 |
def test_check_package_global():
"""Test for an installed package."""
installed_package = list(pkg_resources.working_set)[0].project_name
assert package.is_installed(installed_package) | 29,867 |
def solar_wcs_frame_mapping(wcs):
"""
This function registers the coordinates frames to their FITS-WCS coordinate
type values in the `astropy.wcs.utils.wcs_to_celestial_frame` registry.
"""
dateobs = wcs.wcs.dateobs if wcs.wcs.dateobs else None
# SunPy Map adds 'heliographic_observer' and 'rsu... | 29,868 |
def toa_error_peak_detection(snr):
"""
Computes the error in time of arrival estimation for a peak detection
algorithm, based on input SNR.
Ported from MATLAB Code
Nicholas O'Donoughue
11 March 2021
:param snr: Signal-to-Noise Ratio [dB]
:return: expected time of arrival ... | 29,869 |
def scrape_random_contracts(data_dir: str, max_contracts=10000,
verbose: bool = True, filtering: bool = True, stop_words: Set[str] = None) -> List[LabeledProvision]:
"""Randomly sample contracts to extract labeled provisions from"""
if verbose:
print('Fetching contracts from'... | 29,870 |
def statCellFraction(gridLimit, gridSpace, valueFile):
"""
Calculate the fractional value of each grid cell, based on the
values stored in valueFile.
:param dict gridLimit: Dictionary of bounds of the grid.
:param dict gridSpace: Resolution of the grid to calculate values.
:param str valueFile: ... | 29,871 |
def tabulate_metaclonotype(
file,
metaclonotype_source_path,
metaclonotype_file,
source_path,
ncpus =1,
max_radius = 36,
write = False,
project_path = "counts"):
"""
Tabulate a set of meta-clonotypes in a single bulk repertoires
Parameters
----------
metaclon... | 29,872 |
def _return_ids_to_df(temp_trip_stack, origin_activity, destination_activity, spts, tpls, trip_id_counter):
"""
Write trip ids into the staypoint and tripleg GeoDataFrames.
Parameters
----------
temp_trip_stack : list
list of dictionary like elements (either pandas series or pyt... | 29,873 |
def relative_url_functions(current_url, course, lesson):
"""Return relative URL generators based on current page.
"""
def lesson_url(lesson, *args, **kwargs):
if not isinstance(lesson, str):
lesson = lesson.slug
if course is not None:
absolute = url_for('course_page'... | 29,874 |
def fix_CompanySize(r):
"""
Fix the CompanySize column
"""
if type(r.CompanySize) != str:
if r.Employment == "Independent contractor, freelancer, or self-employed":
r.CompanySize = "0 to 1 Employees"
elif r.Employment in [
"Not employed, but looking for work",
... | 29,875 |
def write_thermo_yaml(phases=None, species=None, reactions=None,
lateral_interactions=None, units=None,
filename=None, T=300., P=1., newline='\n',
ads_act_method='get_H_act',
yaml_options={'default_flow_style': None, 'indent': 2,
... | 29,876 |
def move_weighted(state: State, nnet: NNet) -> tuple:
"""
Returns are random move with weighted probabilities from the neural network.
:param state: State to evaluate
:param nnet: Neural network used for evaluation
:return: Move as ((origin_row, origin_column),(target_row,target_column)
"""
... | 29,877 |
def build_get301_request(**kwargs: Any) -> HttpRequest:
"""Return 301 status code and redirect to /http/success/200.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :class:`~azure.core.rest.HttpRequest` that you w... | 29,878 |
def error_function_latticeparameters(varying_parameters_values_array,
varying_parameters_keys,
Miller_indices,
allparameters,
absolutespotsindices,
... | 29,879 |
def run_forward_model(z_in):
"""
Run forward model and return approximate measured values
"""
x_dummy[:prm.nn]=z_in
x_dummy[prm.nn:]=prm.compute_velocity(z_in,t0)
x_meas = H_meas.dot(x_dummy)
return x_meas | 29,880 |
def test_pn_file():
"""## test_pn_file
Manual test that
[x] A path to a markdown file can be specified and shown
"""
app = pn.Column(test_pn_file.__doc__, pnx.Markdown(path=TEST_MD_FILE, name="test"),)
app.servable("test_pn_file") | 29,881 |
def optimize(name: str, circuit: cirq.Circuit) -> cirq.Circuit:
"""Applies sycamore circuit decompositions/optimizations.
Args:
name: the name of the circuit for printing messages
circuit: the circuit to optimize_for_sycamore
"""
print(f'optimizing: {name}', flush=True)
start = time... | 29,882 |
def download_sbr(destination=None):
"""Download an example of SBR+ Array and return the def path.
Examples files are downloaded to a persistent cache to avoid
re-downloading the same file twice.
Parameters
----------
destination : str, optional
Path where files will be downloaded. Opti... | 29,883 |
def isvalid_sequence(
level: str, time_series: Tuple[Union[HSScoring, CollegeScoring]]
) -> bool:
"""Checks if entire sequence is valid.
Args:
level: 'high school' or 'college' level for sequence analysis.
time_series: Tuple of sorted match time_series events.
Raises:
Value... | 29,884 |
def create_backend_app(): # pragma: no cover
"""Returns WSGI app for backend."""
routes = handlers.get_backend_routes() + swarming.get_backend_routes()
app = webapp2.WSGIApplication(routes, debug=utils.is_local_dev_server())
gae_ts_mon.initialize(app, cron_module='backend')
gae_ts_mon.register_global_metrics... | 29,885 |
def non_linear_relationships():
"""Plot logarithmic and exponential data along with correlation coefficients."""
# make subplots
fig, axes = plt.subplots(1, 2, figsize=(12, 3))
# plot logarithmic
log_x = np.linspace(0.01, 10)
log_y = np.log(log_x)
axes[0].scatter(log_x, log_y)
axes[0].s... | 29,886 |
def label_samples(annotation, atlas, atlas_info=None, tolerance=2):
"""
Matches all microarray samples in `annotation` to parcels in `atlas`
Attempts to place each sample provided in `annotation` into a parcel in
`atlas`, where the latter is a 3D niimg-like object that contains parcels
each idnetif... | 29,887 |
def main():
"""Encrypt payload."""
print()
print("====== Test encode -----------------------------------------")
temp = 25.06
humi = 50.55
print("Temperature:", temp, "Humidity:", humi)
print()
data = bytes(bytearray.fromhex('2302CA090303BF13')) # HA BLE data (not encrypted)
count_i... | 29,888 |
def group_by(x, group_by_fields='Event', return_group_indices=False):
"""
Splits x into LIST of arrays, each array with rows that have same
group_by_fields values.
Gotchas:
Assumes x is sorted by group_by_fields (works in either order, reversed
or not)
Does NOT put in empty lists... | 29,889 |
def unlock_file(fd):
"""unlock file. """
try:
fcntl.flock(fd, fcntl.LOCK_UN)
return (True, 0)
except IOError, ex_value:
return (False, ex_value[0]) | 29,890 |
def DsseTrad(nodes_num, measurements, Gmatrix, Bmatrix, Yabs_matrix, Yphase_matrix):
"""
Traditional state estimator
It performs state estimation using rectangular node voltage state variables
and it is customized to work without PMU measurements
@param nodes_num: number of nodes of the grid
@p... | 29,891 |
def _get_specs(layout, surfs, array_name, cbar_range, nvals=256):
"""Get array specifications.
Parameters
----------
layout : ndarray, shape = (n_rows, n_cols)
Array of surface keys in `surfs`. Specifies how window is arranged.
surfs : dict[str, BSPolyData]
Dictionary of surfaces.
... | 29,892 |
def get_pool_data(index, val, field):
"""
Return val for volume based on index.
Parameters
----------
index: str
base field name.
val: str
base field value.
field: str
requested field value.
Returns
-------
str: the requested value, None if absent.
... | 29,893 |
def test_modular_apicast(set_gateway_image, api_client):
"""
Sends a request.
Asserts that the header added by the example policy is present.
"""
response = get(api_client(), "/")
assert response.status_code == 200
assert 'X-Example-Policy-Response' in response.headers | 29,894 |
def upper_camel_to_lower_camel(upper_camel: str) -> str:
"""convert upper camel case to lower camel case
Example:
CamelCase -> camelCase
:param upper_camel:
:return:
"""
return upper_camel[0].lower() + upper_camel[1:] | 29,895 |
def test_custom_link_marshaler():
"""Test that json marshaler use custom marshaler to marshal a link.
1. Create a sub-class of JSONMarshaler with redefined create_link_marshaler factory.
2. Create json marshaler from the sub-class.
3. Marshal a link.
4. Check that custom marshaler is used to marsha... | 29,896 |
def get(isamAppliance, cert_dbase_id, check_mode=False, force=False):
"""
Get details of a certificate database
"""
return isamAppliance.invoke_get("Retrieving all current certificate database names",
"/isam/ssl_certificates/{0}/details".format(cert_dbase_id)) | 29,897 |
def read_environment_file(envfile=None):
"""
Read a .env file into os.environ.
If not given a path to a envfile path, does filthy magic stack backtracking
to find manage.py and then find the envfile.
"""
if envfile is None:
frame = sys._getframe()
envfile = os.path.join(os.path.... | 29,898 |
def model_check(func):
"""Checks if the model is referenced as a valid model. If the model is
valid, the API will be ready to find the correct endpoint for the given
model.
:param func: The function to decorate
:type func: function
"""
def wrapper(*args, **kwargs):
model = None
... | 29,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.