content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_pmf_hist_normalization():
"""Test that output data behaves like a PMF."""
x, h, w = utils.pmf_hist(a_norm)
nose.tools.assert_almost_equal(sum(h), 1)
nose.tools.assert_less_equal(h.max(), 1) | 5,320,200 |
def hough_line (im, nr=512, na=512, yc=None, xc=None, threshold=10,\
disp=False, dispacc=False):
"""
Perform the Hough transform for lines of the image 'im'.
This routine performs a straight-line Hough transform of the image 'im',
which should normally contain output from an edge detect... | 5,320,201 |
def database_session():
"""This fixture prepares database and fixture records."""
yield from DatabaseForTest.database_session() | 5,320,202 |
def build_response(session_attributes, speechlet_response):
"""builds resopnse"""
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
} | 5,320,203 |
def insertion_sort(L):
"""Implementation of insertion sort."""
n = len(L)
if n < 2:
return L
for i in range(1, n):
tmp = L[i]
j = i
while j > 0 and tmp < L[j - 1]:
L[j] = L[j - 1]
j -= 1
L[j] = tmp | 5,320,204 |
def pool_labels_must_contain_all_the_volume_request_topology_labels(create_request):
"""pool labels must contain all the volume request topology labels."""
assert (
common_labels(
create_request[CREATE_REQUEST_KEY]["topology"]["pool_topology"]["labelled"][
"inclusion"
... | 5,320,205 |
def test_random_state():
"""Tests the initialization with a fixed random state in Decision Tree."""
clf1 = DecisionTree(random_state=7)
clf2 = DecisionTree(random_state=7)
data1 = clf1.data_points
data2 = clf2.data_points
assert equal(data1, data2).all() | 5,320,206 |
def get_bgp_peer():
"""
collects local and bgp neighbor ip along with device name in below format
{
'local_addr1':['neighbor_device1_name', 'neighbor_device1_ip'],
'local_addr2':['neighbor_device2_name', 'neighbor_device2_ip']
}
"""
config_db = ConfigDBConnector()
config_db.connec... | 5,320,207 |
def _do_nothing(string):
"""Makes the ConfigParser case sensitive."""
return string | 5,320,208 |
def show_game(game_id):
"""Return the rendered template for a game with game_id.
Args:
game_id(int)
Returns: Rendered html template
"""
game = session.query(Games).filter_by(id=game_id).one()
date = game.release_date.date().strftime("%d, %B %Y")
category = session.query(Category).... | 5,320,209 |
def is_symmetric(mat):
"""Return whether a sy.Matrix is symmetric."""
n, nc = mat.shape
return nc == n and all(mat[j,i] == mat[i,j] for i in range(n) for j in range(i+1, n)) | 5,320,210 |
def download_ftp_text(file_url: str) -> str:
"""Download FTP file to memory return it as string (ASCII encoding is
assumed).
:param file_url: file URL which must start with ftp://
"""
with open_ftp_file(file_url) as fp:
return fp.read().decode('ASCII') | 5,320,211 |
def choice_likeFestival(user_id):
"""
๊ฐ๊ณ ์ถ์ ์ถ์ ์ ํ
"""
print('choice_likeFestival')
for row in userInfoDB.rows:
if row[0].value == user_id: # ๋ฐฉ๋ฌธํ๋ ์ ์ด ์์๋ ์ฌ๋, ๋ฆฌ์คํธ๋ก ์ ์ฅ๋๋ฏ๋ก ๋ฆฌ์คํธ๋ก ์ ๊ทผ
userRow = row[0].row()
index = contentListCode.index(stateDB.loc[user_id, 'contentCode'])
... | 5,320,212 |
def least_square_regression(x, y, xlabel = "x", ylabel = "y", prefix="", suffix=""):
"""
Perform least square regression to find the best fit line and returns the slope of the line.
**Parameters**
x : List of values along x axis.
y : List of values along y axis.
"""
X = np.asa... | 5,320,213 |
def distclean():
"""Cleans up project environment with removing all non-repository files"""
session.clean()
Repository.distclean() | 5,320,214 |
def build_dict(*param_dicts, **param_dict):
"""
Create a merged dictionary from the supplied dictionaries and keyword parameters.
"""
merged_param_dict = param_dict.copy()
for d in param_dicts:
if d is not None:
# log.info("param_dicts %r"%(d,))
merged_param_dict.upda... | 5,320,215 |
def calc_volume(all_vertices, element):
"""Calculate the volume for the given element based on type.
Returns length between points (2D) and volume within points (3D)."""
vertices = all_vertices[element.vertice_ids]
# 1D case with lines (volume) and points (area)
if element.element_type == ElementTy... | 5,320,216 |
def Mode(hist):
"""Returns the value with the highest frequency.
hist: Hist object
returns: value from Hist
"""
p, x = max([(p, x) for x, p in hist.Items()])
return x | 5,320,217 |
def get_img_space(wsp, img):
"""
Find out what image space an image is in
Note that this only compares the voxel->world transformation matrix to the
reference image for each space. It is quite possible for two images to be in
the same space but not be registered to one another. In this case,
... | 5,320,218 |
def get_dir(algorithm, mode):
"""
Used to determine the plotting folder
Parameters
----------
algorithm: String
The name of the current ANC algorithm running
mode: String
The MODE (precorded or anc) the server is currently running
Returns
-------
path : Path
... | 5,320,219 |
def get_comma_delimiter(include_a_space=True):
"""Return the comma delimiter appropriate for the current language (Arabic or English).
When include_a_space is True (the default), the delimiter includes a space to make the returned
value easy to use with join() when constructing a list.
"""
delimite... | 5,320,220 |
def most_frequent(text):
""" Returns the letter frequencies of the given text"""
letters = tuple(text)
freqs = {}
for let in letters:
freqs.setdefault(let, 0)
freqs[let] += 1
rankedpairs = []
for key, val in freqs.items():
rankedpairs += [(val, key)]
rankedpairs = sor... | 5,320,221 |
def str_to_bool(string):
"""Used as a type in argparse so that we get back a proper
bool instead of always True
"""
return string.lower() in ("y", "yes", "1", "true") | 5,320,222 |
def generateAggProfiles(year, interval='M'):
"""
This function generates the aggregate input data required for building the experimental model
"""
#generate folder structure and file names
feather_path= {}
csv_path= {}
for i in ['pp', 'aggpp_' + interval, 'a' + interval + 'd', '... | 5,320,223 |
def _run_canned_tests(env,osenv):
"""Run the tests from the tests subdirectory"""
retval = 0 # success
env['test_dir'] = env.escape_string(mbuild.join(env['src_dir'],'tests'))
cmd = "%(python)s %(test_dir)s/run-cmd.py --build-dir %(build_dir)s/examples "
dirs = ['tests-base', 'tests-knc', ... | 5,320,224 |
def new(nbits, prefix=b"", suffix=b"", initial_value=1, little_endian=False, allow_wraparound=False):
"""Create a stateful counter block function suitable for CTR encryption modes.
Each call to the function returns the next counter block.
Each counter block is made up by three parts:
+------+---------... | 5,320,225 |
def format_json_file(file_path):
"""
Formats a json file with 4 space indents.
Args:
file_path (str):
Returns:
"""
if file_path.endswith('.json'):
data = read_json_from_file(file_path)
write_json_to_file(file_path, data) | 5,320,226 |
def setup_webui():
"""Provisions webui services in all nodes defined in webui role."""
if env.roledefs['webui']:
execute("setup_webui_node", env.host_string) | 5,320,227 |
def scoreNF(shelf: Shelf, item: Item, self=None) -> Tuple[int, Shelf, bool]:
""" Next Fit """
if self.shelves:
open_shelf = self.shelves[-1]
if self._item_fits_shelf(item, open_shelf):
return (0, open_shelf, False)
if self.rotation and self._item_fits_shelf(item, open_shelf, ... | 5,320,228 |
def parse_str_to_date(date_str):
"""
Recieves a Date String (e.g. 2019-10-09)
and returns a datetime object
"""
#T22:25:00-03:00
if type(date_str) != str:
return None
return dt.datetime(
int(date_str[0:4]), #Year
int(date_str[5:7]), #Month
int(date_str[8:10])... | 5,320,229 |
def size(imageOrFilter) :
"""Return the size of an image, or of the output image of a filter
This method take care of updating the needed informations
"""
# we don't need the entire output, only its size
imageOrFilter.UpdateOutputInformation()
img = image(imageOrFilter)
return img.GetLargestPossibleReg... | 5,320,230 |
def fetch_eigenv(odb_name, step_name, n_eigen):
"""
Get eigenvalues.
Return the eigenvalues of a perturbation buckling analysis from an abaqus database.
Parameters
----------
odb_name : class
Abaqus model containing the eigenvalues
step_name : string
Name of the ... | 5,320,231 |
def _not_exhausted(last_fetched):
"""Check if the last fetched tasks were the last available."""
return len(last_fetched) == 100 | 5,320,232 |
def files_by_extension(root, extensions):
"""
Returns a list of files that match the extensions given after crawling the root directory
"""
assert(os.path.isdir(root))
file_list = []
for roots, _, files in os.walk(root):
for f in files:
ext = os.path.splitext(f)[1][1:].strip().lower()
if ext in extensio... | 5,320,233 |
def playonyt(topic: str, use_api: bool = False, open_video: bool = True) -> str:
"""Play a YouTube Video"""
if use_api:
response = requests.get(
f"https://pywhatkit.herokuapp.com/playonyt?topic={topic}"
)
if open_video:
web.open(response.content.decode("ascii"))
... | 5,320,234 |
def get_data(filename: str = "test", roi: str = []) -> list:
"""
Return data (pixel values) from an ROI in an image for every extension.
NOT FINISHED!
Args:
filename: image filename.
roi: Region-Of-Interest.
Returns:
list of pixel values.
"""
filename = azcam.utils.... | 5,320,235 |
def execute_select_dataframe_columns(dataframe, select_dataframe_columns):
"""
Filter dataframe using the provided columns
Args:
dataframe (array[str]): Array of columns names
select_dataframe_columns (pandas.Dataframe): Dataframe
Returns:
pandas.Dataframe: Dataframe filtered
... | 5,320,236 |
def plot_median_freq_evol(time_signal, signal, time_median_freq, median_freq, activations_begin,
activations_end, sample_rate, file_name=None):
"""
-----
Brief
-----
Graphical representation of the EMG median power frequency evolution time series.
-----------
Descr... | 5,320,237 |
def extant_file(x):
"""
'Type' for argparse - checks that file exists but does not open.
"""
if not os.path.exists(x):
# Argparse uses the ArgumentTypeError to give a rejection message like:
# error: argument input: x does not exist
raise argparse.ArgumentTypeError("{0} does not ... | 5,320,238 |
def SetMonotime(func):
"""Older tornado doesn't have monotime(); stay compatible."""
if hasattr(tornado.util, 'monotime_impl'):
tornado.util.monotime_impl = func
else:
time.time = func | 5,320,239 |
def test_from_format(schema, to_fn, buf_cls):
"""
Test that check_types-guarded function reads data from source serialization
format.
"""
@pa.check_types
def fn(df: pa.typing.DataFrame[schema]):
return df
for df, invalid in [
(mock_dataframe(), False),
(invalid_inpu... | 5,320,240 |
def has_oxidation_states(comp):
"""Check if a composition object has oxidation states for each element
Args:
comp (Composition): Composition to check
Returns:
(boolean) Whether this composition object contains oxidation states
"""
for el in comp.elements:
if not hasattr(el, ... | 5,320,241 |
def check_fsig_int(quad_int, cryst_ptgrp, sigma, *args):
"""
For specific sigma rotations, a function of m, U, V, W (fsig) is computed.
The ratio of fsig and sigma should be a divisor of kmax. This
condition is checked and those integer quadruples that satisfy
this condition are returned
Parame... | 5,320,242 |
def test_cqv_dataframe_multithread_3_threads():
"""Tests cqv function for dataframe when num_threads is multi."""
data = pd.DataFrame(
{
"col-1": pd.Series([0.2, 0.5, 1.1, 1.4, 1.8, 2.3, 2.5, 2.7, 3.5]),
"col-2": pd.Series([5.4, 5.4, 5.7, 5.8, 5.9, 6.0, 6.6, 7.1, 7.9]),
}... | 5,320,243 |
def printc(*s, color="grey", hl=None, bg=None, file=sys.stderr):
"""
Prints some text with some color, using Terminal escape sequences
>>> printc("Hello world", color="blue")
\033[1;34mHello world\033[1;m
>>> printc("Hello world", color="blue", hl=True)
\033[1;44mHello world\033[1;m
"""
... | 5,320,244 |
def exit_flow(exit_inputs: Tensor) -> Tensor:
"""
Exit flow
Implements the second of the three broad parts of the model. Includes the optional fully-connected layers,
and the logistic regression segment of the model.
:param exit_inputs: Tensor output generated by the Middle Flow segment, having shap... | 5,320,245 |
def test_encode_tagset_values(values, expected):
"""Test that we can properly encode data into the expected format"""
header = encode_tagset_values(values)
assert expected == header
# Ensure what we generate also parses correctly
assert values == decode_tagset_string(header) | 5,320,246 |
def check_Latitude(observation):
"""
Validates that observation contains valid age value
Returns:
- assertion value: True if age is valid, False otherwise
- error message: empty if age is valid, False otherwise
"""
value = observation.get("Latitude")
... | 5,320,247 |
def read_and_reshape_data(filename):
"""
Read in the Snake grid output and reshape it into a 3d array of
(ncycles, ncells, ncols).
Parameters
----------
None
Returns
-------
sgrid: (ncycles, ncells, ncols) array of str
The reshaped grid output from Snake. The columns are as... | 5,320,248 |
def chart(start: str, stop: str):
"""ะัะฐัะธะบ ั ะดะฐะฝะฝัะผะธ."""
return flask.render_template('chart.html', start=start, stop=stop) | 5,320,249 |
def test_atomic_g_year_month_max_exclusive_2_nistxml_sv_iv_atomic_g_year_month_max_exclusive_3_4(mode, save_output, output_format):
"""
Type atomic/gYearMonth is restricted by facet maxExclusive with value
1971-05.
"""
assert_bindings(
schema="nistData/atomic/gYearMonth/Schema+Instance/NISTS... | 5,320,250 |
def toa_error_cross_corr(snr, bandwidth, pulse_len, bandwidth_rms=None):
"""
Computes the timing error for a Cross-Correlation time of arrival
estimator, given the input signal's bandwidth, pulse length, and RMS
bandwidth.
Ported from MATLAB Code
Nicholas O'Donoughue
11 March 2021
... | 5,320,251 |
def search_projects():
"""
Search for projects
- When given the name of a known project (*modulo* normalization), redirect
to that project's page
- When given an unknown project name, search for all known project names
that have it as a prefix
- When given a search term with a ``*`` i... | 5,320,252 |
def parse_opt_int(s: Optional[str]) -> Optional[int]:
"""
parse_opt_int(s: Optional[str]) -> Optional[int]
If s is a string, parse it for an integer value (raising a ValueError if
it cannot be parsed correctly.)
If s is None, return None.
Otherwise, raise a TypeError.
"""
if s is None:
... | 5,320,253 |
def get_record_parser(config, is_test=False):
"""
Get the tfrecords sample parser.
:param config: Contains the configurations to be used.
:param is_test: Indicate if the data_type is test.
:return: The parser method.
"""
def parse(example):
"""
Extract features from a single ... | 5,320,254 |
def get_model_loader(namespace: Optional[str] = None) -> ModelConfigLoader[SegmentationModelBase]:
"""
Returns a ModelConfigLoader for segmentation models, with the given non-default namespace (if not None)
to search under.
"""
return ModelConfigLoader[SegmentationModelBase](model_configs_namespace=... | 5,320,255 |
def beam_search(mat: np.ndarray, chars: str, beam_width: int = 25, lm: Optional[LanguageModel] = None) -> str:
"""Beam search decoder.
See the paper of Hwang et al. and the paper of Graves et al.
Args:
mat: Output of neural network of shape TxC.
chars: The set of characters the neural netw... | 5,320,256 |
def load_mmd():
"""Loads libMultiMarkdown for usage"""
global _MMD_LIB
global _LIB_LOCATION
try:
lib_file = 'libMultiMarkdown' + SHLIB_EXT[platform.system()]
_LIB_LOCATION = os.path.abspath(os.path.join(DEFAULT_LIBRARY_DIR, lib_file))
if not os.path.isfile(_LIB_LOCATION):
... | 5,320,257 |
def generate_hyperparameters(k):
"""
generate k sets of hyperparameters randomly : (mutate_prob, elite, alpha, beta)
Args:
k: number of sets
Returns:
list of settings, where each setting is a set of hyperparameters
"""
settings = []
for i in range(k):
setting = [np.... | 5,320,258 |
def unparse_point_sources(point_sources, strict=False, expand_env_vars=False, properties=lambda x:''):
""" Convert a list (or other iterable) of PointSource objects into XML.
strict : bool
set True to generate exception, error message identifying offending source, reason
properties : a f... | 5,320,259 |
def pion_to_muon_avg(x_lower, x_upper):
"""
Energy distribution of a numu from the decay of pi
Args:
x_lower,x_lower (float): energy fraction transferred to the secondary, lower/upper bin edge
Returns:
float: average probability density in bins (xmin,xmax)
"""
if x_lower.shape != x_... | 5,320,260 |
def secord_update(t, x, u, params={}):
"""Second order system dynamics"""
omega0 = params.get('omega0', 1.)
zeta = params.get('zeta', 0.5)
u = np.array(u, ndmin=1)
return np.array([
x[1],
-2 * zeta * omega0 * x[1] - omega0*omega0 * x[0] + u[0]
]) | 5,320,261 |
def addChangeListener(target, listener, *args, **kwargs):
"""
Shortcut for addEventListener(target, ChangeListener, 'stateChanged',
listener).
"""
from javax.swing.event import ChangeListener
return addEventListener(target, ChangeListener, 'stateChanged', listener,
*... | 5,320,262 |
def drop_no_image(df: pd.DataFrame,
imaged_samples: List[int]) -> pd.DataFrame:
"""
Pandas pipe function to drop any rows from table for samples that have no images.
"""
df_temp = df[df['Sample'].isin(imaged_samples)]
return df_temp | 5,320,263 |
def parse_fasta(handle):
"""Parse sequences in a FASTA file.
Sequence headers are trimmed after the first whitespace.
Returns:
Sequences in FASTA file keyed on their headers (i.e. > line)
"""
sequences = OrderedDict()
skip = False
for line in handle:
try:
line ... | 5,320,264 |
def assign_cat(plugin):
"""Assigns `symbols` module mapping to the `Warp` plugin."""
items = []
for item in MAPPING_SYMBOLS:
items.append(
plugin.create_item(
category=plugin.CATEGORY_SYMBOLS,
label=item[0],
short_desc=item[1],
... | 5,320,265 |
def demultiplexSamples(inputfile,outputfile):
""" demultiplexes all the samples """
os.chdir(os.path.join(root_dir,"demultiplexed"))
cmd = "pyBarcodeFilter.py -f '%s' -b '%s' -m '%s'" % (inputfile,os.path.join(home_dir,args.barcodes),args.mismatches)
logger.info(cmd)
os.system(cmd)
os.chdir(root_dir) | 5,320,266 |
def _get_func_def_ret_type(semanal: SemanticAnalyzerPluginInterface, funcdef: FuncDef) -> Type:
"""
Given a `FuncDef`, return its return-type (or `Any`)
"""
ret_type = None
type_ = funcdef.type
if isinstance(type_, CallableType):
ret_type = type_.ret_type
if isinstance(ret_type, U... | 5,320,267 |
def test_launch_with_fake_oauth_consumer_key_value():
"""
Does the launch request work when the consumer_key isn't correct?
"""
oauth_consumer_key = 'my_consumer_key'
oauth_consumer_secret = 'my_shared_secret'
launch_url = 'http://jupyterhub/hub/lti/launch'
headers = {'Content-Type': 'applic... | 5,320,268 |
def setup(hass, config):
"""Mock a successful setup."""
return True | 5,320,269 |
def load_mappings(descriptions):
"""
Input to an LSTM must be a 3D tensor. For that, I
am reading all the descriptions line by line and
storing their embeddings row wise into a numpy
array of 3 dimensions and shape (n, 500, 300).
"""
global wv
count = 0
# Fixed shape for the input layer of the lstm network.
... | 5,320,270 |
def generate_breadcrumbs(text):
"""
It expects a string with format `name=url, name=url, ...' and it will automatically convert that into a list of
dictionaries `[{name: url}, {name: url}, ...]`.
"""
entries = text.split(',')
values = {}
for entry in entries:
entry = entry.split('='... | 5,320,271 |
def clear_vocabulary(namefile_in, namefile_out):
""" Get a file withe vocabulary and nb of apparitions and create a new file with vocabulary and apparitions but
with medoc, punctuation an lettres alone removed"""
out = open(namefile_out, 'w')
with open(namefile_in, 'r') as f:
first = True
... | 5,320,272 |
def _compile_docker_commands(app_name, assembled_specs, port_spec):
""" This is used to compile the command that will be run when the docker container starts
up. This command has to install any libs that the app uses, run the `always` command, and
run the `once` command if the container is being launched fo... | 5,320,273 |
async def test_create_protocol_invalid_file(
decoy: Decoy,
protocol_store: ProtocolStore,
response_builder: ResponseBuilder,
unique_id: str,
current_time: datetime,
async_client: AsyncClient,
) -> None:
"""It should reject a request with an empty file."""
decoy.when(
await protoc... | 5,320,274 |
def equation_expow3(x, a, b, c, d, e):
"""Equation form for expow3 """
return exp(a + b*x + x*c/2) | 5,320,275 |
def _process_cosmos_qa(example):
"""Process cosmos_qa dataset example."""
label = tf.cast(example['label'], tf.int32)
one_hot = tf.one_hot(label, 4)
options = tf.stack([
example['answer0'],
example['answer1'],
example['answer2'],
example['answer3'],
])
return {
'context': examp... | 5,320,276 |
def resolve_collisions(rlist, newr, collision):
"""Adjust region list rlist to avoid overlaps with newr"""
updated = []
for i in range(len(rlist)):
if collision[i]:
updated.extend(split(rlist[i], newr))
else:
updated.append(rlist[i])
return updated | 5,320,277 |
def create_source_list(paths: Sequence[str], options: Options,
fscache: Optional[FileSystemCache] = None,
allow_empty_dir: bool = False) -> List[BuildSource]:
"""From a list of source files/directories, makes a list of BuildSources.
Raises InvalidSourceList on erro... | 5,320,278 |
def beale(xy):
"""
The Beale function, as a set of residuals (cost = sum(residuals**2))
The standard Beale's function is with data as [1.5, 2.25, 2.625],
and has a global minima at (3, 0.5). Beale's function is a coupled
model, linear in x and quartic in y. Its data-space dimension (3) is
great... | 5,320,279 |
def gen_evol(input_dictionary):
"""It generates an output file containing flow and flowing enthalpy for each GEN element. As a convention the library it is suggested to use GEN for any source/sink that is not a well
Parameters
----------
input_dictionary : dictionary
Dictionary contaning the path and name of dat... | 5,320,280 |
def ks_twosamp(data1, data2, alternative="two-sided"):
"""
Computes the Kolmogorov-Smirnov test on two samples.
Missing values are discarded.
Parameters
----------
data1 : array_like
First data set
data2 : array_like
Second data set
alternative : {'two-sided', 'less', '... | 5,320,281 |
def getIdFromVpcArn(resources):
""" given a vpc arn, strip off all but the id """
vpcStr = 'vpc/'
ids = []
for resource in resources:
if vpcStr in resource:
index = resource.rfind(vpcStr)
id = resource[index+len(vpcStr):]
ids.append(id)
return ids | 5,320,282 |
def input_output_mapping():
"""Build a mapping dictionary from pfb input to output numbers."""
# the polyphase filter bank maps inputs to outputs, which the MWA
# correlator then records as the antenna indices.
# the following is taken from mwa_build_lfiles/mwac_utils.c
# inputs are mapped to output... | 5,320,283 |
def test_e2e_github_media_endpoint_double_upload_and_delete(
app: Flask,
indieauthfix: IndieAuthActions,
client: FlaskClient,
testconstsfix: TestConsts,
):
"""Test that a double-upload works as expected and then delete the result
Disabled for now because this test is only useful in remote media... | 5,320,284 |
def get_testmeta_min_max_count(leaf, x_axis):
"""
This function expects all x label titles to be numeric value
so we can calculate the minimum and maximum of them.
"""
testcases = get_testcases(leaf)
# logaritmic, we need to calculate the position
minval = None
maxval = None
for tit... | 5,320,285 |
def xplus(x, v):
"""
Adds two 3DOF states with an arbitrary number of parameters.
"""
xv = np.add(x, v)
xv[2] = unwrap(xv[2])
return xv | 5,320,286 |
def rexec(cmd):
""" executes shell command cmd with the output
returned as a string when the command has
finished.
"""
try:
output = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as exc:
return exc.output[:-1]
else... | 5,320,287 |
def generate_sections_from_pyquery(body):
"""Given a pyquery object, generate section dicts for each section."""
# Capture text inside h1 before the first h2
h1_section = body('.section > h1')
if h1_section:
div = h1_section.parent()
h1_title = h1_section.text().replace('ยถ', '').strip()
... | 5,320,288 |
def get_value(symbol, amount, compare=args.c):
"""
Convert some amount of some coin, into the currency specified by -c
"""
if symbol.upper() == compare.upper():
return amount
#sometimes the API does not respond so this loop tri
num_attempts = 10
for attempt in range(num_attempts):
... | 5,320,289 |
def list_times(service):
"""
Lists the times from the selected calendar in ascending order.
:param service: a google 'service' object
:return: busy is a sorted list of busy times and free is a sorted list of
free times for the selected calendar(s)
"""
app.logger.debug('Entering list_times')
... | 5,320,290 |
def process(utim, data):
"""
Run process
:param Utim utim: Utim instance
:param list data: Data to process [source, destination, status, body]
:return list: [from, to, status, body]
"""
source = data[SubprocessorIndex.source.value]
destination = data[SubprocessorIndex.destination.value... | 5,320,291 |
def get_event_list_current_file(df, fname):
"""
Get list of events for a given filename
:param df: pd.DataFrame, the dataframe to search on
:param fname: the filename to extract the value from the dataframe
:return: list of events (dictionaries) for the given filename
"""
event_file = df[df[... | 5,320,292 |
def list_modules(args):
"""This method gets unique software from spider and prints the software
with total count.
This method implements ``buildtest module list``.
"""
querylimit = config_opts["module"]["list"]["querylimit"]
module_filter_include = config_opts["module"]["list"]["filte... | 5,320,293 |
def get_dealer_reviews_from_cf(url, **kwargs):
""" Get Reviews"""
results = []
json_result = get_request(url)
if json_result:
reviews = json_result["entries"]
for review in reviews:
dealer_review = DealerReview(id=review["id"],
name=re... | 5,320,294 |
def fused_normalize(x: th.Tensor, mean: th.Tensor, std: th.Tensor, eps: float = 1e-8):
"""Normalize or standardize."""
return (x - mean) / (std + eps) | 5,320,295 |
def get_attachment_file_upload_to(instance, filename):
""" Returns a valid upload path for the file of an attachment. """
return instance.get_file_upload_to(filename) | 5,320,296 |
def temp_ann(S_SHSTA_0, S_SHSTA_1, S_SHSTA_2, S_SHSTA_3, I_SHSTA_0, I_SHSTA_1,
I_SHSTA_2, I_SHSTA_3, C_KSWCK_0, C_KSWCK_1, C_KSWCK_2, C_KSWCK_3):
"""
Notes
-----
Where t = 0, provide the current time step. Where t = 1, provide the
1-month prior time step value. Repeat this pattern for a... | 5,320,297 |
def set_player(new_player):
"""Setter for the variable 'player' (keep human the present player X or O)."""
global player
player = new_player | 5,320,298 |
def slice(Matrix, a, b):
"""Slice a matrix properly- like Octave.
Addresses the confounding inconsistency that `M[a,b]` acts differently if
`a` and `b` are the same length or different lengths.
Parameters
----------
Matrix : float array
Arbitrary array
a, b : int lists or arrays
... | 5,320,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.