content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_insider_activity(ticker: str) -> pd.DataFrame:
"""Get insider activity. [Source: Business Insider]
Parameters
----------
ticker : str
Ticker to get insider activity data from
Returns
-------
df_insider : pd.DataFrame
Get insider activity data
"""
url_market_... | 5,321,800 |
def resolve_dependencies(dependencies):
"""Resolve a set of dependencies to a specific versions or Unspecified.
You can find more for the syntax of Debian dependencies relationships
here https://www.debian.org/doc/debian-policy/ch-relationships.html
Args:
dependencies (str): string with depend... | 5,321,801 |
def sampler(img_target, pose, intrinsics, rng, options):
"""
Given a single image, samples rays
"""
pose_target = pose[:3, :4]
ray_origins, ray_directions = get_ray_bundle(
intrinsics.height, intrinsics.width, intrinsics.focal_length, pose_target
)
coords = jnp.stack(
jnp.m... | 5,321,802 |
def sanitize_gpu_ids(gpus: List[int]) -> List[int]:
"""
Checks that each of the GPUs in the list is actually available.
Raises a MisconfigurationException if any of the GPUs is not available.
Args:
gpus: list of ints corresponding to GPU indices
Returns:
unmodified gpus variable
... | 5,321,803 |
def gauge(name: str, documentation: str, labels: tuple = ()) -> Type[Gauge]:
"""Builds a gauge with configured namespace / subsystem."""
return Gauge(
name,
documentation,
labelnames=labels,
namespace=s.PROMETHEUS_NAMESPACE,
subsystem=s.PROMETHEUS_SUBSYSTEM,
) | 5,321,804 |
def uniform_scaling(weights, prune_ratio, prec_layers, succ_layers):
"""Better prune method
Arguments:
weights (OrderedDict): unpruned model weights
prec_layers (dict): mapping from BN names to preceding convs/linears
succ_layers (dict): mapping from BN names to succeeding convs/linears... | 5,321,805 |
def find_port(master_class_name, masters, output, opts):
"""Finds a triplet of free ports appropriate for the given master."""
try:
master_class = getattr(Master, master_class_name)
except AttributeError:
raise ValueError('Master class %s does not exist' % master_class_name)
used_ports = set()
for m ... | 5,321,806 |
def find_match(good_message, bad_message):
""" Makes the hash of the bad message match that of the good one.
Args:
good_message: The good message we want to match.
bad_message: The bad message we want to make match.
Returns:
Variations of the good and bad messages that have the same hash. """
# Gene... | 5,321,807 |
def threadfunc( url, proxy='', port='', user='', passwd='' ):
"""
threadfunc( url, [proxy='', port='', user='', passwd=''] )
-> None
This function is run by the threads. It increments the global
semaphore, grabs the file, then decrements it and terminates the thread.
"""
global currentthread
curren... | 5,321,808 |
def query_by_date_after(**kwargs):
"""
根据发布的时间查询,之后的记录: 2020-06-03之后,即2020-06-03, 2020-06-04, ......
:param kwargs: {'date': date}
:return:
"""
session = None
try:
date = kwargs['date'].strip() + config.BEGIN_DAY_TIME
session = get_session()
ret = session.query(Second... | 5,321,809 |
def split_data(im_in, dim, squeeze_data=True):
"""
"""
# backwards compat
return split_img_data(src_img=im_in, dim=dim, squeeze_data=squeeze_data) | 5,321,810 |
def write_file_reversed (file_name):
"""
Display the contents of the file name on standard output, in reverse order. File is assumed to exist and
be readable.
Returns: Nothing.
"""
f = open (file_name, 'r')
contents = f.readlines ()
contents.reverse ()
for line in contents:
... | 5,321,811 |
def execute(args):
"""This function invokes the SDR model given
URI inputs of files. It may write log, warning, or error messages to
stdout.
args - a python dictionary with at the following possible entries:
args['workspace_dir'] - a uri to the directory that will write output
... | 5,321,812 |
def user_groups(username, htgroup_fn, strict=True):
"""
Returns a list of group names for the given user
"""
groups = []
for group_name, users in read_groups(htgroup_fn, strict=strict).items():
if username in users:
groups.append(group_name)
return groups | 5,321,813 |
def uffangle(i,j,k,boij,bojk,theta):
"""
Return the UFF parameters for an angle interaction in Gromacs units (degrees, kJ mol^-1 rad^-2).
Not used for the nebterpolator but I decided to keep this code.
i = Element symbol (string)
j = Element symbol for the middle atom (string)
k = Element s... | 5,321,814 |
def img_get_random_patch(img,w,h):
"""Get a random patch of a specific width and height from an image"""
# Note that for this function it is the user's responsibility to ensure
# the image size is big enough. We'll do an asertion to help but...
# Figure out the maximum starting point within the image ... | 5,321,815 |
def list_to_dict(items):
"""Create dictionary from a parenthesized list of attribute/value pairs
:param items: list
:return: dict
"""
if not items:
items = []
# minimal
# dict(zip(items[0::2], items[1::2])
def recursive(item):
"""Check value of parenthesized list and i... | 5,321,816 |
def AVERAGEIF(avg_list, condition_list, condition):
"""Find the average of a list based on a specfic condition in another list.
Parameters
----------
avg_list : list or array
list or array that you will take the average of. Length must match condition_list.
condition_list : list or array
... | 5,321,817 |
def fresnel_ts(n0, n1, theta0, theta1):
"""Compute the "t sub s" fresnel coefficient.
This is associated with transmission of the s-polarized electric field.
Parameters
----------
n0 : `float`
refractive index of the "left" material
n1 : `float`
refractive index of the "right" ... | 5,321,818 |
def main():
"""main function entry point"""
logging.info("Starting")
# calls to more functions | 5,321,819 |
def get_client_id_from_access_token(aws_region, aws_user_pool, token):
""" Pulls the client ID out of an Access Token
"""
claims = get_claims(aws_region, aws_user_pool, token)
if claims.get('token_use') != 'access':
raise ValueError('Not an access token')
return claims.get('client_id') | 5,321,820 |
def bgloop(tag, *iterables, runner=None):
"""Run a loop in a background thread."""
if runner is None:
runner = run_thread
def decorator(func):
if tag in bg_instances and bg_instances[tag].running:
raise RuntimeError("Already running loop")
bg_instances[tag] = Object()
... | 5,321,821 |
def get_metrics_rating(start: AnyStr,
end: AnyStr,
tenant_id: AnyStr,
namespaces: List[AnyStr]) -> List[Dict]:
"""
Get the rating for metrics.
:start (AnyStr) A timestamp, as a string, to represent the starting time.
:end (AnyStr) A ... | 5,321,822 |
def calculate_previous_risk_score_weightings() -> List[float]:
"""
Creates a risk score weighting distribution of size MAX_PREVIOUS_INCIDENTS such that the distribution
is a decreasing linear series that sums to 1. For example, with MAX_PREVIOUS_INCIDENTS == 3,
this function returns [0.5, 0.333..., 0.16... | 5,321,823 |
def warp(x, flo, device):
"""
warp an image/tensor (im2) back to im1, according to the optical flow
x: [B, C, H, W] (im2)
flo: [B, 2, H, W] flow
"""
B, C, H, W = x.size()
# mesh grid
xx = torch.arange(0, W).view(1, -1).repeat(H, 1)
yy = torch.arange(0, H).view(-1, 1).repeat(1, W)
... | 5,321,824 |
def expand_path(filename: str) -> str:
"""
Expands variables (user and environment) in a file name.
:param filename: File name, possibly containing variables.
:return: File name with variables expanded.
"""
return os.path.expandvars(os.path.expanduser(filename)) | 5,321,825 |
def FindVolumeClose(hSearch):
"""Close a search handle opened by FindFirstVolume, typically
after the last volume has been returned.
"""
if kernel32.FindVolumeClose(hSearch) == 0:
return error(x_kernel32, "FindVolumeClose") | 5,321,826 |
def load_loggers(debug, persistent_storage):
"""
Loads all the loggers
:param debug: is Debug enabled
:param persistent_storage: is persistent storage enabled
:return logger: main logger of the application
:return storage_loggers: loggers for the persistent data engine
"""
# Load log le... | 5,321,827 |
def authenticated(method):
"""
Decorate methods with this to require that the Authorization
header is filled.
On failure, raises a 401 or 403 error.
Raises:
:py:class:`tornado.web.HTTPError`
"""
@wraps(method)
async def wrapper(self, *args, **kwargs):
if not self.current_... | 5,321,828 |
def _calculate_f1(conf_matrix):
"""
Calculate classification macro F1 score.
Parameters
----------
conf_matrix : pandas.DataFrame
DataFrame of confusion matrix.
Returns
-------
f1_total : float
Total classification macro F1 score including detection FP and FN.
f1_ta... | 5,321,829 |
def prepare_wiki_content(content, indented=True):
"""
Set wiki page content
"""
if indented:
lines = content.split("\n")
content = " ".join(i + "\n" for i in lines)
return content | 5,321,830 |
def get_user_args():
""" **get_user_args** fetches user arguments from arguments"""
display_name = request.args.get('display_name')
email = request.args.get('email')
email_verified = request.args.get('email_verified')
uid = request.args.get('uid')
cell = request.args.get('cell')
provider_dat... | 5,321,831 |
def calculate_camera_center(P: np.ndarray,
K: np.ndarray,
R_T: np.ndarray) -> np.ndarray:
"""
Returns the camera center matrix for a given projection matrix.
Args:
- P: A numpy array of shape (3, 4) representing the projection matrix
Retur... | 5,321,832 |
def __need_local_verify(ins:VerifyTokenLocal=None):
"""
ins 是否存在,是否 VerifyTokenLocal 对象
:param ins:
:return:
"""
if ins is None:
return False # 为 None, 不需要本地验证
if not isinstance(ins, VerifyTokenLocal): # 有值,但是不是 VerifyTokenLocal 实体,抛出异常
raise WrongLocalVerifyTokenInsErr... | 5,321,833 |
def blaster(counts, database, outname = "output"):
"""
Takes a list of counts in the format [[sequence, total reads, unique],...] then blasts each sequence against the
RNASeqList (fasta formatted). Top match is appended to the end of each member of the count.
:param counts: counts object nested list in ... | 5,321,834 |
def test_constraint_repr(op):
"""Test the repr method of a constraint object.
"""
v = Variable('foo')
c = Constraint(v + 1, op)
assert op in repr(c) | 5,321,835 |
def playsound(soundfile):
"""Play sound through default mixer channel in blocking manner.
This will load the whole sound into memory before playback
"""
pygame.init()
pygame.mixer.init()
sound = pygame.mixer.Sound(soundfile)
clock = pygame.time.Clock()
sound.play()
whil... | 5,321,836 |
def average_spectra(spec_data, t_avg, h_avg, **kwargs):
"""
Function to time-height average Doppler spectra
:param spec_data: list of xarray data sets containing spectra (linear units)
:param t_avg: integer
:param h_avg: integer
:param kwargs: 'verbosity'
:return: list of xarray data sets co... | 5,321,837 |
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(description="Sync Gitlab Issue into MS Project ")
parser.... | 5,321,838 |
def get_db_dot_fmt_strings(db_list, config, query_extension="fasta"):
"""
Return a list of strings that are "{db}.{format}". Where db is the name of the database and format is the extension generated by the search (eg lastx, or tbl). There is a special case for fragmented HMM dbs where we need to add ".dbatch" ... | 5,321,839 |
def colormap(exps, colorby, definedinEM, annotation=None):
"""Generate the self.colors in the format which compatible with matplotlib"""
if definedinEM:
if colorby == "reads":
color_res = []
for i in exps.get_readsnames():
c = exps.get_type(i, "color")
... | 5,321,840 |
def wfs_25d_point(omega, x0, n0, xs, xref=[0, 0, 0], c=None, omalias=None):
"""Point source by 2.5-dimensional WFS.
::
____________ (x0-xs) n0
D(x0,k) = \|j k |xref-x0| ------------- e^(-j k |x0-xs|)
|x0-xs|^(3/2)
"""
x0 = util.asarray_o... | 5,321,841 |
def test_start_params(key, data, dtype):
"""Test starting parameters against statsmodels
"""
order, seasonal_order, intercept = extract_order(key)
y_train, y_train_cudf, _, _, exog_past, exog_past_cudf, *_ \
= get_dataset(data, dtype)
# fillna for reference to match cuML initial estimation... | 5,321,842 |
def load_labels(fn, delimiter=',', id_col=0, label_col=1):
"""
Load ID list with label IDs
e.g. use to load segment label, or synapse label
"""
d = np.genfromtxt(fn, delimiter=delimiter, dtype=int)
label_to_id = {}
id_to_label = {}
for i in range(d.shape[0]):
push_dict(label_to_i... | 5,321,843 |
def write_data():
"""
Write any json data received, to a temporal folder. This data will be, later on, read by other services.
:return:
"""
with open('/tmp/{}'.format(os.environ.get('PAYLOAD_FILENAME', 'data.json')), 'a') as out:
out.write(json.dumps(json.loads(request.data)))
return js... | 5,321,844 |
def flatten_with_joined_string_paths(structure, separator='/'):
"""Replacement for deprecated tf.nest.flatten_with_joined_string_paths."""
return [(separator.join(map(str, path)), item)
for path, item in tree.flatten_with_path(structure)] | 5,321,845 |
def make_non_pad_mask(lengths, xs=None, length_dim=-1):
"""Make mask tensor containing indices of non-padded part.
Args:
lengths (LongTensor or List): Batch of lengths (B,).
xs (Tensor, optional): The reference tensor. If set, masks will be the same shape as this tensor.
length_dim (int... | 5,321,846 |
def get_time_cols(X: pd.DataFrame, labels: bool = False) -> pd.Series:
"""Get time columns."""
X = pd.DataFrame(X)
logger = logging.getLogger(__name__)
is_time = X.dtypes.apply(lambda x: issubclass(x.type, np.datetime64))
n_features = np.sum(is_time)
logger.info("The number of time features is ... | 5,321,847 |
def load(filename):
"""Loads result data from the given json file.
Args:
filename: The name of the input file.
"""
with open(filename, 'r') as fp:
data = json.load(fp)
log.debug(f'Read json from {filename}', data)
if data['version'] == version:
d = data['runinfo']
... | 5,321,848 |
def error(*msgs):
"""
Display ERROR level messages.
:type msgs: list
:param msgs:
"""
output_messages(msgs, tag='ERROR') | 5,321,849 |
def default_browser():
"""
Return the name of the default Browser for this system.
"""
return 'firefox' | 5,321,850 |
def dmp_ground(c, u):
"""
Return a multivariate constant.
Examples
========
>>> from sympy.polys.densebasic import dmp_ground
>>> dmp_ground(3, 5)
[[[[[[3]]]]]]
>>> dmp_ground(1, -1)
1
"""
if not c:
return dmp_zero(u)
for i in range(u + 1):
c = [c]
... | 5,321,851 |
def invoke_permissionError():
"""
Raised when trying to run an operation without the adequate access rights - for example filesystem permissions.
"""
# PASS | 5,321,852 |
def bkb(gp_model, inducing_points, q_bar=1):
"""Update the GP model using BKB algorithm.
Parameters
----------
gp_model: ExactGP
model to update
inducing_points: torch.Tensor
Tensor of dimension [N x d_x]
q_bar: float
float with algorithm parameter.
"""
gp_model.... | 5,321,853 |
def run_duplicate_streams(cmd, timeout=_default_timeout()):
"""
<Purpose>
Provide a function that executes a command in a subprocess and, upon
termination, returns its exit code and the contents of what was printed to
its standard streams.
* Might behave unexpectedly with interactive commands.
... | 5,321,854 |
def splinter_remote_url(request):
"""Remote webdriver url.
:return: URL of remote webdriver.
"""
return request.config.option.splinter_remote_url | 5,321,855 |
def test_mean_rand_arithmetic():
""" Test computation of arithmetic mean in RunningStats, with random values. """
# Set up case.
shape = (10, 10)
data = torch.rand(EMA_THRESHOLD, *shape)
# Perform and check computation.
mean = RunningStats(shape=shape, ema_alpha=EMA_ALPHA)
for i in range(l... | 5,321,856 |
def edit_update_old_value_all_awaiting_apply_or_review(edit):
"""
Updates the OldValue of all pending or approved but not applied edits
that modify the same SourceRow and SourceColumn to the SourceColumn's current value.
:param edit: The reference edit to get the queryset for updating
"""
curre... | 5,321,857 |
def run(*args, **kwargs):
"""Run the external command. See ``subprocess.check_output``."""
# normalize args
if len(args) == 1:
if isinstance(args[0], str):
args = shlex.split(args[0], posix=IS_POSIX)
else:
args = args[0]
if args[0] in ("python", "putup", "pip", "... | 5,321,858 |
def tfresize_image(image, size=(cfg.IMG_W, cfg.IMG_H)):
""" Resize image. """
return tf.image.resize(image, size) | 5,321,859 |
def history():
"""Show history of transactions"""
# Get information about stocks that the transactions
transactions = db.execute(
"SELECT symbol, shares, price_per_share, price, time FROM transactions WHERE user_id = ?",
session["user_id"],
)
return render_template("history.html", ... | 5,321,860 |
def import_ops():
"""Import all CLI modules in the current package"""
for _, name, ispkg in pkgutil.iter_modules([os.path.dirname(__file__)]):
if ispkg:
continue
if name.startswith(_ops_module_prefix):
importlib.import_module('.' + name, __name__) | 5,321,861 |
def serve_static_file(request, filename, root=MEDIA_ROOT, force_content_type=None):
"""
Basic handler for serving up static media files.
Accepts an optional ``root`` (filepath string, defaults to ``MEDIA_ROOT``) parameter.
Accepts an optional ``force_content_type`` (string, guesses if ``None``) par... | 5,321,862 |
def progress(count, total, status="", progress_print: bool = settings.USE_PROGRESS_BAR):
"""进度条"""
bar_len = 30
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = "█" * filled_len + "•" * (bar_len - filled_len)
msg = "%s| %s%s %s \n"... | 5,321,863 |
def crystal_fh2(input_dictionary,phot_in,theta=None,forceratio=0):
"""
:param input_dictionary: as resulting from bragg_calc()
:param phot_in: photon energy in eV
:param theta: incident angle (half of scattering angle) in rad
:return: a dictionary with structure factor
"""
# outfil = in... | 5,321,864 |
def split_list_item_by_taking_words_in_parentheses(item):
"""This function goes through items in a list and creates a new item with only the words inside the parentheses."""
species_pop_name = item.split('(')[0].split(',')
if len(species_pop_name) > 1:
species_pop_name = species_pop_name[1][1:] + sp... | 5,321,865 |
def _set_arxiv_info(paper):
"""
Retrieve paper information from the html.
:param paper: SubmittedPaper object to scrape html information.
:type paper: SubmittedPaper
:return: SubmittedPaper object with html information retrieved.
:rtype: SubmittedPaper
"""
# Remove all the muck that scr... | 5,321,866 |
def fetch_accountTransactions(accountNum):
"""
Function to return all the transaction related to an account number provided as a parameter. This
function assumes that the user has been previously authenticated and that the request is for an
account they own.
Args:
accountNum (int): User's a... | 5,321,867 |
def test_count_primes():
"""Test count_primes function."""
assert primesieve.count_primes(100) == 25
assert primesieve.count_primes(10**6) == 78498
assert primesieve.count_primes(100, 10**6) == 78473
assert primesieve.count_primes(10**10) == 455052511
assert primesieve.count_primes(10**9, 10**10... | 5,321,868 |
def resolve_all(dirs, *paths):
"""
Returns a list of paths created by joining `paths` onto each dir in `dirs` using `os.path.join` and discarding all
join results that do not exist.
:param dirs: A list of dir strings to resolve against
:param paths: Path components to join onto each dir in `dirs` w... | 5,321,869 |
def test_AWSPDS_S2L2AReader(rio, get_object):
"""Test AWSPDS_S2L2AReader."""
rio.open = mock_rasterio_open
get_object.return_value = L2A_TILEJSON
with pytest.raises(InvalidSentinelSceneId):
with S2L1CReader("S2A_tile_20170323_17SNC"):
pass
with S2JP2Reader(SENTINEL_SCENE_L2) as... | 5,321,870 |
def main(items=None, printmd=None, printcal=None,
found=False, filename_template='${collection}/${date}/${id}',
save=None, download=None, requester_pays=False, headers=None, **kwargs):
""" Main function for performing a search """
if items is None:
## if there are no items then pe... | 5,321,871 |
def test_flowsplit_x2_ctd(testdir):
"""Test the Cheng-Todreas Detailed (1986) flow split
correlations against data published in the 1986 paper
Notes
-----
I (M. Atz) could not find any tabulated data, so I visually
assessed the data by hand from Figure 14 of the Cheng-Todreas
paper (1986). ... | 5,321,872 |
def get_utility_flow(heat_utilities, agent):
"""Return the total utility duty of heat utilities for given agent in GJ/hr"""
if isinstance(agent, str): agent = HeatUtility.get_agent(agent)
return sum([i.flow * i.agent.MW for i in heat_utilities if i.agent is agent]) / 1e3 | 5,321,873 |
async def test_flux_with_custom_start_stop_times(hass, legacy_patchable_time):
"""Test the flux with custom start and stop times."""
platform = getattr(hass.components, "test.light")
platform.init()
assert await async_setup_component(
hass, light.DOMAIN, {light.DOMAIN: {CONF_PLATFORM: "test"}}
... | 5,321,874 |
def pad(value, digits, to_right=False):
"""Only use for positive binary numbers given as strings.
Pads to the left by default, or to the right using to_right flag.
Inputs: value -- string of bits
digits -- number of bits in representation
to_right -- Boolean, direction of padding
... | 5,321,875 |
def abort(state: State) -> Process:
"""End of aborted workflow."""
return Abort(state) | 5,321,876 |
def test_link_dirs_at_node():
"""Test areas of patches."""
y = [0, 1, 3, 0, 1, 3, 0, 1, 3]
x = [3, 3, 3, 4, 4, 4, 6, 6, 6]
graph = StructuredQuadGraph((y, x), shape=(3, 3))
assert_array_equal(graph.link_dirs_at_node,
[[-1, -1, 0, 0], [-1, -1, 1, 0], [ 0, -1, 1, 0],
... | 5,321,877 |
def my_todos():
"""This takes the user to the homepage."""
return render_template('index.html') | 5,321,878 |
def setup_directories(
create_report_directory=True,
create_publish_directory=False,
temporary_work_directory=None,
):
"""
Setup a temporary directory, a report directory under it (created if necessary),
and the publish directory (not created by default if necessary).
"""
if not tempora... | 5,321,879 |
def build_network(cfg):
""" Build the network based on the cfg
Args:
cfg (dict): a dict of configuration
Returns:
network (nn.Module)
"""
network = None
pretrained = cfg['model']['pretrained']
kwargs = {
'num_classes': cfg['model']['num_classes'],
}
if cfg['m... | 5,321,880 |
def plot_budget_exploration(solutions_dictionary: dict, institution: Institution, plot_dir: str, break_to_smaller_plots: bool = True):
"""
Plots the weights of the people as a function of B (test budget)
:param solutions_dictionary:
:param institution:
:param plot_dir:
:return:
"""
if no... | 5,321,881 |
def check_band_below_faint_limits(bands, mags):
"""
Check if a star's magnitude for a certain band is below the the
faint limit for that band.
Parameters
----------
bands : str or list
Band(s) to check (e.g. ['SDSSgMag', 'SDSSiMag'].
mags : float or list
Magnitude(s) of the ... | 5,321,882 |
def findNmin_ballot_comparison_rates(alpha, gamma, r1, s1, r2, s2,
reported_margin, N, null_lambda=1):
"""
Compute the smallest sample size for which a ballot comparison
audit, using Kaplan-Markov, with the given statistics could stop
Parameters
----------
... | 5,321,883 |
def patch_item(news_id, patches):
"""Apply the patches to the given news ID. If the categories change, they will be updated
in the related NewsCategoriesMapping. Returns the modified JSON presentation."""
news = News.query.filter_by(NewsID=news_id).first()
result = {}
# Make sure it is a list
i... | 5,321,884 |
def get_sample_prediction(session, regression):
"""Generate and return a sample prediction formatted specifically for table creation.
Args:
session: A SQLalchemy session object
regression: A regression object from four_factor_regression.py
Returns:
A DataOperator object initialized... | 5,321,885 |
def log_variables(y_dataset, variables_to_log):
"""
take the log of given variables
:param variables_to_log: [list of str] variables to take the log of
:param y_dataset: [xr dataset] the y data
:return: [xr dataset] the data logged
"""
for v in variables_to_log:
y_dataset[v].load()
... | 5,321,886 |
def find_place_num(n, m):
"""
"""
if n==1 or m==1:
return 1
else:
return find_place_num(n-1, m) + find_place_num(n, m-1) | 5,321,887 |
def main():
"""
The main method for executing the RecSys approach given by parsing command line arguments
There are 2 main approaches: content, collab.
content approach: The main content method to perform the recommending the movie with content-based approach
collab approach: The main collab method ... | 5,321,888 |
def AddWorkerpoolUpdateArgs(parser, release_track):
"""Set up all the argparse flags for updating a workerpool.
Args:
parser: An argparse.ArgumentParser-like object.
release_track: A base.ReleaseTrack-like object.
Returns:
The parser argument with workerpool flags added in.
"""
return AddWorkerp... | 5,321,889 |
def check_vibes(x0, y0, z0, x1, y1, z1, deadzone=750):
"""
Return boolean if the accelerometer senses vibration.
This module has a range of 1500 while resting.
The default dead zone is 750 because 1500 is quite rare.
Values for this can be measured with min-max.py before coded here.
"""
tot... | 5,321,890 |
def voiced_seg(sig,fs,f0,stepTime):
"""
Voiced segments
sig: Speech signal
fs: Sampling frequency
f0: Pitch contour
stepTime: Step size (in seconds) used to computed the f0 contour.
"""
yp = f0.copy()
yp[yp!=0] = 1
#In case the starting point is F0 and not 0
if yp[0] == 1:
... | 5,321,891 |
def scale_min_max(x, min_in, max_in, min_out, max_out):
"""Scales linearly"""
return np.clip((((max_out - min_out) * (x - min_in)) / (max_in - min_in)) + min_out, min_out, max_out) | 5,321,892 |
def ast_to_z3(inspected_function: dict):
"""
Get the inspected object from the ast visit
and call each mapper from extracted object to its generated Z3 conditions
then, concatenate their results in a single string.
:param inspected_function generated from the AST Visit
:return:
"""
local_variables = [x['declar... | 5,321,893 |
def freight_june_2014():
"""Find the number of freight of the month"""
for i in fetch_data_2013():
if i[1] == "Freight" and i[4] == "June":
num_0 = i[6]
return int(num_0) | 5,321,894 |
def add_license_creation_fields(license_mapping):
"""
Return an updated ``license_mapping`` of license data adding license status
fields needed for license creation.
"""
license_mapping.update(
is_active=False,
reviewed=False,
license_status="NotReviewed",
)
return li... | 5,321,895 |
def filegroup(space, fname):
""" filegroup - Gets file group """
return _filegroup(space, fname) | 5,321,896 |
def convert_examples_to_features(examples, tokenizer, label_list=None, max_seq_length=128):
"""Loads a data file into a list of `InputBatch`s."""
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example)
tokens_b = None
if None:
... | 5,321,897 |
def make_reference_bands_inline(wannier_bands, vasp_bands, efermi=None):
"""
Compare bandstructure results from wannier and vasp.
Takes two input array.bands nodes, stores them if they're not already
stored. Takes the relevant bands from the vasp bandstructure and stores and outputs
them in a node ... | 5,321,898 |
def test_threading(vts_machine, tmpdir, chpy_custom_server2):
"""using rawer fixture vts_machine to allow to control when teardown is
called"""
# recording mode
domain = chpy_custom_server2
vts_machine.setup(basedir=tmpdir)
assert vts_machine.is_recording
# client function
active = BgTas... | 5,321,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.