content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_ExtremelyRandomizedTreesRegressionSklearn_5():
"""Non-trivial test case, including standard deviation."""
n, m, xlen = 150, 600, 10
train_inputs = np.reshape(np.linspace(-xlen / 2, +xlen / 2, n), (n, 1))
train_labels = (train_inputs * 2 + 1).flatten()
train_data = smlb.TabularData(data=tra... | 6,900 |
def confirm_channel(bitcoind, n1, n2):
"""
Confirm that a channel is open between two nodes
"""
assert n1.id() in [p.pub_key for p in n2.list_peers()]
assert n2.id() in [p.pub_key for p in n1.list_peers()]
for i in range(10):
time.sleep(0.5)
if n1.check_channel(n2) and n2.check_c... | 6,901 |
def has_permissions(**perms):
"""A :func:`check` that is added that checks if the member has any of
the permissions necessary.
The permissions passed in must be exactly like the properties shown under
:class:`discord.Permissions`.
Parameters
------------
perms
An argument list of p... | 6,902 |
def reload_configs():
"""
Reloads configuration parameters in stackstorm database from configuration files.
"""
os.system("st2ctl reload --register-configs") | 6,903 |
def extend_params(params, more_params):
"""Extends dictionary with new values.
Args:
params: A dictionary
more_params: A dictionary
Returns:
A dictionary which combines keys from both dictionaries.
Raises:
ValueError: if dicts have the same key.
"""
for yak in more_params:
if yak in p... | 6,904 |
def __compute_libdeps(node):
"""
Computes the direct library dependencies for a given SCons library node.
the attribute that it uses is populated by the Libdeps.py script
"""
if getattr(node.attributes, 'libdeps_exploring', False):
raise DependencyCycleError(node)
env = node.g... | 6,905 |
def image2pptx(argv=sys.argv[1:]):
"""Paste images to PowerPoint.
Args:
--image-path (Path, optional) : Paths to image files. Defaults to ``()``.
--image-dir (Path, optional) : Path to the directory where images are. Defaults to ``None``.
-W/--slide-width (int, optional) : The... | 6,906 |
def _AccumulatorResultToDict(partition, feature, grads, hessians):
"""Converts the inputs to a dictionary since the ordering changes."""
return {(partition[i], feature[i, 0], feature[i, 1]): (grads[i], hessians[i])
for i in range(len(partition))} | 6,907 |
def scale_rotor_pots(rotors, scale_factor=((), None)):
""" scale the pots
"""
# Count numbers
numtors = 0
for rotor in rotors:
numtors += len(rotor)
# Calculate the scaling factors
scale_indcs, factor = scale_factor
nscale = numtors - len(scale_indcs)
if nscale > 0:
... | 6,908 |
async def countdown_minutes(channel, minutes):
"""Send a countdown message (updated each minute)
and another one when the countdown finishes."""
countdown = await channel.send("Time left: %d minutes" % minutes)
edit = asyncio.sleep(0)
while minutes > 0:
sleep = asyncio.sleep(60)
awai... | 6,909 |
def twitter_retrieve_data_streaming_api(ctx, consumer_key, consumer_secret, access_token, access_secret, save_data_mode, tweets_output_folder, area_name,
x_min, y_min, x_max, y_max, languages, max_num_tweets, only_geotagged,
db_username, db... | 6,910 |
async def create(payload: ProductIn):
"""Create new product from sent data."""
product_id = await db.add_product(payload)
apm.capture_message(param_message={'message': 'Product with %s id created.', 'params': product_id})
return ProductOut(**payload.dict(), product_id=product_id) | 6,911 |
def get_glove_info(glove_file_name):
"""Return the number of vectors and dimensions in a file in GloVe format."""
with smart_open(glove_file_name) as f:
num_lines = sum(1 for line in f)
with smart_open(glove_file_name) as f:
num_dims = len(f.readline().split()) - 1
return num_lines, num_... | 6,912 |
def retrieve_database_inputs(db_session: Session) -> (
Dict[str, List[RevenueRate]], Dict[str, MergeAddress], List[Driver]):
"""
Retrieve the static inputs of the model from the database
:param db_session: SQLAlchemy Database connection session
:return: level of service mapped to List of Revenue... | 6,913 |
def _evolve_cx(base_pauli, qctrl, qtrgt):
"""Update P -> CX.P.CX"""
base_pauli._x[:, qtrgt] ^= base_pauli._x[:, qctrl]
base_pauli._z[:, qctrl] ^= base_pauli._z[:, qtrgt]
return base_pauli | 6,914 |
def tp_pixel_num_cal(im, gt):
""" im is the prediction result;
gt is the ground truth labelled by biologists;"""
tp = np.logical_and(im, gt)
tp_pixel_num = tp.sum()
return tp_pixel_num | 6,915 |
def xsg_data(year=None, month=None,
retry_count=3, pause=0.001):
"""
获取限售股解禁数据
Parameters
--------
year:年份,默认为当前年
month:解禁月份,默认为当前月
retry_count : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
... | 6,916 |
def crm_ybquery_v2():
"""
crm根据用户手机号查询subId
:return:
"""
resp = getJsonResponse()
try:
jsonStr = request.data
# 调用业务逻辑
resp = {"message":"","status":200,"timestamp":1534844188679,"body":{"password":"21232f297a57a5a743894a0e4a801fc3","username":"admin"},"result":{"id"... | 6,917 |
def get_split_file_ids_and_pieces(
data_dfs: Dict[str, pd.DataFrame] = None,
xml_and_csv_paths: Dict[str, List[Union[str, Path]]] = None,
splits: Iterable[float] = (0.8, 0.1, 0.1),
seed: int = None,
) -> Tuple[Iterable[Iterable[int]], Iterable[Piece]]:
"""
Get the file_ids that should go in each... | 6,918 |
def calc_full_dist(row, vert, hor, N, site_collection_SM):
"""
Calculates full distance matrix. Called once per row.
INPUTS:
:param vert:
integer, number of included rows
:param hor:
integer, number of columns within radius
:param N:
integer, number of points in row
... | 6,919 |
def traffic_flow_color_scheme():
""" maybe not needed """
pass | 6,920 |
def main(example="A"):
"""
Arguments of this example:
:param str example:
Whether to use example A (requires windows) or B
"""
# Parameters for sen-analysis:
sim_api = setup_fmu(example=example)
calibration_classes, validation_class = setup_calibration_classes(
example=exam... | 6,921 |
def background_upload_do():
"""Handle the upload of a file."""
form = request.form
# Is the upload using Ajax, or a direct POST by the form?
is_ajax = False
if form.get("__ajax", None) == "true":
is_ajax = True
print form.items()
# Target folder for these uploads.
# target = o... | 6,922 |
def write_yml(yml_file, host="127.0.0.1", port=2379):
"""Write a yml file to etcd.
Args:
yml_file (str): Path to the yml file.
host (str): Etcd host.
port (int): Etcd port.
"""
print(f"Writing the yml file {yml_file} in ETCD. Host: {host}. Port: {port}.")
etcd_tool = EtcdToo... | 6,923 |
def catch_list(in_dict, in_key, default, len_highest=1):
"""Handle list and list of list dictionary entries from parameter input files.
Casts list entries of input as same type as default_val.
Assign default values if user does not provide a given input parameter.
Args:
in_dict: Dictionary in ... | 6,924 |
def _load_candidate_scorings (spec, input_dir_candidates, predictor):
"""
Load the msms-based scores for the candidates of the specified msms-spectra.
:param spec: string, identifier of the spectra and candidate list. Currently
we use the inchikey of the structure represented by the spectra.
:... | 6,925 |
def load_dict_data(selected_entities=None, path_to_data_folder=None):
"""Loads up data from .pickle file for the selected entities.
Based on the selected entities, loads data from storage,
into memory, if respective files exists.
Args:
selected_entities: A list of string entity names to be loa... | 6,926 |
def p_mtp3field(p):
"""mtp3field : SIO
| OPC
| DPC
| SLS
| HSIO
| HOPC
| HDPC
| HSLS""" | 6,927 |
def cart_del(request, pk):
""" remove an experiment from the analysis cart and return"""
pk=int(pk) # make integer for lookup within template
analyze_list = request.session.get('analyze_list', [])
if pk in analyze_list:
analyze_list.remove(pk)
request.session['analyze_list'] = analyze_list
... | 6,928 |
def get_block_devices(bdms=None):
"""
@type bdms: list
"""
ret = ""
if bdms:
for bdm in bdms:
ret += "{0}\n".format(bdm.get('DeviceName', '-'))
ebs = bdm.get('Ebs')
if ebs:
ret += " Status: {0}\n".format(ebs.get('Status', '-'))
... | 6,929 |
def outlier_test(model_results, method='bonf', alpha=.05, labels=None,
order=False, cutoff=None):
"""
Outlier Tests for RegressionResults instances.
Parameters
----------
model_results : RegressionResults instance
Linear model results
method : str
- `bonferroni`... | 6,930 |
def imgcat(data, width='auto', height='auto', preserveAspectRatio=False,
inline=True, filename=''):
"""
The width and height are given as a number followed by a unit, or the
word "auto".
N: N character cells.
Npx: N pixels.
N%: N percent of the session's width or h... | 6,931 |
def align_reconstruction(reconstruction, gcp, config):
"""Align a reconstruction with GPS and GCP data."""
res = align_reconstruction_similarity(reconstruction, gcp, config)
if res:
s, A, b = res
apply_similarity(reconstruction, s, A, b) | 6,932 |
def OpenTrade(request, callback, customData = None, extraHeaders = None):
"""
Opens a new outstanding trade. Note that a given item instance may only be in one open trade at a time.
https://docs.microsoft.com/rest/api/playfab/client/trading/opentrade
"""
if not PlayFabSettings._internalSettings.Clie... | 6,933 |
def move(request, content_type_id, obj_id, rank):
"""View to be used in the django admin for changing a :class:`RankedModel`
object's rank. See :func:`admin_link_move_up` and
:func:`admin_link_move_down` for helper functions to incoroprate in your
admin models.
Upon completion this view sends the ... | 6,934 |
def test_second_playback_enforcement(mocker, tmp_path):
"""
Given:
- A mockable test
When:
- The mockable test fails on the second playback
Then:
- Ensure that it exists in the failed_playbooks set
- Ensure that it does not exists in the succeeded_playbooks list
"""
... | 6,935 |
def decode_textfield_ncr(content):
"""
Decodes the contents for CIF textfield from Numeric Character Reference.
:param content: a string with contents
:return: decoded string
"""
import re
def match2str(m):
return chr(int(m.group(1)))
return re.sub('&#(\d+);', match2str, conte... | 6,936 |
def reflect_or_create_tables(options):
"""
returns a dict of classes
make 'em if they don't exist
"tables" is {'wfdisc': mapped table class, ...}
"""
tables = {}
# this list should mirror the command line table options
for table in list(mapfns.keys()) + ['lastid']:
# if option... | 6,937 |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_grpc_interface]
interface_dir=<<path to the parent directory of your Protocol Buffer (pb2) files>>
#<<package_name>>=<<communication_ty... | 6,938 |
def show_server(data):
"""Show server.""" | 6,939 |
def get_workers_count_based_on_cpu_count():
"""
Returns the number of workers based available virtual or physical CPUs on this system.
"""
# Python 2.6+
try:
import multiprocessing
return multiprocessing.cpu_count() * 2 + 1
except (ImportError, NotImplementedError):
pass... | 6,940 |
def addAttributeToChannelList(channellist, channelType, channelName, attributename, attributevalue):
"""Adds channel attributes to the supplied list.
Note: This method only changes the supplied list. It does not communicate with a dmgr.
For example, it creates the following:
'channel_attributes'... | 6,941 |
def test_file_contents(
downloader, filing_type, ticker, before_date, downloaded_filename
):
"""Only run this test when the sample filings folder exists.
This check is required since the distributed python package will
not contain the sample filings test data due to size constraints.
"""
dl, dl... | 6,942 |
def color_print(path: str, color = "white", attrs = []) -> None:
"""Prints colorized text on terminal"""
colored_text = colored(
text = read_warfle_text(path),
color = color,
attrs = attrs
)
print(colored_text)
return None | 6,943 |
def generate_chords(midi_path=None):
"""Generates harmonizing chords and saves them as MIDI.
Input parameters : Midi to harmonize to (Primer Midi), automatically set to Midi from transcription.py
Output = Midifile named "Midifile.chords.midi" in same location
"""
tf.logging.set_verbosity('INFO')
... | 6,944 |
def main(debug):
"""
\b
fetchmesh is a Python library and a command line utility to facilitate
the use of the RIPE Atlas anchoring mesh measurements.
\b
The documentation and the source code are available at
https://github.com/maxmouchet/fetchmesh.
"""
if debug:
logging.basi... | 6,945 |
def _handle_sync_response(response_packet,
commands_waiting_for_response):
"""
"""
# for ACK/synchronous responses we only need to call the registered
# callback.
sequence_number = response_packet.sequence_number
if sequence_number in commands_waiting_for_response:
... | 6,946 |
def create_cluster_spec(parameters_server: str, workers: str) -> tf.train.ClusterSpec:
"""
Creates a ClusterSpec object representing the cluster.
:param parameters_server: comma-separated list of hostname:port pairs to which the parameter servers are assigned
:param workers: comma-separated list of host... | 6,947 |
def save_books_readers(
book: Books,
reader: Readers):
"""Reader's books control and save in data base."""
flag = False
if book.readers is not None:
for i in range(len(book.readers)):
if book.readers[i].id is reader.id:
flag =... | 6,948 |
def ranger_daemon_trigger(raw_args=None):
"""
Pass in raw_args if you wana trigger via this method
eg: ['-zk', 'localhost:2181', '-s', 'myapp', '-host', 'localhost', '-p', '9090', '-e', 'stage', '-hcu', 'http://localhost:9091/healthcheck?pretty=true']
:param raw_args: sys.argv (arguments to the script)
... | 6,949 |
def bq_client(context):
"""
Initialize and return BigQueryClient()
"""
return BigQueryClient(
context.resource_config["dataset"],
) | 6,950 |
def longascnode(x, y, z, u, v, w):
"""Compute value of longitude of ascending node, computed as
the angle between x-axis and the vector n = (-hy,hx,0), where hx, hy, are
respectively, the x and y components of specific angular momentum vector, h.
Args:
x (float): x-component of position
... | 6,951 |
def volumetric_roi_info(atlas_spec):
"""Returns a list of unique ROIs, their labels and centroids"""
if is_image(atlas_spec) and is_image_3D(atlas_spec):
if atlas_spec.__class__ in nibabel.all_image_classes:
atlas_labels = atlas_spec.get_fdata()
else:
atlas_labels = np.a... | 6,952 |
def predictFuture(bo:board, sn:snake, snakes:list, foods:list):
"""
Play forward (futuremoves) turns
Check for enemy moves before calculating route boards
==
bo: boardClass as board
sn: snakeClass as snake
snakes: list[] of snakes
==
return: none
(set board routing... | 6,953 |
def test_return_complex_ref(namespace: TestNamespace) -> None:
"""Test returning a non-trivial reference."""
refH = namespace.addRegister("h")
refL = namespace.addRegister("l")
bitsHL = ConcatenatedBits(refL.bits, refH.bits)
slicedBits = SlicedBits(bitsHL, IntLiteral(0), 8)
namespace.addRetRefer... | 6,954 |
def convert_to_distance(primer_df, tm_opt, gc_opt, gc_clamp_opt=2):
"""
Convert tm, gc%, and gc_clamp to an absolute distance
(tm_dist, gc_dist, gc_clamp_dist)
away from optimum range. This makes it so that all features will need
to be minimized.
"""
primer_df['tm_dist'] = get_distance(
... | 6,955 |
def _tmap_error_detect(tmap: TensorMap) -> TensorMap:
"""Modifies tm so it returns it's mean unless previous tensor from file fails"""
new_tm = copy.deepcopy(tmap)
new_tm.shape = (1,)
new_tm.interpretation = Interpretation.CONTINUOUS
new_tm.channel_map = None
def tff(_: TensorMap, hd5: h5py.Fil... | 6,956 |
def get_filter(DetectorId=None, FilterName=None):
"""
Returns the details of the filter specified by the filter name.
See also: AWS API Documentation
Exceptions
:example: response = client.get_filter(
DetectorId='string',
FilterName='string'
)
:type Detect... | 6,957 |
def generate_dataset(config, ahead=1, data_path=None):
"""
Generates the dataset for training, test and validation
:param ahead: number of steps ahead for prediction
:return:
"""
dataset = config['dataset']
datanames = config['datanames']
datasize = config['datasize']
testsize = co... | 6,958 |
def search(isamAppliance, name, check_mode=False, force=False):
"""
Search UUID for named Web Service connection
"""
ret_obj = get_all(isamAppliance)
return_obj = isamAppliance.create_return_object()
return_obj["warnings"] = ret_obj["warnings"]
for obj in ret_obj['data']:
if obj['na... | 6,959 |
def flask_app(initialize_configuration) -> Flask:
"""
Fixture for making a Flask instance, to be able to access application context manager.
This is not possible with a FlaskClient, and we need the context manager for creating
JWT tokens when is required.
@return: A Flask instance.
"""
fla... | 6,960 |
def test_customize_tag():
"""
>>> d = {'name':'uliweb'}
>>> dirs = [os.path.join(path, 'templates', x) for x in ['a']]
>>> print (template_file('new_tag.html', d, dirs=dirs))
<BLANKLINE>
uliweb
""" | 6,961 |
def http_request(method, url_suffix, params=None, data=None, headers=HEADERS, safe=False):
"""
A wrapper for requests lib to send our requests and handle requests and responses better.
:type method: ``str``
:param method: HTTP method for the request.
:type url_suffix: ``str``
... | 6,962 |
def train(train_loader, model, criterion, average, optimizer, epoch, opt):
"""one epoch training"""
model.train()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
end = time.time()
for i, (images, labels, _) in enumerate(train_loader):
data_time.update... | 6,963 |
def FP(target, prediction):
"""
False positives.
:param target: target value
:param prediction: prediction value
:return:
"""
return ((target == 0).float() * prediction.float().round()).sum() | 6,964 |
def RunJ2ObjC(java, jvm_flags, j2objc, main_class, output_file_path,
j2objc_args, source_paths, files_to_translate):
"""Runs J2ObjC transpiler to translate Java source files to ObjC.
Args:
java: The path of the Java executable.
jvm_flags: A comma-separated list of flags to pass to JVM.
j2... | 6,965 |
def get_angle(A, B, C):
"""
Return the angle at C (in radians) for the triangle formed by A, B, C
a, b, c are lengths
C
/ \
b / \a
/ \
A-------B
c
"""
(col_A, row_A) = A
(col_B, row_B) = B
(col_C, row_C) = C
a = pixel_distance(C, B)
b = pix... | 6,966 |
def single_labels(interesting_class_id):
"""
:param interesting_class_id: integer in range [0,2] to specify class
:return: number of labels for the "interesting_class"
"""
def s_l(y_true, y_pred):
class_id_true = K.argmax(y_true, axis=-1)
accuracy_mask = K.cast(K.equal(class_id_true,... | 6,967 |
def get_iam_policy(client=None, **kwargs):
"""
service_account='string'
"""
service_account=kwargs.pop('service_account')
resp = client.projects().serviceAccounts().getIamPolicy(
resource=service_account).execute()
# TODO(supertom): err handling, check if 'bindings' is correct
if 'bi... | 6,968 |
def get_rdf_lables(obj_list):
"""Get rdf:labels from a given list of objects."""
rdf_labels = []
for obj in obj_list:
rdf_labels.append(obj['rdf:label'])
return rdf_labels | 6,969 |
def _create_model_fn(pipeline_proto, is_chief=True):
"""Creates a callable that build the model.
Args:
pipeline_proto: an instance of pipeline_pb2.Pipeline.
Returns:
model_fn: a callable that takes [features, labels, mode, params] as inputs.
"""
if not isinstance(pipeline_proto, pipeline_pb2.Pipelin... | 6,970 |
def boolean_automatic(meshes, operation, **kwargs):
"""
Automatically pick an engine for booleans based on availability.
Parameters
--------------
meshes : list of Trimesh
Meshes to be booleaned
operation : str
Type of boolean, i.e. 'union', 'intersection', 'difference'
Returns... | 6,971 |
def get_context(work=None):
"""Get a concrete Context object.
Args:
work (gmx.workflow.WorkSpec): runnable work as a valid gmx.workflow.WorkSpec object
Returns:
An object implementing the :py:class:`gmx.context.Context` interface, if possible.
Raises:
gmx.exceptions.ValueError... | 6,972 |
def test_data():
"""Get the `CIFAR-10` test data."""
global _MEAN # pylint: disable=global-statement
_np.random.seed(1)
view = _skdc10.view.OfficialImageClassificationTask()
permutation = _np.random.permutation(range(10000))
if _MEAN is None:
_MEAN = view.train.x.reshape((50000 * 32 * 3... | 6,973 |
def plotHistogram(dataframe,label):
"""
:param dataframe: dataframe object of data
:param label: name of continous target variable
:return: None
"""
plt.hist(dataframe[label], bins=10)
plt.show() | 6,974 |
def normalize_key_combo(key_combo):
"""Normalize key combination to make it easily comparable.
All aliases are converted and modifier orders are fixed to:
Control, Alt, Shift, Meta
Letters will always be read as upper-case.
Due to the native implementation of the key system, Shift pressed in
c... | 6,975 |
def set_device_parameters(request):
"""Set up the class."""
if NAPALM_TEST_MOCK:
driver = request.cls.patched_driver
else:
driver = request.cls.driver
request.cls.device = driver(
NAPALM_HOSTNAME,
NAPALM_USERNAME,
NAPALM_PASSWORD,
timeout=60,
opti... | 6,976 |
def save_esco(G, features: bool):
""" Saving the graph, wither with or without features """
if features:
out_file = esco_out_file_features
enrich_esco_graph_with_features(G)
else:
out_file = esco_out_file
# no idea which labels to use and why... DGL doc could be a bit more expli... | 6,977 |
def shape_to_np(shape, dtype="int"):
"""
Used to convert from a shape object returned by dlib to an np array
"""
return np.array([[shape.part(i).x, shape.part(i).y] for i in range(68)], dtype=dtype) | 6,978 |
def inet_pton(space, address):
""" Converts a human readable IP
address to its packed in_addr representation"""
n = rsocket.inet_pton(rsocket.AF_INET, address)
return space.newstr(n) | 6,979 |
def delete_routing_segmentation_maps_from_source_segment(
self,
segment_id: int,
) -> bool:
"""Delete D-NAT policies for specific source segment
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - vrf
- DELETE
- /v... | 6,980 |
def load_bounding_boxes(dataset_dir):
"""
Load bounding boxes and return a dictionary of file names and corresponding bounding boxes
"""
# Paths
bounding_boxes_path = os.path.join(dataset_dir, 'bounding_boxes.txt')
file_paths_path = os.path.join(dataset_dir, 'images.txt')
# Read bou... | 6,981 |
def _replace_generator_docstring(package_path: Path, replacement: str) -> None:
"""
Replace the generator docstring in the __init__.py module.
(see _parse_generator_docstring for more details).
:param package_path: path to the
:param replacement: the replacement to use.
"""
protocol_name =... | 6,982 |
def _identifier(name):
"""
:param name: string
:return: name in lower case and with '_' instead of '-'
:rtype: string
"""
if name.isidentifier():
return name
return name.lower().lstrip('0123456789. ').replace('-', '_') | 6,983 |
def roots(p):
"""
Return the roots of a polynomial with coefficients given in p.
The values in the rank-1 array `p` are coefficients of a polynomial.
If the length of `p` is n+1 then the polynomial is described by
p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
Parameters
----------
... | 6,984 |
def test_empty_jailer_id(test_microvm_with_ssh):
"""Test that the jailer ID cannot be empty."""
test_microvm = test_microvm_with_ssh
# Set the jailer ID to None.
test_microvm.jailer.jailer_id = ""
# pylint: disable=W0703
try:
test_microvm.spawn()
# If the exception is not throw... | 6,985 |
def download_object_file(bucket_name, source_filename=DEFAULT_MODEL_FILE, dest_filename=DEFAULT_MODEL_FILE):
"""Downloads file from bucket and saves in /tmp dir.
Args:
bucket_name (string): Bucket name.
source_filename (string): Name of file stored in bucket. [default: model.joblib]
... | 6,986 |
def test_unsilence_errors(tmp_path, capfd):
"""Check that HDF5 errors can be muted/unmuted from h5py"""
filename = tmp_path / 'test.h5'
# Unmute HDF5 errors
try:
h5py._errors.unsilence_errors()
_access_not_existing_object(filename)
captured = capfd.readouterr()
... | 6,987 |
def calculate_trade_from_swaps(
swaps: List[AMMSwap],
trade_index: int = 0,
) -> AMMTrade:
"""Given a list of 1 or more AMMSwap (swap) return an AMMTrade (trade).
The trade is calculated using the first swap token (QUOTE) and last swap
token (BASE). Be aware that any token data in between wi... | 6,988 |
def _show_scheduled_roles(account_number: str) -> None:
"""
Show scheduled repos for a given account. For each scheduled show whether scheduled time is elapsed or not.
"""
role_ids = get_all_role_ids_for_account(account_number)
roles = RoleList.from_ids(role_ids)
# filter to show only roles th... | 6,989 |
def tokenize(s):
"""
Tokenize a string.
Args:
s: String to be tokenized.
Returns:
A list of words as the result of tokenization.
"""
#return s.split(" ")
return nltk.word_tokenize(s) | 6,990 |
def evaluate(request):
"""Eval view that shows how many times each entry was tracked"""
# default filter
end_date = datetime.date.today()
start_date = datetime.date(year=end_date.year, month=end_date.month - 1, day=end_date.day)
num_entries = 5
# get custom filter values from form
if reques... | 6,991 |
def plot_af_correlation(vf1, vf2, ax=None, figsize=None):
"""
Create a scatter plot showing the correlation of allele frequency between
two VCF files.
This method will exclude the following sites:
- non-onverlapping sites
- multiallelic sites
- sites with one or more missing ge... | 6,992 |
def significant_pc_test(adata, p_cutoff=0.1, update=True, obsm='X_pca', downsample=50000):
"""
Parameters
----------
adata
p_cutoff
update
obsm
downsample
Returns
-------
"""
pcs = adata.obsm[obsm]
if pcs.shape[0] > downsample:
print(f'Downsample PC matrix ... | 6,993 |
def files_from_output(folder):
"""Get list of result files from output log."""
files = []
with open(path.join(folder, "OUTPUT.out")) as out_file:
for line in tqdm(out_file.readlines(), desc="Read files from output"):
if line.find("+ -o") != -1:
files.append(line.replace(... | 6,994 |
def act_tags_and_rootlabels():
"""
Create a CSV file named swda-actags-and-rootlabels.csv in
which each utterance utt has its own row consisting of just
utt.act_tag, utt.damsl_act_tag(), and utt.trees[0].node
restricting attention to cases in which utt has a single,
perfectly matching tree a... | 6,995 |
def validate_file_name(file_name):
"""Validate file name."""
if not file_name:
raise TypeError("Invalid filename!")
if not isinstance(file_name, unicode):
raise ValueError("Invalid filename!")
if not os.path.isfile(file_name):
raise IOError("File not exist: " + file_name) | 6,996 |
def unique_hurricanes(hurdat):
"""
Returns header info for each unique hurricanes in HURDAT2-formatted text
file hurdat.
"""
#split on returns if hurdat is not a list
if not isinstance(hurdat, list):
hurdat = hurdat.split('\n')
header_rows = [parse_header(
line, line_num
... | 6,997 |
def find_package_data():
"""
Find package_data.
"""
theme_dirs = []
for dir, subdirs, files in os.walk(pjoin('jupyterlab', 'themes')):
slice_len = len('jupyterlab' + os.sep)
theme_dirs.append(pjoin(dir[slice_len:], '*'))
schema_dirs = []
for dir, subdirs, files in os.walk(pj... | 6,998 |
def EnableBE():
""" enables BE workloads, locally
"""
if st.k8sOn:
command = 'kubectl label --overwrite nodes ' + st.node.name + ' hyperpilot.io/be-enabled=true'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, \
stderr=subprocess.PIPE)
_, stderr =... | 6,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.