content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def matyas(x: np.ndarray):
"""
The Matyas function has no local minima except the global one.
The function is usually evaluated on the square xi ∈ [-10, 10], for all i = 1, 2.
Global minimum at (0, 0)
:param x: 2-dimensional
:return: float
"""
assert x.shape[-1] == 2
x1 = x.... | 5,312,600 |
def flatten(array: list):
"""Converts a list of lists into a single list of x elements"""
return [x for row in array for x in row] | 5,312,601 |
def slice_sample(x_start, logpdf_target, D, num_samples=1, burn=1, lag=1,
w=1.0, rng=None):
"""Slice samples from the univariate disitrbution logpdf_target.
Parameters
----------
x_start : float
Initial point.
logpdf_target : function(x)
Evaluates the log pdf of target distr... | 5,312,602 |
def test_in_ipython():
"""Tests are supposed to be run outside an IPython process.
"""
assert not in_ipython() | 5,312,603 |
def format_object_name(meta: Dict, object_name: str) -> str:
"""
Parameters
----------
metas: Dict
Single Granule metadata JSON response from CMR
object_name: str
Name of object (ex. hdf file, xml file)
Returns
----------
str
Object name for granule.
If i... | 5,312,604 |
def ShortName(url):
"""Returns a shortened version of a URL."""
parsed = urlparse.urlparse(url)
path = parsed.path
hostname = parsed.hostname if parsed.hostname else '?.?.?'
if path != '' and path != '/':
last_path = parsed.path.split('/')[-1]
if len(last_path) < 10:
if len(path) < 10:
r... | 5,312,605 |
def select_attachment(pattern, cursor):
"""Prompt the user for the attachment that matches the pattern.
Args:
This function takes the same arguments as the find_attachments
function.
Returns:
A (parentItemID, path) pair, None if no matches were found.
"""
attachments = find... | 5,312,606 |
def keyevent2tuple(event):
"""Convert QKeyEvent instance into a tuple"""
return (event.type(), event.key(), event.modifiers(), event.text(),
event.isAutoRepeat(), event.count()) | 5,312,607 |
def log_git(repo_path: Union[pathlib.Path, str], repo_name: str = None):
"""
Use python logging module to log git information
Args:
repo_path (Union[pathlib.Path, str]): path to repo or file inside repository (repository is recursively searched)
"""
try:
git_info = get_repo_info(rep... | 5,312,608 |
def datetime_to_absolute_validity(d, tzname='Unknown'):
"""Convert ``d`` to its integer representation"""
n = d.strftime("%y %m %d %H %M %S %z").split(" ")
# compute offset
offset = FixedOffset.from_timezone(n[-1], tzname).offset
# one unit is 15 minutes
s = "%02d" % int(floor(offset.seconds / (... | 5,312,609 |
def test_handle_exceptions():
"""Handling of exceptions
The try statement works as follows.
- First, the try clause (the statement(s) between the try and except keywords) is executed.
- If no exception occurs, the except clause is skipped and execution of the try statement
is finished.
- If ... | 5,312,610 |
def backward_committor(basis, weights, in_domain, guess, lag, test_basis=None):
"""Estimate the backward committor using DGA.
Parameters
----------
basis : list of (n_frames[i], n_basis) ndarray of float
Basis for estimating the committor. Must be zero outside of the
domain.
weights... | 5,312,611 |
def get_language_from_request(request, current_page=None):
"""
Return the most obvious language according the request
"""
language = get_language_in_settings(request.REQUEST.get('language', None))
if language is None:
language = getattr(request, 'LANGUAGE_CODE', None)
if language is None... | 5,312,612 |
def process_refund_contract_transaction(contract_transaction_bytes: bytes, delivery_time: int,
funding_value: int, funding_output_script: P2MultiSig_Output, server_keys: ServerKeys,
account_metadata: AccountMetadata, channel_row: ChannelRow) -> Tuple[bytes, bytes, bytes]:
"""
The way a payment c... | 5,312,613 |
def _get_link_url(start_component_revision_dict, end_component_revision_dict):
"""Return link text given a start and end revision. This is used in cases
when revision url is not available."""
url = start_component_revision_dict['url']
if not url:
return None
vcs_viewer = source_mapper.get_vcs_viewer_for_... | 5,312,614 |
def eskapade_bootstrap():
"""Generate Eskapade project structure."""
import argparse
parser = argparse.ArgumentParser('eskapade_bootstrap',
description='Generate Eskapade project structure.',
epilog='Please note, existing files with ... | 5,312,615 |
def blastall_available():
"""Returns True if blastall can be run, False otherwise."""
cmd = str(BLASTALL_DEFAULT)
# Can't use check=True, as blastall without arguments returns 1!
try:
result = subprocess.run(
cmd,
shell=False,
check=False,
stdout=s... | 5,312,616 |
def get_inv_unit(block_index,diff):
"""
given a block index and a 0-indexed layer in that block, returns a unit index.
"""
bottleneck_block_mapping = {1:0,
2:3,
3:7,
4:13}
return bottleneck_block_mapping... | 5,312,617 |
def write_data_dictionary(output_dir):
"""
Write table schema for all tables
model settings
txt_format: output text file name (default data_dict.txt) or empty to suppress txt output
csv_format: output csv file name (default data_dict.tcsvxt) or empty to suppress txt output
schema_t... | 5,312,618 |
def find_image_any_format(filename: str, folder: str) -> Union[str, None]:
"""Takes a filename and returns an image of any of the supported formats."""
for _format in IMAGES:
image = f"{filename}.{_format}"
image_path = IMAGE_SET.path(filename=image, folder=folder)
if os.path.isfile(imag... | 5,312,619 |
def dummy_token(db, dummy_app_link):
"""Return a token for the dummy app/user."""
token_string = TOKEN_PREFIX_OAUTH + generate_token()
token = OAuthToken(access_token=token_string, app_user_link=dummy_app_link, scopes=['read:legacy_api', 'read:user'])
token._plaintext_token = token_string
db.session... | 5,312,620 |
def get_update_packages():
"""
Return a list of dict about package updates
"""
pkgs = []
apt_pkg.init()
# force apt to build its caches in memory for now to make sure
# that there is no race when the pkgcache file gets re-generated
apt_pkg.config.set("Dir::Cache::pkgcache","")
try:... | 5,312,621 |
def verify_bitcoin_message(ctx, message, signature, address):
""" Verifies that an arbitrary message was signed by
the private key corresponding to address
"""
w = ctx.obj['wallet']
verified = w.verify_bitcoin_message(message=message,
signature=signature,
... | 5,312,622 |
def train(list_training_data, list_training_labels, list_test_data,
save_name, learning_rate, load_previous_save=False, auto_threshold_labels=False,
data_clip_range = None, network_size_factor = 1):
"""This is the runner for the brain mask prediction project.
It will either train the CNN ... | 5,312,623 |
def learn_conditional_density(model, xs, ys, ws=None, regularizer=None, val_frac=0.05, step=ss.Adam(a=1.e-4), minibatch=100, patience=20, monitor_every=1, logger=sys.stdout, rng=np.random):
"""
Train model to learn the conditional density p(y|x).
"""
xs = np.asarray(xs, np.float32)
ys = np.asarray(... | 5,312,624 |
def _run_with_output(command, cwd="caffe/"):
""" Runs a comand, and displays the output as it is running.
Args:
command: The command to run.
cwd: Directory to run command in.
Returns:
The command output. """
popen = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=cwd)
lines_iterator = iter(p... | 5,312,625 |
def powspec_highom(fs, mu, s, kp, km, vr, vt, tr):
"""Return the high-frequency behavior of the power spectrum"""
o = 2*pi*fs
Td = np.log((mu + s - vr) / (mu + s - vt)) + tr
Ppp = (kp*exp(-(kp+km)*tr)+km)/(kp+km)
return r0(locals()) * (1.-Ppp*Ppp*np.exp(-2*kp*(Td-tr)))/(1+Ppp*Ppp*np.exp(-2*kp*(Td-tr... | 5,312,626 |
def bigger_price(limit: int, data: list) -> list:
"""
TOP most expensive goods
"""
result_list = []
for i in range(limit):
id_max_price, max_price = find_max_price(data)
result_list.append(data.pop(id_max_price))
return result_list | 5,312,627 |
def makeBlock(data):
"""Applies the block tags to text
"""
global appliedstyle
return "%s%s%s" % (appliedstyle['block'][0], data, appliedstyle['block'][1]) | 5,312,628 |
def by_key(dct, keys, fill_val=None):
""" dictionary on a set of keys, filling missing entries
"""
return dict(zip(keys, values_by_key(dct, keys, fill_val=fill_val))) | 5,312,629 |
def get_vivo_uri():
"""
Find an unused VIVO URI with the specified VIVO_URI_PREFIX
"""
test_uri = VIVO_URI_PREFIX + 'n' + str(random.randint(1, 9999999999))
query = """
SELECT COUNT(?z) WHERE {
<""" + test_uri + """> ?y ?z
}"""
response = vivo_sparql_query(query)
while int(response["resul... | 5,312,630 |
def imbothat(img, el):
"""
Function to mimic MATLAB's imbothat function
Returns bottom-hat of image
Bottom-hat defined to be the difference between input and
the closing of the image
"""
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, el)
return closing - img | 5,312,631 |
def _downsampling_base(
primary_id_strings, storm_times_unix_sec, target_values, target_name,
class_fraction_dict, test_mode=False):
"""Base for `downsample_for_training` and `downsample_for_non_training`.
The procedure is described below.
[1] Find all storm objects in the highest class (e... | 5,312,632 |
def liste_erreur(estimation, sol):
"""
Renvoie une liste d'erreurs pour une estimation et un pas donnés.
Paramètres
----------
estimation : estimation calculée pour la résolution de l'équation différentielle
sol : solution exacte
"""
(x,y) = estimation ... | 5,312,633 |
def get_pods_amount(v1: CoreV1Api, namespace) -> int:
"""
Get an amount of pods.
:param v1: CoreV1Api
:param namespace: namespace
:return: int
"""
pods = v1.list_namespaced_pod(namespace)
return 0 if not pods.items else len(pods.items) | 5,312,634 |
def create_pod(kube_host, kube_port, namespace, pod_name, image_name,
container_port_list, cmd_list, arg_list):
"""Creates a Kubernetes Pod.
Note that it is generally NOT considered a good practice to directly create
Pods. Typically, the recommendation is to create 'Controllers' to create and
ma... | 5,312,635 |
def test04():
"""代理的使用方法,代理网站比如:快代理, mimvp代理"""
url = 'http://www.baidu.com/'
proxies = {
# 免费代理
'http': 'http://117.69.99.82:37862',
# 付费代理格式
# 'http': 'http://user:pwd@111.177.166.47:9999'
}
resp = requests.get(url=url, proxies=proxies)
print(resp.status_code) | 5,312,636 |
def detection(post_id):
""" zipファイル展開 """
file = File.objects.get(pk=post_id)
p_id = post_id % 10
OUT_DIR = os.path.join(
BASE_DIR,
'media',
'images',
str(p_id))
if os.path.exists(OUT_DIR):
shutil.rmtree(OUT_DIR)
os.makedirs(OUT_DIR)
if file.zip.path.s... | 5,312,637 |
def convert_jupyter_to_databricks(
input_filename: str = "nofile", output_filename: str = "nofile"
):
"""Main function to convert jupyter files to databricks python files.
Args:
input_filename (str, optional): input filename .ipynb. Defaults to "nofile".
output_filename (str, optional): out... | 5,312,638 |
def a2_scan(num, *args, wait=None, md=None, **kwargs):
"""Performs a multi-motor scan on a linear trajectory, waiting the specified
amount of time at each step.
Parameters
----------
num : integer
number of steps
``*args`` : {Positioner, Positioner, int}
patterned like (``moto... | 5,312,639 |
def insul_diamond(pixels, bins,
window=10, ignore_diags=2, balanced=True, norm_by_median=True):
"""
Calculates the insulation score of a Hi-C interaction matrix.
Parameters
----------
pixels : pandas.DataFrame
A table of Hi-C interactions. Must follow the Cooler columnar format:
... | 5,312,640 |
def add_frame(dataset):
""" process a dataset consisting of a list of imgs"""
if args.place != 'random':
offset = eval(args.place)
assert type(offset) == tuple and len(offset) == 2
Xs = dataset[0]
newX = []
for (idx, k) in enumerate(Xs):
if args.place == 'random':
... | 5,312,641 |
def floor(x: ndarray) -> ndarray:
"""Returns the floor of the input, element-wise.."""
return _which_np(x).floor(x) | 5,312,642 |
def brightness_classification(ms_image):
"""
Description of brightness_classification
Classifies pixels of image using a simplified version of the method described in:
- http://www.sciencedirect.com/science/article/pii/S0169204617301950
Geometrical rules are not applied.
Args:
... | 5,312,643 |
def build_lights(cfg):
"""Build lights."""
return LIGHTS.build(cfg) | 5,312,644 |
def download_img(url=None, out_file=None):
""" This function downloads an audio file from a url to a file. """
file_ = requests.get(url)
pathlib.Path(out_file).parent.mkdir(parents=True, exist_ok=True)
log.info(f"downloading {url} to {out_file}")
with open(str(out_file), "wb") as f:
f.write(... | 5,312,645 |
def get_obo(force: bool = False) -> Obo:
"""Get miRBase as OBO."""
version = bioversions.get_version(PREFIX)
return Obo(
ontology=PREFIX,
name="miRBase",
iter_terms=get_terms,
iter_terms_kwargs=dict(version=version, force=force),
typedefs=[from_species, has_mature],
... | 5,312,646 |
def create_invitation(secrets) -> dict:
"""
Create an invitation for an existing share.
"""
subscription_id = secrets["SUBSCRIPTIONID"]
resource_group_name = "rg_crosstenant"
account_name = "kmdatashare"
share_name = "publishershare1"
invitation_name = "invitesp"
url = f"https://man... | 5,312,647 |
def useCython():
"""
Switch to using Cython methods if available
"""
global local_linear
if HAS_CYTHON:
import cy_local_linear
local_linear = cy_local_linear | 5,312,648 |
def allocate_lock():
"""Dummy implementation of _thread.allocate_lock()."""
return LockType() | 5,312,649 |
def cropped_thumbnail(instance, field_name, width=None, height=None, scale=None, **kwargs):
"""Cropper"""
thumbnail_options = copy(kwargs)
ratiofield = instance._meta.get_field(field_name)
image = getattr(instance, ratiofield.image_field)
if ratiofield.image_fk_field:
image = getattr(image, ... | 5,312,650 |
def find_roots_quadratic(a: float, b: float, c: float) -> set:
"""Return a set containing the solutions to the equation ax^2 + bx + c = 0.
Each solution is a float.
You may ASSUME that:
- a != 0
- (b * b) - (4 * a * c) >= 0
>>> find_roots_quadratic(1, -15, 56) == {8.0, 7.0}
True
>... | 5,312,651 |
def provision():
"""Create the config files to run the site on the server."""
_setup_dir_variables()
deploy.settings._settings_prompt(env)
env.enable = confirm('Enable site (this activates generated config)?')
env.setup_ssl = confirm('Enable SSL?', default=False)
deploy.provision._create_dir_str... | 5,312,652 |
def reconcile(
column_to_reconcile,
type_id=None,
top_res=1,
property_mapping=None,
reconciliation_endpoint="https://wikidata.reconci.link/en/api",
):
"""
Reconcile a DataFrame column
This is the main function of this package, it takes in a Pandas Series,
that is, a column of a Data... | 5,312,653 |
def test_file_selection_invalid_format(input_file, expected_exception):
"""FileSelectionFolder files can be edited. And of course edited badly. Check whether users are getting proper
feedback """
datafile_path = RESOURCE_PATH / "fileselections" / input_file
with pytest.raises(expected_exception) as e:
... | 5,312,654 |
def dilute_mask(mask, dilute_distance=0):
"""Expand mask regions with given distance
mask: image with dim (H, W, C)
"""
if dilute_distance == 0: # no dilution
return mask
background = np.zeros_like(mask)
# left, right, up, down dilute
l_dilute = background.copy()
r_dilute = back... | 5,312,655 |
def with_expected_arguments(args, env={}):
"""Python script that checks its argv and environment."""
arg_string = ', '.join(['"{}"'.format(arg) for arg in args])
return _SCRIPT_WITH_EXPECTED_ARGUMENTS_TEMPLATE.format(arg_string, env) | 5,312,656 |
def test_pow():
"""Ensures that add works correctly."""
pow_ = (_ ** 2)._
assert pow_(3) == 9 | 5,312,657 |
def createisosurfacemesh(grid, step=None, offset=None, isolevel=None):
"""
This function creates an isosurface from voxel data using the
marching cubes algorithm.
Returns a mesh.
**Parameters:**
`grid` : 3D numpy array containing the voxel data
`step` : voxel sizes in each directi... | 5,312,658 |
def add_sys_recursion_limit_argument(
parser,
short_alias=(),
long_alias=(),
*,
metavar='NUM',
default=sys.getrecursionlimit(),
help='override maximum depth of the Python interpreter stack (default: %(default)d)'
):
"""
add_sys_recursion_limit_argument(par... | 5,312,659 |
def get_property(prop, project):
"""Get certain property from project folder."""
with open(os.path.join(project, '__init__.py')) as f:
result = re.search(r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(prop),
f.read())
return result.group(1) | 5,312,660 |
def get_project_cls_by_name(project_name: str) -> tp.Type[bb.Project]:
"""Look up a BenchBuild project by it's name."""
for project_map_key in bb.project.ProjectRegistry.projects:
if not _is_vara_project(project_map_key):
# currently we only support vara provided projects
continu... | 5,312,661 |
def get_next_non_summer_quarter(request):
"""
Return the Term object for the non-summer quarter after the quarter
refered in the current user sesssion.
"""
return get_next_non_summer_term(get_current_quarter(request)) | 5,312,662 |
def ses_get_ed_status(sg_name):
"""
Return different status code as a dictionary from the SES Element
Descriptor page.
"""
for element_type, descriptor, line in _ses_get_ed_line(sg_name):
# Look for status info
mobj = re.search(r'status:\s*(.+)', line)
if mobj:
st... | 5,312,663 |
def trick_for_mountaincar(state, done, reward, state_):
"""
-1 for each time step, until the goal position of 0.5 is reached.
As with MountainCarContinuous v0, there is no penalty for climbing the left hill,
which upon reached acts as a wall.
state[0] means position: -1.2 ~ 0.6
state[1] veloc... | 5,312,664 |
def process_image(ctx, source_image, dst_filename, width, height=None,
crop=False):
"""Build image from source image, optionally compressing and resizing.
"source_image" is the absolute path of the source in the content directory,
"dst_filename" is the absolute path of the target in the o... | 5,312,665 |
def create_optimizer(
learning_rate, num_train_steps,
warmup_steps=0, warmup_proportion=0, lr_decay_power=1.0,
layerwise_lr_decay_power=-1, n_transformer_layers=None):
"""Creates an optimizer and training op."""
global_step = tf.train.get_or_create_global_step()
increment_global_step_op = t... | 5,312,666 |
def test_fails_incompatible_dtypes(driver, function_store, existing_cube):
"""
Should also cross check w/ seed dataset.
"""
df = pd.DataFrame(
{
"x": [0.0, 1.0, 2.0, 3.0],
"p": [0, 0, 1, 1],
"v3": [10, 11, 12, 13],
"i3": [100, 101, 102, 103],
... | 5,312,667 |
def set_output_stream(out: Any):
"""
Takes in an output stream at sets it as the active output stream.
Parameters
----------
out: Any
Output stream.
"""
has_write_method = getattr(out, "write", False)
if not has_write_method:
raise AttributeError("Output stream does ... | 5,312,668 |
def build_cpo_transition_matrix(val):
""" Builds a TransitionMatrix model expression from a Python value.
If active, this method uses the value cache to return the same CpoExpr for the same value.
Args:
val: Value to convert. Iterator or iterators of integers, or existing TransitionMatrix expressi... | 5,312,669 |
def dict_list(files='rotokas.dic', include_header=False) :
"""
Deprecated: use C{ToolboxData.parse()}
@param files: One or more toolbox files to be processed
@type files: L{string} or L{tuple(string)}
@param include_header: treat header as entry?
@type include_header: boolean
@rtype: it... | 5,312,670 |
def check_preconditions():
""" check if we can find the network interface to monitor """
logger.info("Checking preconditions ...")
find_interface(settings.WIFI_INTERFACES) | 5,312,671 |
def quarter_to_month(str_date):
"""
Transform string representing year and quarter in date.
Parameters
----------
str_date : string
String representing year (YYYY) and quarter (qq) as YYYYQq.
Returns
-------
date : datetime.date
Transformed date.
"""
... | 5,312,672 |
def edge_failure_sampling(failure_scenarios,edge_column):
"""Criteria for selecting failure samples
Parameters
---------
failure_scenarios - Pandas DataFrame of failure scenarios
edge_column - String name of column to select failed edge ID's
Returns
-------
edge_failure_samples - List ... | 5,312,673 |
def do_work():
"""Make sure total CPU time of our process increases"""
t = 0
e = time.clock() + 0.05
if isinstance(psi.arch.arch_type(), psi.arch.ArchAIX):
e += 0.8
while t < e:
for i in range(100):
math.sin(i)
t = time.clock() | 5,312,674 |
def create_and_attach_oauth(user_settings, access_token, token_type):
"""helper function to set the AddonGitHubOauthsettings and link it with
AddonGitHubUserSettings
:param AddonGitHubUserSettings user_settings: User settings record
:param str access_token: OAuth access token
:param str token_type:... | 5,312,675 |
def extract_fp_fn(fname_in, prefix_out):
"""
:param fname_in:
:param prefix_out:
:return:
"""
logger.debug('Starting filtering ...')
t0 = time.time()
mode = 'rb' if fname_in.endswith('bcf') else 'r'
vcf_in = pysam.VariantFile(fname_in, mode)
fp_vcf_out = pysam.VariantFile(prefix_out + '-fp.vcf', ... | 5,312,676 |
def basicClusteringProperties(network, clustering):
"""
compute diversity and related properties for the given clustering
adds results to node attributes
"""
if clustering == 'Cluster':
properties = ['InterclusterFraction', 'ClusterDiversity', 'ClusterBridging', 'ClusterCentrality']
else... | 5,312,677 |
def deserializer(chain) -> Contract:
"""Set crowdsale end strategy."""
# Create finalizer contract
args = []
contract, hash = chain.provider.deploy_contract('TestBytesDeserializer', deploy_args=args)
return contract | 5,312,678 |
def get_payload(fetch_me):
"""Get object from s3, reads underlying http stream, returns bytes.
Args:
fetch_me (dict): Mandatory. Must contain key:
- methodArgs
- Bucket: string. s3 bucket name.
- Key: string. s3 key name.
Returns:
bytes: payload ... | 5,312,679 |
def demo_legacy_grammar():
"""
Check that batch_interpret() is compatible with legacy grammars that use
a lowercase 'sem' feature.
Define 'test.fcfg' to be the following
"""
g = nltk.parse_fcfg("""
% start S
S[sem=<hello>] -> 'hello'
""")
print "Reading grammar: %s" % g... | 5,312,680 |
def train():
"""
Train the tfidf model, requires downloaded data and saves to models/
"""
guesser.train(save=True) | 5,312,681 |
def repl_remove_attributes_from_sgr(matchobj, remove: List[str]) -> str:
"""Addapted remove_sequence_from_text function to be used with regex"""
return remove_attributes_from_sgr(matchobj.group(0), remove) | 5,312,682 |
def _update_data(entity_id, public_key, sso_url, expires_at):
"""
Update/Create the SAMLProviderData for the given entity ID.
Return value:
False if nothing has changed and existing data's "fetched at" timestamp is just updated.
True if a new record was created. (Either this is a new provide... | 5,312,683 |
def my_solver(filename: str) -> str:
"""Dummy solver function.
It does nothing apart from waiting on average 2.5sec
:type filename: object
:Return: the same filename a the input
"""
print("Running my solver")
time.sleep(random.random() * 2)
return filename | 5,312,684 |
def distance_reward_predator(dx, dy, dz):
"""
Returns: Reward = $\exp(-c \cdot d^2)$
"""
distance = np.linalg.norm([dx, dy, dz])
rw = np.exp(-config.reward.coef_distance_reward_predator * distance * distance)
return rw, distance | 5,312,685 |
def load_combo_catalog():
"""Load a union of the user and global catalogs for convenience"""
user_dir = user_data_dir()
global_dir = global_data_dir()
cat_dirs = []
if os.path.isdir(user_dir):
cat_dirs.append(user_dir + '/*.yaml')
cat_dirs.append(user_dir + '/*.yml')
if os.path.... | 5,312,686 |
def _plot_position_error(
dfs_day: Dict[str, pd.core.frame.DataFrame],
dfs_month: Dict[str, pd.core.frame.DataFrame],
figure_dir: PosixPath,
file_vars: Dict[str, Any],
) -> None:
"""Plot horizontal and vertical position error plots
Args:
dfs_day: Dictionary with function type as key... | 5,312,687 |
def flags_t_v_chan(data, chan, targets, freq_range=None, pol=[0, 1], **plot_kwargs):
"""Waterfall plot of flagged data in channels vs time.
Parameters
----------
data : :class:`np.ndarray`
complex, shape(num_times, num_chans, num_pol)
chan : :class:`np.ndarray`
real, shape(num_chans... | 5,312,688 |
def fuzz(file_path, function_name, print_failures, all):
# type: (str, str, bool, bool) -> None
"""
TODO
Args:
file_path:
function_name:
print_failures:
all:
Returns:
"""
if all:
pass # TODO after stub file gen is in
else: # TODO
result... | 5,312,689 |
def canonical_pruning(X, y, sample_weight, initial_mx_formula,
loss_function,
iterations=100,
n_candidates=100,
n_kept_best=0,
learning_rate=0.1,
regularization=10.,
... | 5,312,690 |
def count_arg_nums(method_signature):
"""
Based on the method signature(jni format) to count the arguments number.
:param method_signature: method signature(jni format)
:return: arguments number
"""
arg_signature = re.findall(re.compile(r'\((.*?)\)'), method_signature)[0]
pattern = re.compil... | 5,312,691 |
def ip_to_net_ent_title_ios(ip_addr):
""" Converts an IP address into an OSI Network Entity Title
suitable for use in IS-IS on IOS.
>>> ip_to_net_ent_title_ios(IPAddress("192.168.19.1"))
'49.1921.6801.9001.00'
"""
try:
ip_words = ip_addr.words
except AttributeError:
import n... | 5,312,692 |
def test_notification_listgen_ignores_invalid_conditions(postgres, classification_data, monkeypatch,
operator_data_importer, mocked_config, logger, db_conn,
tmpdir):
"""Test that dirbs-listgen ignores I... | 5,312,693 |
def voiceProgression(key, chordProgression):
"""Voices a chord progression in a specified key using DP.
Follows eighteenth-century voice leading procedures, as guided by the cost
function defined in the `chordCost` and `progressionCost` functions.
Returns a list of four-pitch chords, corresponding to s... | 5,312,694 |
def plot_aerodynamic_coefficients(results, line_color = 'bo-', save_figure = False, save_filename = "Aerodynamic_Coefficients", file_type = ".png"):
"""This plots the aerodynamic coefficients
Assumptions:
None
Source:
None
Inputs:
results.segments.condtions.aerodynamics.
lift_coe... | 5,312,695 |
def run(testnet):
"""Main entry point for the node"""
print(HEADER)
alchemy.main.run(testnet) | 5,312,696 |
def test_tail():
"""
ensure that the tail elements are formated based on the container element.
"""
html = (u'<body>Hi<span style="white-space: pre"> 1 3 </span>'
u' versus 1 3')
assert get_text(html, config) == u'Hi 1 3 versus 1 3' | 5,312,697 |
def start_screener_analysis(
req):
"""start_screener_analysis
Start screener-driven analysis with a simple workflow:
1) Convert FinViz screeners into a list of tickers
and a ``pandas.DataFrames`` from each ticker's html row
2) Build unique list of tickers
3) Pull datasets for each t... | 5,312,698 |
def metade(valor:float, formatado:bool = False):
"""
Retorna a metade do valor que você botou
:param valor: o valor que você quer a metade
:param formatado: Se você quer que o valor estaja formatado para R$
:return: A metade do valor
"""
valor /= 2
if(formatado == True):
valorfo... | 5,312,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.