content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_init_from_emailmessage_with_issue():
"""Test the init_data_emailmessage function with issue."""
data = NotificationData.init_from_emailmessage("")
assert data is None | 5,324,200 |
def print_dictionary(my_dict: dict, level: int = 1, indent: int = 4, dense: bool = False) -> None:
""" Recursively prints the structure of a dictionary and the types of the values of its keys
:param my_dict: Dictionary to print
:param level: Degree of nesting
:param indent: Number of whi... | 5,324,201 |
def deproject(center,depth,K,pose=None):
"""
center.shape = [1,2]
depth.shape = [1,1]
K.shape = [3,3]
"""
out_gt = center * depth
out_gt = np.concatenate((out_gt, depth), 1)
# out_gt = [1,3]
inv_K = np.linalg.inv(K.T)
xyz = np.dot(out_gt, inv_K)
return xyz | 5,324,202 |
def get_branches(repo_id: str):
"""
Gets the branches from desired repository.
:param repo_id: repo id
:return: list(dict)
"""
branches = requests.get(url=BRANCHES_API_URL.format(repo_id), headers=HEADER).json()
return [parse_branch(branch) for branch in branches] | 5,324,203 |
def lfs_cart_portlet(context, title=None):
"""Tag to render the cart portlet.
"""
if title is None:
title = _(u"Cart")
portlet = CartPortlet()
portlet.title = title
return {
"html": portlet.render(context)
} | 5,324,204 |
def test_make_uris_request():
"""Return a request for all URIs with easy difficulty."""
# Given
difficulty = "easy"
# When
request = GraphGateway._make_uris_request(difficulty)
# Then
assert request == {
"KeyConditionExpression": Key("Difficulty").eq("EASY"),
"ProjectionExp... | 5,324,205 |
def test_declarative_barb_gfs_knots():
"""Test making a contour plot."""
data = xr.open_dataset(get_test_data('GFS_test.nc', as_file_obj=False))
barb = BarbPlot()
barb.data = data
barb.level = 300 * units.hPa
barb.field = ['u-component_of_wind_isobaric', 'v-component_of_wind_isobaric']
barb... | 5,324,206 |
def new(entities: Iterable[DXFEntity] = None, query: str = "*") -> EntityQuery:
"""Start a new query based on sequence `entities`. The `entities` argument
has to be an iterable of :class:`~ezdxf.entities.DXFEntity` or inherited
objects and returns an :class:`EntityQuery` object.
"""
return EntityQu... | 5,324,207 |
def create_pydot_graph(op_nodes, data_nodes, param_nodes, edges, rankdir='TB', styles=None):
"""Low-level API to create a PyDot graph (dot formatted).
"""
pydot_graph = pydot.Dot('Net', graph_type='digraph', rankdir=rankdir)
op_node_style = {'shape': 'record',
'fillcolor': '#6495ED... | 5,324,208 |
def stop_updating():
"""
Stops receiving location updates.
"""
__PyLocationHelper__.stopUpdating() | 5,324,209 |
def info_session(request, session_type):
"""Information session request form."""
if not SESSION_TYPES.get(session_type):
raise Http404
if request.method == 'POST':
form = InfoSessionForm(session_type, request.POST)
if form.is_valid():
cd = form.cleaned_data
se... | 5,324,210 |
def _get_batch(generator, batch_size, num_steps, max_word_length):
"""
Read batches of input.
"""
cur_stream = [None] * batch_size
no_more_data = False
while True:
inputs = np.zeros([batch_size, num_steps], np.int32)
if max_word_length is not None:
char_inputs = np.z... | 5,324,211 |
def transform_frame(frame, transformation_matrix):
"""
transform the selected region to bird's eye view
:param frame: the original image
:param transformation_matrix: the transformation matrix
:return: the image after transform, width scale, and height scale
"""
rows, cols, _ = frame.shape
... | 5,324,212 |
def test_inputs_constraints(minimal_inputs: Dict[str, str]) -> None:
"""
Test Inputs state class properties.
"""
missing_inputs = minimal_inputs.copy()
missing_inputs.pop("project")
read_data = json.dumps(missing_inputs)
with patch("builtins.open", mock_open(None, read_data)):
with ... | 5,324,213 |
def _annotation_dict_all_filter(data, query):
"""Match edges with the given dictionary as a sub-dictionary.
:param dict data: A PyBEL edge data dictionary
:param dict query: The annotation query dict to match
:rtype: bool
"""
annotations = data.get(ANNOTATIONS)
if annotations is None:
... | 5,324,214 |
def split_storm_info(storm_list):
"""split_storm_info takes a list of strings and creates a pandas dataframe
for the data set taken off the NHC archive. This function is called in the main to
find all storms."""
name, cycloneNum, year, stormType, basin, filename = [], [], [], [], [], []
for line in... | 5,324,215 |
def open_file(file_name):
""" Opens a comma separated CSV file
Parameters
----------
file_name: string
The path to the CSV file.
Returns:
--------
Output: the opened file
"""
# Checks for file not found and perrmission errors
try:
f = open(file_name, 'r')
... | 5,324,216 |
def linear_inshape(module_masks, mask):
"""
Coarse grained input mask does not change the shape of weights and output tensor
Parameters
----------
module_masks : ModuleMasks
The ModuleMasks instance of the linear
mask : CoarseMask
The mask of its input tensor
Returns
--... | 5,324,217 |
def test_enable_8021q_3(monkeypatch):
"""Verify that enable_802q_1 function return exception if 8021q can not be loaded.
"""
cmd_list = []
def mockreturn(command):
cmd_list.append(command)
so = "8021q"
if command == "lsmod | grep ^8021q":
so = ""
return CmdS... | 5,324,218 |
def test_update_sqrt(H_and_SQ, SC, measurement_style):
"""Sqrt-update coincides with non-square-root update."""
H, _ = H_and_SQ
SC_new, kalman_gain, innov_chol = tornadox.sqrt.update_sqrt(H, SC)
assert isinstance(SC_new, jnp.ndarray)
assert isinstance(kalman_gain, jnp.ndarray)
assert isinstanc... | 5,324,219 |
def prep_data_for_feature_gen(data):
"""Restructure OANDA data to use it for TA-Lib feature generation"""
inputs = {
'open': np.array([x['openMid'] for x in data]),
'high': np.array([x['highMid'] for x in data]),
'low': np.array([x['lowMid'] for x in data]),
'close': np.arr... | 5,324,220 |
def matriz_krylov(A, x, n_iters=None):
"""Genera una matriz de krylov dada una matriz A y un vector x. Cada columna de la matriz es la iteración i de A^i*x.
Args:
A (matriz): Matriz de aplicación
x (vector): Vector base
n_iters (int, optional): Número de iteraciones. Por defecto es el n... | 5,324,221 |
def test_case_result_score(answers, user_test_id):
"""
Calculate result score for test.
Check every user's answer (check_answer), calculate number of correct answers.
@param answers: dict of pairs question_id and list of answers.
@param user_test_id: UserTestCase object id --> int
@return: res... | 5,324,222 |
def AtensDeltaV(df):
"""Delta V calculation for Atens asteroids, where a < 1."""
df['ut2'] = 2 - 2*np.cos(df.i/2)*np.sqrt(2*df.Q - df.Q**2)
df['uc2'] = 3/df.Q - 1 - (2/df.Q)*np.sqrt(2 - df.Q)
df['ur2'] = 3/df.Q - 1/df.a - (
(2/df.Q)*np.cos(df.i/2)*np.sqrt(df.a*(1-df.e**2)/df.Q))
return df | 5,324,223 |
def init__builtin__(space):
"""NOT_RPYTHON"""
##SECTION##
## filename '<codegen /Users/steve/Documents/MIT TPP/2009-2010/6.893/project/pypy-dist/pypy/interpreter/gateway.py:824>'
## function 'pypy_init'
## firstlineno 2
##SECTION##
# global declarations
# global object g3dict
# global object gs___name__
# glob... | 5,324,224 |
def CalculateXuIndex(mol):
"""
#################################################################
Calculation of Xu index
---->Xu
Usage:
result=CalculateXuIndex(mol)
Input: mol is a molecule object
Output: result is a numeric value
###... | 5,324,225 |
def register_dataclass(registry: ServiceRegistry, target, for_, context=None):
""" Generic injectory factory for dataclasses """
# Note: This function could be a decorator which already knows
# the registry, has all the targets, and can do them in one
# container that it makes. For example:
# from ... | 5,324,226 |
async def test_json_request(aresponses: ResponsesMockServer) -> None:
"""Test JSON response is handled correctly."""
aresponses.add(
"api.eiswarnung.de",
"/test",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
... | 5,324,227 |
def cleanup(cluster_name, cluster_id):
"""
Cleanup existing cluster in AWS
Args:
cluster_name (str): Name of the cluster
cluster_id (str): Cluster id to cleanup
"""
data = {'cluster_name': cluster_name, 'cluster_id': cluster_id}
template = templating.Templating(base_path=TEMPLA... | 5,324,228 |
async def async_setup_entry(hass, config_entry):
"""Set up the UniFi component."""
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
controller = UniFiController(hass, config_entry)
controller_id = get_controller_id_from_config_entry(config_entry)
hass.data[DOMAIN][controller_id] = contr... | 5,324,229 |
def delete(profile, name):
"""Delete a load balancer.
Args:
profile
A profile to connect to AWS with.
name
The name of a load balancer.
"""
# Make sure it exists before we try to delete it.
load_balancer_data = fetch_by_name(profile, name)
if not load_... | 5,324,230 |
def test_cray_capmc_xname_reinit_call(cli_runner, rest_mock):
""" Test `cray capmc xname_reinit create --xnames <xname list>` """
runner, cli, opts = cli_runner
url_template = capmc_url_base + '/xname_reinit'
config = opts['default']
hostname = config['hostname']
result = runner.invoke(cli, ['ca... | 5,324,231 |
async def test_if_fires_on_state_change(hass, calls, enable_custom_integrations):
"""Test for turn_on and turn_off triggers firing.
This is a sanity test for the toggle entity device automation helper, this is
tested by each integration too.
"""
platform = getattr(hass.components, "test.switch")
... | 5,324,232 |
async def on_issue_opened(
*,
action, issue, repository, sender, installation,
assignee=None, changes=None,
):
"""Whenever an issue is opened, greet the author and say thanks."""
github_api = RUNTIME_CONTEXT.app_installation_client
comments_api_url = issue["comments_url"]
author... | 5,324,233 |
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['time_to_run'] = int(env['_run_duration'])
env['suffix'] = 'WMT'
env['recording_interval'] = int(float(env['_run_duration'... | 5,324,234 |
def file_to_dataframe(file_id, compression='infer', client=None,
**read_kwargs):
"""Load a :class:`~pandas.DataFrame` from a CSV stored in a Civis File
The :class:`~pandas.DataFrame` will be read directly from Civis
without copying the CSV to a local file on disk.
Parameters
... | 5,324,235 |
def parse_hub_remove(arg: str):
"""Parse --remove flag under hub mode."""
if arg in ['data', 'all']:
data_files = glob.glob(hub_configs.HUB_DATA_DIR + '/*.csv')
for f in data_files:
os.remove(f)
print(f'Removed stored file at {f}')
if arg in ['logs', 'all']:
if os.path.exists(hub_configs.L... | 5,324,236 |
def dataset_to_xy(
dataset: Dataset,
target_columns: Union[str, list],
qid_column: Optional[str],
):
"""Convert Merlin Dataset to XGBoost DMatrix"""
df = dataset.to_ddf()
qid = None
if qid_column:
df = df.sort_values(qid_column)
qid = df[qid_column]
all_target_columns =... | 5,324,237 |
def assignment_a():
"""
Assignment a) consists of our simple baseline BinaryClassifier
In this function we train and evaluate it.
Note we can generate an evaluation csv for different configurations via our Evaluator (comment out the last line)
"""
classifier = BinaryClassifier()
classifier.a... | 5,324,238 |
def clean_data(df):
"""Clean data included in the DataFrame and transform categories part
INPUT
df -- type pandas DataFrame
OUTPUT
df -- cleaned pandas DataFrame
"""
categories = df['categories'].str.split(pat=';', expand=True)
row = categories.loc[0]
colnames = []
for entry in r... | 5,324,239 |
def builder_start():
"""Start the builder instance."""
instance = BuilderInstance.instance()
if instance.status() == 'stopped':
print("Starting builder instance...")
instance.start()
for _ in range(60):
if instance.status() == 'running':
break
... | 5,324,240 |
def compute_timeline(agents, ts_tuple, dep_ivs):
"""
Compute the timeline of events that can occur in the field.
Given the departure intervals of the agents, this function
computes a common timeline of events that captures all possible
occurances of events in the field.
Parameters
----------
agents: A list ... | 5,324,241 |
def acl(ctx):
"""Work with catalogs access control list in the current Organization.
\b
Examples
vcd catalog acl add my-catalog 'org:TestOrg1:Change' \\
'user:TestUser1:FullControl' 'org:TestOrg2'
Add one or more access setting to the specified catalog.
access-list ... | 5,324,242 |
def test_suite():
"""Test suite including all test suites"""
testSuite = unittest.TestSuite()
testSuite.addTest(test_randomdata.test_suite())
return testSuite | 5,324,243 |
def eHealthClass_setupPulsioximeterForNextReading():
"""eHealthClass_setupPulsioximeterForNextReading()"""
return _ehealth.eHealthClass_setupPulsioximeterForNextReading() | 5,324,244 |
def test_create_yaml_parameter_file2(tmp_path):
"""Test if file overwriting protection works"""
fln = os.path.join(tmp_path, "parameters.yaml")
# Generate the set of parameters (we don't use docstring in this test)
param_dict = _generate_parameter_set()
doc_string, parameters = _generate_sample_do... | 5,324,245 |
def hist_argmaxima2(hist, maxima_thresh=.8):
"""
must take positive only values
Setup:
>>> # ENABLE_DOCTEST
>>> from vtool_ibeis.histogram import * # NOQA
GridSearch:
>>> hist1 = np.array([1, .9, .8, .99, .99, 1.1, .9, 1.0, 1.0])
>>> hist2 = np.array([1, .9, .8, .99, .... | 5,324,246 |
def meet_types(s: Type, t: Type) -> ProperType:
"""Return the greatest lower bound of two types."""
if is_recursive_pair(s, t):
# This case can trigger an infinite recursion, general support for this will be
# tricky so we use a trivial meet (like for protocols).
return trivial_meet(s, t... | 5,324,247 |
def delete_context(id):
"""
Delete the requested context object.
This WILL delete the index, but any alias of the same name.
:param id: str, the unique ID of the requested Context
:return: aknowledge message as JSON
"""
# get the object
ctx = Context.get(id)
ctx.delete(delete_index=... | 5,324,248 |
def dosplot(filename=None, prefix=None, directory=None, elements=None,
lm_orbitals=None, atoms=None, subplot=False, shift=True,
total_only=False, plot_total=True, legend_on=True,
legend_frame_on=False, legend_cutoff=3., gaussian=None, height=6.,
width=8., xmin=-6., xmax=6... | 5,324,249 |
def get_relative_percentage(new, last):
"""
:param new: float
New value
:param last: float
Last value
:return: float in [0, 100]
Percentage (with errors handling)
"""
ratio = get_ratio(new, last)
relative_ratio = ratio - 1.0
return 100.0 * relative_ratio | 5,324,250 |
def parse_data_name(line):
"""
Parses the name of a data item line, which will be used as an attribute name
"""
first = line.index("<") + 1
last = line.rindex(">")
return line[first:last] | 5,324,251 |
def api_error(api, error):
"""format error message for api error, if error is present"""
if error is not None:
return "calling: %s: got %s" % (api, error)
return None | 5,324,252 |
def dailyImage(request,date=None):
""" returns daily image html page for date """
today = datetime.datetime.today()
earliest = Image.pub_dates.earliest()
if date is None:
this_date = datetime.datetime.strftime(today,'%F')
else:
try:
this_date = datetime.datetime(*(tim... | 5,324,253 |
def get_depolarizing_channel(T, t_gate=10e-9):
"""Get the depolarizing channel
Args:
T (float): Decoherence parameter (seconds)
"""
assert T > 0
assert t_gate > 0
gamma = 1 - pow(np.e, -1 / T * t_gate)
noise_model = depolarize(gamma)
return noise_model | 5,324,254 |
def censor_signal(signal, filtered_signal, fold, left_trim, right_trim_percent):
"""Finds points where residual is greater than the given fold, and trims
given number of point from the left, and some multiple of that from the right.
"""
ltrim = int(left_trim)
rtrim = int(left_trim * right_trim_percent)
indexes =... | 5,324,255 |
def get_choices(state, attribute_name):
"""
Return a list of the choices (excluding separators) in the
SelectionCallbackProperty.
"""
choices = []
labels = []
display_func = getattr(type(state), attribute_name).get_display_func(state)
if display_func is None:
display_func = str
... | 5,324,256 |
def props_list(star_df,outfolder='starprops',kepler=True,overwrite=False):
"""input DataFrame must have the following columns:
name,teff,e_teff,logg,e_logg,feh,e_feh
"""
if type(star_df) == type(''):
star_df = pd.read_table(star_df,delimiter='\s+')
if kepler:
star_df['nam... | 5,324,257 |
def compatibility_factors_to_coo(ncf: dict, nreg: dict):
"""
ncf : nodal_compatibility_factors
"""
nN = len(ncf)
widths = np.zeros(nN, dtype=np.int32)
for iN in prange(nN):
widths[iN] = len(nreg[iN])
shapes = (widths**2).astype(np.int64)
N = np.sum(shapes)
data = np.zeros(N, ... | 5,324,258 |
def combine_complex(output_arr_t):
"""
Returns a transformation that joins two real inputs into complex output
(1 output, 2 inputs): ``output = real + 1j * imag``.
"""
input_t = Type(dtypes.real_for(output_arr_t.dtype), shape=output_arr_t.shape)
return Transformation(
[Parameter('output'... | 5,324,259 |
def quantity_unwrapped(units, multiplier=1.0):
"""
A decorator for setters to extract the plain device value from the quantity.
"""
def wrap(f):
@wraps(f)
def wrapped(self, value):
value.assert_dimensions(units)
return f(self, value.value * multiplier)
return wrapped
return wrap | 5,324,260 |
def displacement_error(pred_fut_traj, fut_traj, consider_ped=None, mode="sum"):
"""
Compute ADE
Input:
- pred_fut_traj: Tensor of shape (seq_len, batch, 2). Predicted trajectory. [12, person_num, 2]
- fut_traj: Tensor of shape (seq_len, batch, 2). Groud truth future trajectory.
- consider_ped: ... | 5,324,261 |
def __json(informations: _Dict[int, ErrorInfo]) -> str:
"""制作 json 格式的数据"""
errcodes: _Dict[int, _Dict[str, str]] = dict()
for code, info in informations.items():
errcodes[code] = dict(info._asdict())
return _json.dumps(errcodes, indent=4, sort_keys=True, ensure_ascii=False) | 5,324,262 |
def write_ref_gro(outfile, velocities=False, box='10.0 10.0 10.0'):
"""
Write a GRO file from the reference data.
Parameters
----------
outfile: file
The file in which to write.
velocities: bool
Set if velocities must be written.
box: str
The box string to write at t... | 5,324,263 |
def get_average_pairwise_distance(df, n=1000):
"""Get average pairwise distance for a group of embeddings. Smaller number means closer together.
With n=1000, this function is generally precise within 0.01
Parameters
----------
df: DataFrame
input data
n: int
number of rando... | 5,324,264 |
def thorpe_scales(S, T, p, lat, lon, axis=-1):
"""
Thorpe scales simplified for estimating dissipation rates
Parameters
----------
S : Practical Salinity
T : Practical Temperature
P : Pressure Measurements -- NOT A NORMALIZED PRESSURE GRID
lat : Latitude
lon : Longitude
Returns... | 5,324,265 |
def v() -> Dict[TState, float]:
"""Initial state values for use in tests."""
return {"A": 3.0, "B": 1.0, "C": 0.0} | 5,324,266 |
def test_is_hot_pixel():
"""Test hot pixel detector."""
# Create random signal
signal = np.random.default_rng().integers(20, size=100)
# Add hot pixels
signal[10::20] = 50
signal[10::30] = 150
hot_pix = is_hot_pixel(signal)
assert len(hot_pix) == 100
assert 3 <= sum(hot_pix) < 6
... | 5,324,267 |
def save_tl_images(input_yaml, output_folder):
"""
Extracts labelled pictures of traffic lights.
Saves them as separate files in specified output_folder.
:param input_yaml: Path to yaml file
:param output_folder: path to folder. created if does not exist
"""
images = get_all_labels(input_ya... | 5,324,268 |
def GetSvnInfo():
"""Returns the project name and the current SVN workspace's root path."""
for line in GetCommandOutput('svn info .'):
m = _SVN_INFO_URL_RE.match(line)
if m:
project = m.group(1) # googletest or googlemock
rel_path = m.group(2)
root = os.path.realpath(rel_path.co... | 5,324,269 |
def prRowv(fh, *objs):
"""Print a row from each argument to a tab file.
Does string conversion on each columns"""
first = True
for col in objs:
if not first:
fh.write("\t")
fh.write(str(col))
first = False
fh.write("\n") | 5,324,270 |
def post_with_dict_param(dict_in_param):
"""
"""
pass | 5,324,271 |
def iter_listeners(event):
"""Return an iterator for all the listeners for the event provided."""
ctx = stack.top
return ctx.app.extensions.get('plugin_manager')._event_manager.iter(event) | 5,324,272 |
def _compute_box_size(topology, density):
"""
Lookup the masses in the `topology`
and compute a cubic box that matches
the `density` given the number of molecules
defined in the topology. Units are nm
Parameters:
-----------
topology: :class:`polyply.src.topology`
density: float
... | 5,324,273 |
def main():
"""Entry point for test_analy"""
config = parse_command_line()
test_reverse_analy = TestReverseAnaly(config.module, config.file)
d_object = test_reverse_analy.create_conf_model_with_conf_info()
content = test_reverse_analy.check_reverse_conf_model(d_object) | 5,324,274 |
def nodes_in_frustum(scene, frustum, skip_invisible=True):
"""
create Bounding boxes for meshes + manual offset value for skinned?
"""
yield node | 5,324,275 |
def build_template(ranges, template, build_date, use_proxy=False, redir_target=""):
"""
Input: output of process_<provider>_ranges(), output of get_template()
Output: Rendered template string ready to write to disk
"""
return template.render(
ranges=ranges["ranges"],
header_comments=... | 5,324,276 |
def _get_named_value(obj, name):
""" Utility function that returns the value of the given copasi object
:param obj: a copasi object, that could be a compartment, species, parameter, reaction
:param name: the reference name to return
:return:
"""
is_metab = isinstance(obj, COPASI.CMetab)
is_... | 5,324,277 |
def lang_add(cursor, lang, trust):
"""Adds language for db"""
if trust:
query = 'CREATE TRUSTED LANGUAGE "%s"' % lang
else:
query = 'CREATE LANGUAGE "%s"' % lang
executed_queries.append(query)
cursor.execute(query)
return True | 5,324,278 |
def test_cloud_receiving_bytes(mock_client, caplog):
"""Test server disconnecting instance."""
cloud = MagicMock()
conn = iot.CloudIoT(cloud)
mock_client.receive.return_value = mock_coro(MagicMock(
type=WSMsgType.BINARY,
))
yield from conn.connect()
assert 'Connection closed: Recei... | 5,324,279 |
def lemmas(directory, api):
"""Generate lemma/POS annotations (i.e., Lemma namedtuples) via Rosette API
analysis for a directory of text files
directory : a directory of text files
api : a rosette.api.API instance
"""
for filename in find_files(directory, pattern='*.txt'):
adm... | 5,324,280 |
def test_push_method_assigns_stack_top_to_equal_stack_list_at_index_zero():
"""Test that the push method of the Stack class object assigns the stack's
top attribute to equal the data contained at index zero of the Stack's
stack list."""
stack = Stack()
stack.push(3)
assert stack.top == stack.s... | 5,324,281 |
def _strip_and_dedent(s):
"""For triple-quote strings"""
return textwrap.dedent(s.lstrip('\n').rstrip()) | 5,324,282 |
def calculate_stress_by_matrix_rotation(wlsq_strain, U):
"""
Calculate the intra-granular stresses by applying the sample system stiffnes matrix for a given grain and z-slice
to the corresponding strains.
:param wlsq_strain: Strains as a list of numpy arrays, where each list contains a strain component... | 5,324,283 |
def fundamentals_dataframe(
timeframe: Timeframe, stock: str, ld: LazyDictionary
) -> pd.DataFrame:
"""Return a dict of the fundamentals plots for the current django template render to use"""
df = ld["stock_df"]
# print(df)
df["change_in_percent_cumulative"] = df[
"change_in_percent"
].c... | 5,324,284 |
def create_random_word_db(output_path, sen_idx, dict_size=50001):
"""
Create db for existing of random word in the sentence
We consider this test as binary classification
Here the input is the sentence representation concatenate with the representation of the some word
For positive examples we use t... | 5,324,285 |
def returns_normally(expr):
"""For use inside `test[]` and its sisters.
Assert that `expr` runs to completion without raising or signaling.
Usage::
test[returns_normally(myfunc())]
"""
# The magic is, `test[]` lifts its expr into a lambda. When the test runs,
# our arg gets evaluated ... | 5,324,286 |
def verify_presentation_state_content(presentation_state):
"""Helper function to verify that the content in presentation_state is appropriate
to create a basic text SR object
----------
Parameters
"""
if not isinstance(presentation_state, dict):
print("instance is expected to be a dict"... | 5,324,287 |
def getProfile(request):
"""
Return MY profile for editing.
"""
profile = UserProfile.objects.get(
user=request.user
)
return profile.ajax() | 5,324,288 |
def finder(input, collection, fuzzy=False, accessor=lambda x: x):
"""
Args:
input (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
based on the `input`.
fuzzy (bool): perform a fuzzy search (d... | 5,324,289 |
def calc_rets(returns, weights):
"""
Calculate continuous return series for futures instruments. These consist
of weighted underlying instrument returns, who's weights can vary over
time.
Parameters
----------
returns: pandas.Series or dict
A Series of instrument returns with a Mult... | 5,324,290 |
def testMaze(n_training_trials, n_navigation_trials):
"""
No comments here. Look at single_maze_learning_agent.py for more details!
"""
ValueLearning.DBG_LVL = 0
move_distance = 0.29
nx = 6
ny = 6
n_fields = round(1.0 * (nx + 3) * (ny+3))
Hippocampus.N_CELLS_PER_FIELD = 4
n_cel... | 5,324,291 |
def group_calc(df, single_group_func, group_col, sort_col=None,
exclude_groups=None):
"""Performs a general function on a dataframe with distinct subsets.
In a tidy, time series dataframe with multiple groups, say states, age
groups, etc. there is often a need to perform an operation on each... | 5,324,292 |
def check_addressbook(assert_address_book):
"""Check the validity and completeness of the address book."""
assert zope.location.interfaces.ISite.providedBy(
assert_address_book.address_book)
assert_address_book.has_attribute('keywords', IKeywords)
assert_address_book.has_attribute(
'prin... | 5,324,293 |
def str2int(video_path):
"""
argparse returns and string althout webcam uses int (0, 1 ...)
Cast to int if needed
"""
try:
return int(video_path)
except ValueError:
return video_path | 5,324,294 |
def set_deterministic_pytorch(args):
"""Ensures pytorch produces deterministic results depending on the program arguments
:param Namespace args: The program arguments
"""
# seed setting
torch.manual_seed(args.seed)
# debug mode setting
# 0 would be fastest, but 1 seems to be reasonable
... | 5,324,295 |
def describe_inheritance_rule(rule):
"""
Given a dictionary representing a koji inheritance rule (i.e., one of the
elements of getInheritanceData()'s result), return a tuple of strings to be
appended to a module's stdout_lines array conforming to the output of
koji's taginfo CLI command, e.g.:
... | 5,324,296 |
def plot_cv_indices(cv, X, y, ax, lw=50):
"""Create a sample plot for indices of a cross-validation object."""
splits = list(cv.split(X=X, y=y))
n_splits = len(splits)
# Generate the training/testing visualizations for each CV split
for ii, (train, test) in enumerate(splits):
# Fill in indi... | 5,324,297 |
def find_colour(rgb):
"""Compare given rgb triplet to predefined colours to find the closest one"""
# this cannot normally happen to an image that is processed automatically, since colours
# are rbg by default, but it can happen if the function is called with invalid values
if rgb[0] < 0 or rgb[0] > 25... | 5,324,298 |
def training_pipeline(
training_data_loader,
skew_comparison,
trainer,
evaluator,
deployment_trigger,
model_deployer,
):
"""Train, evaluate, and deploy a model."""
X_train, X_test, y_train, y_test = training_data_loader()
skew_comparison(X_train, X_test)
model = trainer(X_train=X... | 5,324,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.