content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _query_multi_armed_bandit_probabilities():
"""Get query results.
Queries above BANDIT_PROBABILITY_QUERY and yields results
from bigquery. This query is sorted by strategies implemented."""
client = big_query.Client()
return client.query(query=BANDIT_PROBABILITY_QUERY).rows | 5,308,800 |
def check_jobs():
"""Check if various jobs have been running.
The following URL parameters can be provided:
- names:
- Comma separated list of names of tasks to check.
- seconds (default 3600)
- How many seconds are allowed since last completion of a job
named in the names parameter.
If a job in... | 5,308,801 |
def load_darknet_weights(model, fp):
"""
Load DarkNet .weights file to `tf.keras.Model`.
Args:
model: `tf.keras.Model`
fp: Path to .weights file to load.
Returns:
None
Raises:
AssertionError: If weights are incompatible with the model hence,
not fully loa... | 5,308,802 |
def med(data, mw=24, sf=16, sigma=5.0):
"""
Median baseline correction
Algorith described in:
Friedrichs, M.S. JBNMR 1995 5 147-153.
Parameters:
* data Array of spectral data.
* mw Median Window size in pts.
* sf Smooth window size in pts.
* sigma Standard-deviation of Gaus... | 5,308,803 |
def test_heart_list_params(withings_api: WithingsApi) -> None:
"""Test function."""
responses_add_heart_list()
withings_api.heart_list(startdate="2020-01-01", enddate="2020-07-23", offset=1)
assert_url_query_equals(
responses.calls[0].request.url,
{"startdate": "1577836800", "enddate": ... | 5,308,804 |
def raoult_liquido(fraccion_vapor, presion_vapor, presion):
"""Calcula la fraccion molar de liquido mediante la ec de Raoult"""
return fraccion_vapor * presion / presion_vapor | 5,308,805 |
def deletePlayers():
"""Remove all the player records from the database."""
dbcursor = connect()
dbcursor.execute("TRUNCATE players")
return 1 | 5,308,806 |
def self_chat():
"""
This function makes cleverbot chat with itself.
"""
alice = Cleverbot()
bob = Cleverbot()
message = "Hi there! How are you doing?"
print("Press Ctrl-c to stop \n")
try:
while True:
print("Bob: ", message)
message = alice.send(message)
... | 5,308,807 |
def recursepath(path, reverse=False):
# type: (Text, bool) -> List[Text]
"""Get intermediate paths from the root to the given path.
Arguments:
path (str): A PyFilesystem path
reverse (bool): Reverses the order of the paths
(default `False`).
Returns:
list: A list of... | 5,308,808 |
def pack_items(arrays, key_encoding="utf-8"):
"""
Packs the specified items by computing the relevant file offsets
and return the list of ItemDescriptors and the overall size of the
file.
"""
num_items = len(arrays)
# We store the keys in sorted order in the key block.
sorted_keys = sort... | 5,308,809 |
def list_datasets():
"""Returns the list of available FiftyOne datasets.
Returns:
a list of :class:`Dataset` names
"""
# pylint: disable=no-member
return sorted(foo.DatasetDocument.objects.distinct("name")) | 5,308,810 |
def upgrade():
"""Migrations for the upgrade."""
conn = op.get_bind()
statement = sa.text('\n'.join(forward_sql))
conn.execute(statement) | 5,308,811 |
def wayPointDistribution(rx, ry, ryaw, s):
"""
:param rx:
:param ry:
:param ryaw:
:param s:
:return: generate the efficients of the reference line
"""
x_list = []
y_list = []
theta_list = []
s_list = []
for i in range(len(rx)):
if 20 * i > (len(rx) - 1):
break
x_list.append(rx[20 * i])
y_list.app... | 5,308,812 |
def rolling_median_(a, n, axis = 0, data = None, instate = None):
"""
Equivalent to rolling_median(a) but returns also the state.
For full documentation, look at rolling_median.__doc__
"""
import bottleneck as bn
state = instate or dict(vec = None)
return _data_state(['data','vec'],_rol... | 5,308,813 |
def implemented_motifs():
"""
Returns
-------
List strings of all implemented motif definitions
"""
return ['Sheet', 'Gamma', 'Herringbone',
'Sandwich'] | 5,308,814 |
def forward_word(event: E) -> None:
"""
Move forward to the end of the next word. Words are composed of letters and
digits.
"""
buff = event.current_buffer
pos = buff.document.find_next_word_ending(count=event.arg)
if pos:
buff.cursor_position += pos | 5,308,815 |
def validate_raw_bytes(value: Any, allow_empty: bool = False) -> None:
"""
Validate whether provided value stores raw bytes value.
:param value: Value to validate.
:param allow_empty: True if empty list is allowed, False otherwise.
:raise TypeError: Value is not tuple or list type.
:raise Valu... | 5,308,816 |
def left(direction):
"""rotates the direction counter-clockwise"""
return (direction + 3) % 4 | 5,308,817 |
def union(list1, list2):
"""Union of two lists, returns the elements that appear in one list OR the
other.
Args:
list1 (list): A list of elements.
list2 (list): A list of elements.
Returns:
result_list (list): A list with the union elements.
Examples:
>>> union([1,2,3... | 5,308,818 |
def test_blocks_infect_network(not_all_connected_directly_nodes):
"""
Feature file: block_gossiping.feature
Scenario: Blocks 'infect' the network and nodes 'closest' to the propose see the blocks first.
"""
first, last = not_all_connected_directly_nodes[0], \
not_all_connected_dire... | 5,308,819 |
def render_analytics_code():
"""
Renders the new google analytics snippet.
"""
return {
'ANALYTICS_TRACKING_ID': getattr(settings, 'ANALYTICS_TRACKING_ID',
'UA-XXXXXXX-XX'),
'ANALYTICS_DOMAIN': getattr(settings, 'ANALYTICS_DOMAIN', 'auto')
} | 5,308,820 |
def valid_proxy(proxy):
"""Return 1 if the proxy string looks like a valid url, for an
proxy URL else return 0."""
import urlparse
scheme, netloc, url, params, query, fragment = urlparse.urlparse(proxy)
if scheme != 'http' or params or query or fragment:
return 0
return 1 | 5,308,821 |
def oauth2_from_dict(oauth2_dictionary: dict):
"""
The function converts a dictionary of OAuth2 to a OAuth2 object.
:param oauth2_dict: A dictionary that contains the keys of a OAuth2.
:type oauth2_dict: dict
:rtype: ibmpairs.authentication.OAuth2
:raises Exception: if not a di... | 5,308,822 |
def export_file(isamAppliance, file_id, filename, check_mode=False, force=False):
"""
Exporting a common log file
"""
import os.path
ret_obj = {'warnings': ''}
if force is True or (os.path.exists(filename) is False):
if check_mode is False: # No point downloading a file if in check_mod... | 5,308,823 |
def _initiate_pipeline_stop(
mlmd_handle: metadata.Metadata,
pipeline_uid: task_lib.PipelineUid) -> metadata_store_pb2.Execution:
"""Initiates a pipeline stop operation.
Upon success, MLMD is updated to signal that the pipeline given by
`pipeline_uid` must be stopped.
Args:
mlmd_handle: A handle t... | 5,308,824 |
def slot_schedule_difference(old_schedule, new_schedule):
"""Compute the difference between two schedules from a slot perspective
Parameters
----------
old_schedule : list or tuple
of :py:class:`resources.ScheduledItem` objects
new_schedule : list or tuple
of :py:class:`resources.Sc... | 5,308,825 |
def reduce_with_info(data: Iterator) -> Generator[tuple]:
"""
Returns reduced data in `ReducedDataInfo` object (which contains information about reduced data).
Info objects consists of:
- index of first reduced element;
- value of first reduced element;
- reduced elements count.
Example:
... | 5,308,826 |
def test_independent_multi_output_sek_shi(
register_posterior_test: RegisterPosterior,
q_sqrt_factory: QSqrtFactory,
full_cov: bool,
full_output_cov: bool,
whiten: bool,
num_latent_gps: int,
output_dims: int,
) -> None:
"""
Independent multi-output posterior with separate independent... | 5,308,827 |
def drive_cancellation_seq(
drive_op_code, ramsey_qubit_names, operation_dict,
sweep_points, n_pulses=1, pihalf_spacing=None, prep_params=None,
cal_points=None, upload=True, sequence_name='drive_cancellation_seq'):
"""
Sweep pulse cancellation parameters and measure Ramsey on qubits the
... | 5,308,828 |
def generate_inputs(generate_calc_job_node, fixture_localhost, generate_structure, generate_kpoints_mesh):
"""Create the required inputs for the ``ProjwfcCalculation``."""
entry_point_name = 'quantumespresso.pw'
inputs = {'structure': generate_structure(), 'kpoints': generate_kpoints_mesh(4)}
parent_ca... | 5,308,829 |
def list_all_links_in_page(source: str):
"""Return all the urls in 'src' and 'href' tags in the source.
Args:
source: a strings containing the source code of a webpage.
Returns:
A list of all the 'src' and 'href' links
in the source code of the webpage.
"""
return re.findal... | 5,308,830 |
def resp_delete_successfully(msg):
"""Response 202"""
response = jsonify({
'message': f'{msg} delete successfully.'
})
response.status_code = 202
return response | 5,308,831 |
def embedding_column_v2(categorical_column,
dimension,
combiner='mean',
initializer=None,
max_sequence_length=0,
learning_rate_fn=None,
embedding_lookup_device=None,
... | 5,308,832 |
def test_tpf_shapes():
"""Are the data array shapes of the TargetPixelFile object consistent?"""
tpf = KeplerTargetPixelFile(filename_tpf_all_zeros)
assert tpf.quality_mask.shape == tpf.hdu[1].data['TIME'].shape
assert tpf.flux.shape == tpf.flux_err.shape | 5,308,833 |
def synthesize_data():
"""
synthesize the (block, program) pairs
:return: train_shape, train_prog, val_shape, val_prog
"""
# == training data ==
data = []
label = []
n_samples = [5000,
30000, 5000, 5000, 5000, 10000,
5000, 5000, 5000, 5000, 30000,
... | 5,308,834 |
def threeAxis(length):
""" Draws an X, Y and Z-axis """
glPushMatrix()
# Z-axis
glColor3f(1.0,0.0,0.0)
axis(length)
# X-axis
glRotated(90,0,1.0,0)
glColor3f(0.0,1.0,0.0)
axis(length)
# Y-axis
glRotated(-90,1.0,0,0)
glColor3f(0.0,0.0,1.0)
axis(length)
glPopMatr... | 5,308,835 |
def parse_predict_data(html: str) -> list[tuple]:
"""Returns the following tuple: (week, (away_data, home_data))
"""
predict_meta = FTE_PREDICT_STATS
parsed = []
soup = BeautifulSoup(html, HTML_PARSER)
# build field processor based on predict metadata
field_proc = {}
for col_key, col_... | 5,308,836 |
def get_direction(source, destination):
"""Find the direction drone needs to move to get from src to dest."""
lat_diff = abs(source[0] - destination[0])
long_diff = abs(source[1] - destination[1])
if lat_diff > long_diff:
if source[0] > destination[0]:
return "S"
else:... | 5,308,837 |
def snr_filter(input_fastq, raw_data_file, output_fastq, min_snr=SNR):
"""
Filter out sequences below a threshold of predicted accuracy
"""
log.info("Filtering sequences below {0} Signal-To-Noise Ratio".format(min_snr))
seq_count = 0
pass_count = 0
raw_data = BasH5Collection( raw_data... | 5,308,838 |
def processFile(file):
"""Processes a file"""
with open(file,"r") as inFile:
input_data = inFile.readlines()
if arguments['--remove']:
output = [line for line in input_data if arguments['<pattern>'] not in line]
else:
output = [line.replace(arguments['<pattern>'],arguments['<rep... | 5,308,839 |
def verifyPicklingCompatibility(otherPythonVersion):
"""
Check a provided python version string versus the present instance string for pickling safety.
:param otherPythonVersion: other version string
:return: True is safe, False otherwise
"""
if otherPythonVersion is None:
return False... | 5,308,840 |
def newAction(
parent,
text,
slot=None,
shortcut=None,
icon=None,
tip=None,
checkable=False,
enabled=True,
checked=False,
):
"""Create a new action and assign callbacks, shortcuts, etc."""
a = QtWidgets.QAction(text, parent)
if icon is ... | 5,308,841 |
def _echelon_form(M, iszerofunc=_iszero, simplify=False, with_pivots=False,
dotprodsimp=None):
"""Returns a matrix row-equivalent to ``M`` that is in echelon form. Note
that echelon form of a matrix is *not* unique, however, properties like the
row space and the null space are preserved.
Parame... | 5,308,842 |
def maybe_make_dirs(path):
"""Creates the sub directories leading up to the given file.
Args:
path: The path to a file (i.e., the last word in the path is assumed to be a
file, not a directory).
Returns:
The path generated.
"""
dirname = os.path.dirname(path)
if dirname and not f_exists(dirn... | 5,308,843 |
def div23():
"""
Returns the divider 22222222222222222222222
:return: divider23
"""
return divider23 | 5,308,844 |
def datetime_to_timestamp(dt):
"""Converts a `datetime.date` or `datetime.datetime` to milliseconds since
epoch.
Args:
dt: a `datetime.date` or `datetime.datetime`
Returns:
the number of milliseconds since epoch
"""
if type(dt) is date:
dt = datetime(dt.year, dt.month, ... | 5,308,845 |
def show_info(person):
"""Show the personal information of the given person.
# Argument
person: `Person`. The person.
"""
print('name:{}, age:{}'.format(person.name, person.age)) | 5,308,846 |
def update_sov_map():
"""Update sovereignty map from ESI."""
EveSovereigntyMap.objects.update_from_esi() | 5,308,847 |
def get_specific_dummies(df, col_map=None, prefix=None, suffix=None, return_df=True):
""" Given a mapping of column_name: list of values, one hot the values
in the column and concat to dataframe. Optional arguments to add prefixes
and/or suffixes to created column names.
Example col_map: {'foo':['... | 5,308,848 |
def record_params(setup_state):
""" Load used app configs into local config on registration from
server/__init__.py """
app = setup_state.app
oauth_provider.init_app(app) | 5,308,849 |
def upload_processing(self, *args, **kwargs):
"""
Executes on Node. Uploads Forcing results to Central and sends LoggingMessage to Central
Is linked to signals which will send messages back to the central
* failure_handler
* success_handler
:param self:
:param kwargs:
:return:
"""
... | 5,308,850 |
def create_controls(pagesize):
"""
Create an LDAP control with a page size of "pagesize".
"""
if LDAP24API:
return SimplePagedResultsControl(True, size=pagesize, cookie='')
else:
return SimplePagedResultsControl(ldap.LDAP_CONTROL_PAGE_OID, True,
... | 5,308,851 |
def threshold_measurement(state, instruction, shots):
"""
NOTE: This function calculates only by using torontonian.
"""
if not np.allclose(state.xpxp_mean_vector, np.zeros_like(state.xpxp_mean_vector)):
raise NotImplementedError(
"Threshold measurement for displaced states are not s... | 5,308,852 |
def white(N, sigma=1, prng=None):
""" Create white noise.
Parameters
---------
N : numeric
Length of 1d noise array to return
sigma : numeric
Standard deviation
prng : np.random.RandomState, None
A RandomState instance, or None
"""
prng = process_prng(pr... | 5,308,853 |
def toggle_small_cell_mode():
"""
Toggle between two different behaviours for when cell is smaller than r_cut/2:
1. clip cell - some neigbours may be lost (default)
2. replicate cell along narrow directions
"""
gcv().toggle_small_cell_mode() | 5,308,854 |
def test_pikk_shuffle():
"""
Test PIKK shuffling
"""
ff = fake_generator()
sam = pikk(5, 5, prng=ff)
assert (sam == [1, 2, 3, 4, 5]).all()
ff = fake_generator()
sam = random_permutation(5, method="random_sort", prng=ff)
assert (sam+1 == [1, 2, 3, 4, 5]).all() | 5,308,855 |
def stop_container(container_id):
"""
Stop a running w3af container
"""
try:
subprocess.check_output('docker stop %s' % container_id, shell=True)
except subprocess.CalledProcessError, cpe:
print('w3af container failed to stop: "%s"' % cpe)
sys.exit(1) | 5,308,856 |
def get_sequence(
series: pd.Series, path_to_pdb: Path
) -> Tuple[str, str, int, int, List[int]]:
"""Gets a sequence of from PDB file, CATH fragment indexes and secondary structure labels.
Parameters
----------
series: pd.Series
Series containing one CATH instance.
path_to_assemblies:Pa... | 5,308,857 |
def upload_file(parameters):
"""Based on uploadFileAsync. Note that this doesn't take
index because we don't need it to do HTTP requests like the typescript code
does."""
# Skip gzip as it is unneeded for now.
total_file_size = os.path.getsize(parameters['file'].absolute_file_path)
if not upload_chunk(param... | 5,308,858 |
def generate_without_options():
"""
Returns 1 to 6 Pokemon based on default generator values
"""
# Generator chooses how many Pokemon to generate
number_of_pokemon = randint(1,6)
try:
api_response = _send_api_request(num_pokemon=number_of_pokemon)
except:
return statement(re... | 5,308,859 |
def fit_harmonic_decay(data, deltat=1.0, numcoef=DEFCOEF, axis=-1):
"""Fit harmonic functions with exponential decay.
Can be used to fit frequency-domain fluorescence image data with
photobleaching.
Parameters
----------
data : array_like
Experimental data (observed values of the depen... | 5,308,860 |
def lab_to_lch(lab):
"""Din99o Lab to Lch."""
l, a, b = lab
h = math.degrees(math.atan2(b, a))
c = math.sqrt(a ** 2 + b ** 2)
# Achromatic colors will often get extremely close, but not quite hit zero.
# Essentially, we want to discard noise through rounding and such.
if c <= ACHROMATIC_TH... | 5,308,861 |
def test_md018_good_with_setext_headings():
"""
Test to make sure this rule does not trigger with a document that
contains a possible Atx Headings without the proper space at the start
if contained within a SetExt Heading.
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = [... | 5,308,862 |
def moments(data, n_neighbors=30, n_pcs=30, mode='connectivities', method='umap', metric='euclidean', use_rep=None,
recurse_neighbors=False, renormalize=False, copy=False):
"""Computes moments for velocity estimation.
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated dat... | 5,308,863 |
def QuadRemeshAsync1(thisMesh, parameters, guideCurves, progress, cancelToken, multiple=False):
"""
Quad remesh this mesh asynchronously.
Args:
guideCurves (IEnumerable<Curve>): A curve array used to influence mesh face layout
The curves should touch the input mesh
Set Guide... | 5,308,864 |
def are_close(col1, col2):
"""This function used to compare values of collections with numeric data
"""
if len(col1) != len(col2):
raise ValueError("Different size of input collections")
result = []
for x, y in zip(col1, col2):
result.append(abs(abs(x) - abs(y)) < 0.4)
r = T... | 5,308,865 |
def compute_depression(input_dem, scale_factor=1, curvature_percentile=75, return_polygon=True, alpha=0.5):
"""
Compute depressions and return a new image with largest depressions filled in.
Parameters
----------
input_dem : np.array, rd.rdarray
2d array of elevation DNs, a DEM
... | 5,308,866 |
def _deregister_ec2_instance(
public_address: str, require_no_running_jobs: bool, region_name: str
) -> bool:
"""
Deregisters an EC2 instance. If require_no_running_jobs is true, then only
deregisters if there are no currently running jobs on the instance. If
require_no_running_jobs is false, we wil... | 5,308,867 |
def disable_x64():
"""Experimental context manager to temporarily disable X64 mode.
Usage::
>>> import jax.numpy as jnp
>>> with disable_x64():
... print(jnp.arange(10.0).dtype)
...
float32
See Also
--------
jax.experimental.enable_x64 : temporarily enable X64 mode.
"""
_x64_state... | 5,308,868 |
def build_tocs(app, pagename, templatename, context, doctree):
"""Injects the global and local Tables of Contents into the HTML context.
Args:
app: The Sphinx application.
pagename (str): The name of the current page.
templatename (str): The name of the template used to render the page.... | 5,308,869 |
def convert(n):
"""convert(n) -> Integer""" # TODO
try:
for character in n:
if character in roman_numbers:
return "Roman"
except:
return "Arabic" | 5,308,870 |
def mse(pred, labs):
"""
Calculates MSE
:param pred: sequence of Strings / predicted score values as strings
:param labs: sequence of Strings / true score values as strings
:return: (Int, Int) / MSE of valid samples AND number of invalid samples
"""
idx = np.where(np.array([isfloat(x) for x ... | 5,308,871 |
def main():
"""Preusmeri na index"""
redirect("/index/") | 5,308,872 |
def described_field_type(singular_type_field):
"""
Human readable equivalent of a singular avro type - e.g. long -> number.
"""
if isinstance(singular_type_field, dict):
if "logicalType" in singular_type_field:
return singular_type_field["logicalType"]
else:
if si... | 5,308,873 |
def findFile(ext="", directory=c.DIRECTORY_PROCESSING):
"""
To find a file given extension and return is name.
"""
name = ""
if ext == "":
# Return the first file in the directory that is not crypted
for f in os.listdir(directory):
if not (f.endswith("kat")):
... | 5,308,874 |
def package_releases(name, show_hidden=True):
"""return a list of package releases"""
return pypi.package_releases(name, show_hidden) | 5,308,875 |
def _randomize_network(network, keep):
"""
This function returns a network with the same nodes and edge number as the input network.
However, each edge is placed randomly.
:param network: NetworkX object
:param keep: List of conserved edges
:return: Randomized network
"""
null = nx.Grap... | 5,308,876 |
def update_sys_path(path):
"""Temporarily add path to sys.path."""
sys.path.append(path)
yield sys.path
sys.path.remove(path) | 5,308,877 |
def get_docstring(value, module_name=None):
"""
Return the docstring for the given value; or C{None} if it
does not have a docstring.
@rtype: C{unicode}
"""
docstring = getattr(value, '__doc__', None)
if docstring is None:
return None
elif isinstance(docstring, six.text_type):
... | 5,308,878 |
def rescale(gray_img, min_value=0, max_value=255):
"""Rescale image.
Inputs:
gray_img = Grayscale image data
min_value = (optional) new minimum value for range of interest. default = 0
max_value = (optional) new maximum value for range of interest. default = 255
Returns:
... | 5,308,879 |
def _classswitch_file(url, header, params):
"""
文件存储类型转换请求
:param url:string类型,文件存储类型转换的url
:param header: dict类型,http 请求header,键值对类型分别为string,比如{'User-Agent': 'Google Chrome'}
:param params: dict类型,http 请求的查询参数,键值对类型分别为string类型
:return: ret: return message, None if response status code not in ... | 5,308,880 |
def cofa(session=None):
"""
Return location class of current COFA.
Parameters
----------
session: db session to use
"""
h = Handling(session)
located = h.cofa()
h.close()
return located | 5,308,881 |
def identity(*args, **kwargs):
"""
An identity function used as a default task to test the timing of.
"""
return args, kwargs | 5,308,882 |
def _with_largest_possible_masks(oneof):
"""Add masks to enable all possible ops / filters in the search space."""
if oneof.tag == basic_specs.OP_TAG:
n = len(oneof.choices)
mask = tf.constant([1 / n] * n, dtype=tf.float32)
elif oneof.tag == basic_specs.FILTERS_TAG:
largest_index = None
for i, cho... | 5,308,883 |
def list_merger_list0(*lists):
"""Picks leading list, discards everything else"""
return lists[0] | 5,308,884 |
def serialize():
"""
Get dict with internal data
"""
with _exception_log_lock:
return {'exceptions': _exceptions.copy()} | 5,308,885 |
def cmp(a,b):
"""3-way comparison like the cmp operator in perl"""
if a is None:
a = ''
if b is None:
b = ''
return (a > b) - (a < b) | 5,308,886 |
async def test_user_connection_failed(opp, mrp_device, pairing_mock):
"""Test error message when connection to device fails."""
pairing_mock.begin.side_effect = exceptions.ConnectionFailedError
result = await opp.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}... | 5,308,887 |
def _pixel_to_map(coordinates, geotransform):
"""Apply a geographical transformation to return map coordinates from
pixel coordinates.
Parameters
----------
coordinates : :class:`numpy:numpy.ndarray`
2d array of pixel coordinates
geotransform : :class:`numpy:numpy.ndarray`
geogr... | 5,308,888 |
def test_affinity_group_reader_with_assigned_vms_no_order():
"""
Test that reading of `vms` attribute of affinity group reads the `href`
of the link as well as content of the `vms` element. Test it's
correctly processed when link is provided after 'vms' element.
"""
reader = XmlReader(make_buffe... | 5,308,889 |
def median_filter(ts: pd.Series, stats: pd.DataFrame = None,
second_pass=False):
"""Apply rolling median filter to time series"""
_ts = ts.dropna() # Make sure there are no empty values
filtered = _ts.copy()
# Assing rolling median from 2nd to 2nd last index
filtered.iloc[1:-1] ... | 5,308,890 |
def calculate_pairwise_correlations(df_variable: pd.DataFrame) -> dict:
"""For each pair of modalities, calculate correlations, and put them together into a column"""
modalities = list(df_variable.columns.values)
df_dict = {}
modality_iterator = itt.combinations(modalit... | 5,308,891 |
def nullify_notifications(href: str, ghost_user: User):
"""
"Nullify" (e.g. clean information) notifications by href
:param href: The nullified href
:param ghost_user: The "ghost" user to assign notifier or owner to
"""
for n in Notification.objects(notifying_href=href):
n.notifier = gh... | 5,308,892 |
def event_context_vars(env_deployment):
"""Return context variables for zaza-events configuration params.
Note that it is cached because env_deployment is immutable, and the date
should only be evaluated the first time.
The "bundle" var is derived from the first model if there is only ONE
model, o... | 5,308,893 |
def main():
"""
Read json and write Steam vdf conversion
"""
import sys
import argparse
parser = argparse.ArgumentParser(prog='json2vdf', description=main.__doc__)
parser.add_argument('-i', '--input',
default=sys.stdin,
type=argparse.FileType('... | 5,308,894 |
def generate_random_string(length):
"""Generates a random string of the specified length.
Args:
length: int. Length of the string to be generated.
Returns:
str. Random string of specified length.
"""
return base64.urlsafe_b64encode(os.urandom(length)) | 5,308,895 |
def update_model(model, player, winner, board_hist, move_hist, learnig_rate):
"""
Updates 2 layer policy network weights using gradient descent (policy gradients) according to the played game data.
Parameters
----------
model: dict {"W1": [numpy Hx9 array], "W2": [numpy 9xH array]}
Policy n... | 5,308,896 |
def eval_():
"""evaluation"""
config.mindrecord_dir = os.path.join(config.coco_root, config.mindrecord_dir)
print('\neval.py config:\n', config)
prefix = "TextFuseNet_eval.mindrecord"
mindrecord_dir = config.mindrecord_dir
mindrecord_file = os.path.join(mindrecord_dir, prefix)
if not os.path... | 5,308,897 |
def init(base_url, username=None, password=None, verify=True):
"""Initialize ubersmith API module with HTTP request handler."""
handler = RequestHandler(base_url, username, password, verify)
set_default_request_handler(handler)
return handler | 5,308,898 |
def view_mol(option, maps=None, out_put=None, target_id=None, extra=None):
"""Function to render the 3D coordinates of a molecule
Takes a PDB code as input
Returns an SD block"""
my_mols = Molecule.objects.filter(prot_id__code=option)
new_mol = ""
for mol in my_mols:
new_mol += (str(mol.... | 5,308,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.