content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def update(boardData):
"""This function is called by the game to inform the ai of any changes that have occored on the game board"""
pass | 37,900 |
def hook_StreamInt(state, level, format_ea, unpack_ea, uint64_ea):
"""Implements _DeepState_StreamInt, which gives us an integer to stream, and
the format to use for streaming."""
DeepManticore(state).api_stream_int(level, format_ea, unpack_ea, uint64_ea) | 37,901 |
def get_local_server_dir(subdir = None):
"""
Get the directory at the root of the venv.
:param subdir:
:return:
"""
figures_dir = os.path.abspath(os.path.join(sys.executable, '..', '..', '..'))
if subdir is not None:
figures_dir = os.path.join(figures_dir, subdir)
return figures_... | 37,902 |
def register():
"""
Method POST
Form:
- oid int
- token char[40]
"""
uid = g.user.uid
oid = get_int_field("oid")
token = get_str_field("token")
activity = Activity.get_latest_activity()
aid = activity.aid
if token != activity.token:
raise Inva... | 37,903 |
def extract_sequence(sent,
annotations,
sources,
label_indices):
"""
Convert the annotations of a spacy document into an array of observations of shape
(nb_sources, nb_bio_labels)
"""
sequence = torch.zeros([len(sent), len(sources), len(... | 37,904 |
def extract_retained_intron(denovo_dir, tophat_dir, pAplus_dir, output_dir):
"""
Check each intron and fetch PIR
Modified from Braunschweig et al., Genome Research, 2014, gr-177790.
"""
print('Start to parse circular RNA introns...')
# set path
fusion_f = '%s/circularRNA_full.txt' % denovo_d... | 37,905 |
def is_valid_password_1(password):
"""
>>> is_valid_password_1("111111")
True
>>> is_valid_password_1("223450")
False
>>> is_valid_password_1("123789")
False
"""
has_double = any(password[c] == password[c+1] for c in range(len(password)-1))
is_ascending = all(password[c] <= passw... | 37,906 |
def mean(x, axis=None, keepdims=False):
"""Mean of a tensor, alongside the specified axis.
Parameters
----------
x: A tensor or variable.
axis: A list of integer. Axes to compute the mean.
keepdims: A boolean, whether to keep the dimensions or not.
If keepdims is False, the rank of the tensor is reduce... | 37,907 |
def frame_pass_valid_sample_criteria(frame, image_type):
"""Returns whether a frame matches type criteria"""
return frame_image_type_match(frame, image_type) | 37,908 |
def test_importvalue():
"""Test Fn.ImportValue function."""
assert Fn.ImportValue(
Fn.Sub("${NetworkStackNameParameter}-SecurityGroupID")
).render() == {
"Fn::ImportValue": {"Fn::Sub": "${NetworkStackNameParameter}-SecurityGroupID"}
} | 37,909 |
def embed(tokenizer, text):
"""
Embeds a text sequence using BERT tokenizer
:param text: text to be embedded
:return: embedded sequence (text -> tokens -> ids)
"""
return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text)) | 37,910 |
def exponent_fmt(x, pos):
""" The two args are the value and tick position. """
return '{0:.0f}'.format(10 ** x) | 37,911 |
def test_immi2():
"""
Test immi on synergistic distribution.
"""
d = bivariates['synergy']
red = i_mmi(d, ((0,), (1,)), (2,))
assert red == pytest.approx(0) | 37,912 |
def test_standard_codec_name_round_trip(name: str) -> None:
"""Test standard name -> Python name -> standard name cycle."""
codec_info = codecs.lookup(name)
assert standard_codec_name(codec_info.name) == name | 37,913 |
def close_review_request(review_request, review_request_id, description):
"""Closes the specified review request as submitted."""
if review_request.status == ReviewRequest.SUBMITTED:
logging.warning('Review request #%s is already submitted.',
review_request_id)
return
... | 37,914 |
def _unpack(arr, extent, order='C'):
"""
This is a helper method that handles the initial unpacking of a data array.
ParaView and VTK use Fortran packing so this is convert data saved in
C packing to Fortran packing.
"""
n1,n2,n3 = extent[0],extent[1],extent[2]
if order == 'C':
arr =... | 37,915 |
def unzip(list):
"""unzip the tensor tuple list
Args:
list: contains tuple of segemented tensors
"""
T, loss = zip(*list)
T = torch.cat(T)
mean_loss = torch.cat(loss).mean()
return T, mean_loss | 37,916 |
def ergs_to_lsun(luminosity):
"""
From luminostiy in erg/s to Lsun
"""
lum = u.Quantity(luminosity, u.erg / u.s)
return lum.to(u.L_sun) | 37,917 |
def decode(code, P):
"""
Decode an RNS representation array into decimal number
:param P: list of moduli in order from bigger to smaller [pn, .., p2, p1, p0]
>>> decode(code=[5, 3, 1], P=[7,6,5])
201
"""
lcms = np.fromiter(accumulate(P[::-1], np.lcm), int)[::-1]
n = code[-1] % P[-1]
... | 37,918 |
def test_fit_interpolated_torsion():
"""
Make sure an error is raised if we try and fit an interpolated torsion.
"""
ff = ForceFieldEditor(force_field="openff_unconstrained-1.3.0.offxml")
# add an interploated general parameter
parameter = ff.force_field["ProperTorsions"].parameters[0]
param... | 37,919 |
def is_collection(obj):
"""
Check if a object is iterable.
:return: Result of check.
:rtype: bool
"""
return hasattr(obj, '__iter__') and not isinstance(obj, str) | 37,920 |
def link(controller: CRUDController, base: pymongo.database.Database):
"""
Link controller related collection to provided database.
:param base: As returned by layabase.load function
"""
if controller.history:
import layabase._versioning_mongo
crud_model = layabase._versioning_mong... | 37,921 |
def write_instance_to_example_files(instances, tokenizer, max_seq_length,
writers, estimator):
"""Create TF example files from `TrainingInstance`s."""
token_map_size = int(max_seq_length / 2)
writer_index = 0
total_written = 0
pretrain_emb = get_pretrained_embeddings(estimator, instances, tokeni... | 37,922 |
def file_md5(fpath):
"""Return the MD5 digest for the given file"""
with open(fpath,'rb') as f:
m = hashlib.md5()
while True:
s = f.read(4096)
if not s:
break
m.update(s)
return m.hexdigest() | 37,923 |
def log_roc_auc(y_true, y_pred, experiment=None, channel_name='metric_charts', prefix=''):
"""Creates and logs ROC AUC curve and ROCAUC score to Neptune.
Args:
y_true (array-like, shape (n_samples)): Ground truth (correct) target values.
y_pred (array-like, shape (n_samples, 2)): Predictions fo... | 37,924 |
def strip_path(full_path):
"""Returns the filename part of full_path with any directory path removed.
:meta private:
"""
return os.path.basename(full_path) | 37,925 |
async def test_update_off(hass, remote, mock_now):
"""Testing update tv off."""
await setup_samsungtv(hass, MOCK_CONFIG)
remote.control = mock.Mock(side_effect=OSError("Boom"))
next_update = mock_now + timedelta(minutes=5)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
... | 37,926 |
def update():
"""
Updates the Database
Returns
-------
None.
"""
os.system("git submodule update --recursive --remote")
return None
# %% Load USA data | 37,927 |
def move(column, player):
"""Apply player move to the given column"""
index = _index_of(column, None)
if index < 0:
print('Entire column is occupied')
return False
column[index] = player
return True | 37,928 |
def error_test_task():
"""
This is a mock task designed to test that we properly report errors to the client.
"""
raise Exception("I'm sorry Dave, I'm afraid I can't do that.") | 37,929 |
def case_undo_negative():
"""
CommandLine:
python -m wbia.algo.graph.tests.dyn_cases case_undo_negative --show
Example:
>>> # ENABLE_DOCTEST
>>> from wbia.algo.graph.tests.dyn_cases import * # NOQA
>>> case_undo_negative()
"""
ccs = [[1], [2]]
edges = [
... | 37,930 |
def q_2(input_file, output_file):
"""
Performs a histogram equalization on the input image.
"""
img = cv2.imread(input_file, cv2.IMREAD_GRAYSCALE)
(height, width) = img.shape[:2]
# Analysing original image and original histogram
# original_hist = cv2.calcHist([img], [0], None, [256], [0... | 37,931 |
def calculate_costs(points, centric_point):
""" Returns the accumulated costs of all point in `points` from the centric_point """
if len(points) == 1:
return points[0].hyp()
_part = (points - centric_point)**2
_fin = []
for point in _part:
_fin.append(point.hyp())
return (np.array(_fin)).sum() | 37,932 |
def formatUs(time):
"""Format human readable time (input in us)."""
if time < 1000:
return f"{time:.2f} us"
time = time / 1000
if time < 1000:
return f"{time:.2f} ms"
time = time / 1000
return f"{time:.2f} s" | 37,933 |
def parse_annotations(ann_filepath: str) -> Dict[int, List[Label]]:
"""Parse annotation file into List of Scalabel Label type per frame."""
outputs = defaultdict(list)
for line in load_file_as_list(ann_filepath):
gt = line.strip().split(",")
class_id = gt[7]
if class_id not in NAME_M... | 37,934 |
def unpark(id: int):
"""
Remove an account from database.
"""
airplane = crud.airplane_by_id(db, id)
crud.destroy_airplane(db, airplane)
console.print(f"{airplane.id} was unparked!") | 37,935 |
def bel_graph_loader(from_dir: str) -> BELGraph:
"""Obtains a combined BELGraph from all the BEL documents in one folder.
:param from_dir: The folder with the BEL documents.
:return: A corresponding BEL Graph.
"""
logger.info("Loading BEL Graph.")
files = [
os.path.join(from_dir, file)
... | 37,936 |
def test_arc_segment_constructor():
"""Test the arc segment constructor."""
points = [[3, 6, 6], [3, 6, 3]]
segment_cw = geo.ArcSegment(points, False)
segment_ccw = geo.ArcSegment(points, True)
check_arc_segment_values(
segment=segment_cw,
point_start=[3, 3],
point_end=[6, 6... | 37,937 |
def apply(lang1: Dict[List[str], float], lang2: Dict[List[str], float], parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> float:
"""
Calculates the EMD distance between the two stochastic languages
Parameters
-------------
lang1
First language
lang2
Second langu... | 37,938 |
def reInpainting(image, ground_truth, teethColor):
"""
if pixel has pink color (marked for teeth) and not in range of teeth => fill by teethColor
"""
isTeeth, isNotTeeth = 0, 0
threshold = calculateThreshhold(image, teethColor)
# print(f"Threshold: {threshold}")
for i in range(0, image.s... | 37,939 |
def data_for_cylinder_along_z(center_x, center_y, radius, height_z):
"""
Method for creating grid for cylinder drawing. Cylinder will be created along Z axis
:param center_x: Euclidean 3 dimensional center of drawing on X axis
:param center_y: Euclidean 3 dimensional center of drawing on Y axis
:par... | 37,940 |
def install_resourcemanager(namenode):
"""Install if the namenode has sent its FQDN.
We only need the namenode FQDN to perform the RM install, so poll for
namenodes() data whenever we have a namenode relation. This allows us to
install asap, even if 'namenode.ready' is not set yet.
"""
if namen... | 37,941 |
def parse_sh_sys_resources(switch_ip, cmd_body, per_switch_stats_dict):
"""
show system resources
"""
if user_args['cli_json']:
parse_sh_sys_resources_json(switch_ip, cmd_body, per_switch_stats_dict)
return
logger.info('parse_sh_sys_resources for %s', switch_ip)
# Load average:... | 37,942 |
def _configure_learning_rate(num_samples_per_epoch, global_step):
"""Configures the learning rate.
Args:
num_samples_per_epoch: The number of samples in each epoch of training.
global_step: The global_step tensor.
Returns:
A `Tensor` representing the learning rate.
Raises:
ValueError: if
""... | 37,943 |
def cpm(adata: ad.AnnData) -> ad.AnnData:
"""Normalize data to counts per million."""
_cpm(adata)
return adata | 37,944 |
def argon2_key(encryption_password, salt):
"""
Generates an encryption key from a password using the Argon2id KDF.
"""
return argon2.low_level.hash_secret_raw(encryption_password.encode('utf-8'), salt,
time_cost=RFC_9106_LOW_MEMORY.time_cost, memory_cost=RFC_9106_LOW_MEMORY.memory_cost,
... | 37,945 |
def main():
"""
May be used for manual testing if needed
"""
config = AmbariConfig().getConfig()
orchestrator = CustomServiceOrchestrator(config)
config.set('agent', 'prefix', "/tmp")
command = {
"serviceName" : "HBASE",
"role" : "HBASE_MASTER",
"stackName" : "HDP",
"stackVersion" : "1.2.0... | 37,946 |
def test_rng_init(instance_generator):
"""Construct a random generator."""
if isinstance(instance_generator, ecole.instance.FileGenerator):
pytest.skip("No dataset in default directory")
type(instance_generator)(rng=ecole.RandomGenerator()) | 37,947 |
def print_policy_analysis(policies, game, verbose=False):
"""Function printing policy diversity within game's known policies.
Warning : only works with deterministic policies.
Args:
policies: List of list of policies (One list per game player)
game: OpenSpiel game object.
verbose: Whether to print po... | 37,948 |
def model_fn(is_training=True, **params):
"""
Create base model with MobileNetV2 + Dense layer (n class).
Wrap up with CustomModel process.
Args:
is_training (bool): if it is going to be trained or not
params: keyword arguments (parameters dictionary)
"""
baseModel = MobileNetV2... | 37,949 |
def make_arg_parser():
"""
Create the argument parser.
"""
parser = argparse.ArgumentParser(description="Scrap WHOIS data.")
parser.add_argument("--config", help="uwhoisd configuration")
parser.add_argument(
"--log",
default="warning",
choices=["critical", "error", "warni... | 37,950 |
def roundToElement(dateTime, unit):
""" Returns a copy of dateTime rounded to given unit
:param datetime.datetime: date time object
:param DtUnit unit: unit
:return: datetime.datetime
"""
year = dateTime.year
month = dateTime.month
day = dateTime.day
hour = dateTime.hour
minute ... | 37,951 |
def tuple_factory(colnames, rows):
"""
Returns each row as a tuple
Example::
>>> from cassandra.query import tuple_factory
>>> session = cluster.connect('mykeyspace')
>>> session.row_factory = tuple_factory
>>> rows = session.execute("SELECT name, age FROM users LIMIT 1")
... | 37,952 |
def delete_the_deletables(
text_widget: tkinter.Text,
index1: str,
index2: str,
delete_func: Callable[[str, str], None],
) -> None:
"""
Delete the deletable content in the given range ``(index1, index2)``.
The sealed blocks in the range are preserved.
"""
deletables = pin_deletable_... | 37,953 |
async def test_generate_raceplan_for_event_missing_intervals(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
event: dict,
format_configuration: dict,
raceclasses: List[dict],
request_body: dict,
) -> None:
"""Should return 400 Bad Request."""
format_configuration_missi... | 37,954 |
def is_error(splunk_record_key):
"""Return True if the given string is an error key.
:param splunk_record key: The string to check
:type splunk_record_key: str
:rtype: bool
"""
return splunk_record_key == 'error' | 37,955 |
def test_remove_slot(slotter_obj):
""" Test slot removal """
slot_obj = slotter_obj.add_slot(30, 40)
assert slot_obj
removed = slotter_obj.remove_slot(slot_obj)
assert removed
removed = slotter_obj.remove_slot(Slot(100,200))
assert removed is False | 37,956 |
def parse_network_info(net_bond, response_json):
"""
Build the network info
"""
out_dict = {}
ip_list = []
node_count = 0
# Build individual node information
for node_result in response_json['result']['nodes']:
for node in response_json['result']['nodes']:
if node['no... | 37,957 |
async def create_or_update(hub, ctx, name, resource_group, **kwargs):
"""
.. versionadded:: 1.0.0
Create or update a network security group.
:param name: The name of the network security group to create.
:param resource_group: The resource group name assigned to the
network security group... | 37,958 |
def download_media_suite(req, domain, app_id):
"""
See Application.create_media_suite
"""
return HttpResponse(
req.app.create_media_suite()
) | 37,959 |
def non_numeric(string: str) -> str:
""" Removes all numbers from the string """
return ''.join(letter for letter in string if not letter.isdigit()) | 37,960 |
def prepare_xs(path, numbergroup=1):
"""Prepare the needed representation of cross-section data
Paramteres:
-----------
path : str
filename of cross-section data
numbergroup : int
number of energies neutron multigroup
Returns:
--------
energies : iterable of str
... | 37,961 |
def shiftField(field, dz):
"""Shifts the z-coordinate of the field by dz"""
for f in field:
if f.ID == 'Polar Data':
f.set_RPhiZ(f.r, f.phi, f.z + dz)
elif f.ID == 'Cartesian Data':
f.set_XYZ(f.x, f.y, f.z + dz)
return field | 37,962 |
def pair_equality(dataframe, column_1, column_2, new_feature_name):
"""
Adds a new binary feature to an existing dataframe which, for every row,
is 1 if and only if that row has equal values in two given columns.
:param dataframe:
Dataframe to add feature to
:param column_1:
Name of... | 37,963 |
def compute_diagram(PhenosObj, FnameJson=None, FnameImage=None, Silent=False):
"""
todo: finish code
todo: add unit tests
computes the phenotype diagram from the phenotypes object obtained from :ref:`phenotypes_compute_json`.
save the diagram as json data with *FnameJson*. useful for e.g. manually ... | 37,964 |
def identity_block(input_tensor, kernel_size, filters, stage, block):
"""The identity block is the block that has no conv layer at shortcut.
# Arguments
input_tensor: input tensor
kernel_size: default 3, the kernel size of middle conv layer at main path
filters: list of integers, the fil... | 37,965 |
def find_linux_kernel_memory(
pml4: PageTable, mem: Memory, mem_range: Interval
) -> Optional[MappedMemory]:
"""
Return virtual and physical memory
"""
# TODO: skip first level in page tables to speed up the search
# i = get_index(mem_range.begin, 0)
# pdt = page_table(mem, pml4.entries[i] &... | 37,966 |
def test_get_coreconfig_atomic_number(number, econf):
"""
Test of the get_econfig function with element names
"""
from masci_tools.util.econfig import get_coreconfig
res = get_coreconfig(number)
assert res == econf | 37,967 |
def cnn_encoder(inputs, is_train=True, reuse=False, name='cnnftxt', return_h3=False):
""" 64x64 --> t_dim, for text-image mapping """
w_init = tf.random_normal_initializer(stddev=0.02)
gamma_init = tf.random_normal_initializer(1., 0.02)
df_dim = 64
with tf.variable_scope(name, reuse=reuse):
... | 37,968 |
def cmp_id(cls1, cls2, idx1, idx2):
"""Compare same particles between two clusters and output numbers
Parameters
----------
cls1,cls2: Cluster object
idx1,idx2: Indices of detected particles in the clusters.
Output
------
The number of same particles.
"""
partId1 = ... | 37,969 |
def get_clinical_cup():
"""
Returns tuple with clinical cup description
"""
return ("8", "2", "M", "01", 25) | 37,970 |
def to_utm_bbox(bbox: BBox) -> BBox:
"""Transform bbox into UTM CRS
:param bbox: bounding box
:return: bounding box in UTM CRS
"""
if CRS.is_utm(bbox.crs):
return bbox
lng, lat = bbox.middle
utm_crs = get_utm_crs(lng, lat, source_crs=bbox.crs)
return bbox.transform(utm_crs) | 37,971 |
async def help_(event, *command_name):
"""Help command. Run `help (command name)` for more information on a specific command.
**Example usage**
* `help`
* `help ping`
* `help info`
"""
if command_name:
parent = event.processor
for token in command_name:
cmd = pa... | 37,972 |
def evaluate(model, docs, nb_samples=100, topn=10):
"""Evaluate the model in terms of similarity of documents."""
mean, stdev, topn_ratio, top1_ratio, nb_samples = rank_to_self(docs, model, nb_samples=nb_samples, topn=topn)
print("similarity to self ({} samples)".format(nb_samples))
print("within top-{}... | 37,973 |
def check(**kwargs: dict) -> None:
"""Updates or deletes proxies once checked
Args:
kwargs [dict]: keyword arguments passed to <Proxy> filter
"""
logger.info("Commencing all available proxy check...")
proxies = get_proxies(**kwargs)
obj = Check.objects.create()
if proxies:
o... | 37,974 |
def run(results: list):
"""
Scan the above specified networks with Nmap and process the results.
"""
global CREATED_FILES, LOGGER
# setup logger
LOGGER = logging.getLogger(__name__)
LOGGER.info("Setting up Nmap scan")
# use Nmap
nmap_call = create_nmap_call()
call_nmap(nmap_ca... | 37,975 |
def define_actions(action):
"""
Define the list of actions we are using.
Args
action: String with the passed action. Could be "all"
Returns
actions: List of strings of actions
Raises
ValueError if the action is not included in H3.6M
"""
actions = ["walking", "wiping", "lifting", "co-exis... | 37,976 |
def gen_order_history_sequence(uid, history_grouped, has_history_flag):
""" 用户订单历史结果构成的序列 """
# 311 天的操作记录
sequence = ['0'] * 311
if has_history_flag == 0:
return sequence
df = history_grouped[uid]
for i in df['days_from_now']:
sequence[i] = str(df[df['days_from_now'] == i].shap... | 37,977 |
def suggest_attribute_as_typo(attribute, attributes):
"""Suggest the attribute could be a typo.
Example: 'a.do_baf()' -> 'a.do_bar()'.
"""
for name in get_close_matches(attribute, attributes):
# Handle Private name mangling
if name.startswith('_') and '__' in name and not name.endswith(... | 37,978 |
def _get_plugin_type_ids():
"""Get the ID of each of Pulp's plugins.
Each Pulp plugin adds one (or more?) content unit type to Pulp. Each of
these content unit types is identified by a certain unique identifier. For
example, the `Python type`_ has an ID of ``python_package``.
:returns: A set of pl... | 37,979 |
def scale_48vcurrent(value, reverse=False, pcb_version=0):
"""
Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw
value to Amps (if reverse=False), or convert a value in Amps to raw (if reverse=True).
For now, raw values are hundredths of a... | 37,980 |
def get_graph(graph_name):
"""Return graph, input can be string with the file name (reuse previous created graph),
or a variable containing the graph itself"""
# open file if its a string, or just pass the graph variable
if '.p' not in graph_name:
graph_name = add_extension(graph_name)
if... | 37,981 |
def max_function(context, nodeset, string):
"""
The dyn:max function calculates the maximum value for the nodes passed as
the first argument, where the value of each node is calculated dynamically
using an XPath expression passed as a string as the second argument.
http://www.exslt.org/dyn/function... | 37,982 |
def get_transfer_encodings():
"""Return a list of supported content-transfer-encoding values."""
return transfer_decoding_wrappers.keys() | 37,983 |
def is_name_valid(name: str, rules: list) -> bool:
""" Determine whether a name corresponds to a named rule. """
for rule in rules:
if rule.name == name:
return True
return False | 37,984 |
def test_formatting(sample_user: User):
"""Verify that user formatting works."""
user_json = sample_user.to_json()
assert 'id' not in user_json | 37,985 |
def fig2data(fig, imsize):
"""
:param fig: Matplotlib figure
:param imsize:
:return:
"""
canvas = FigureCanvas(fig)
ax = fig.gca()
# ax.text(0.0, 0.0, "Test", fontsize=45)
# ax.axis("off")
canvas.draw()
image = np.fromstring(canvas.tostring_rgb(), dtype="uint8")
width,... | 37,986 |
def draw_agent_trail(img, trail_data, rgb, vision):
""" draw agent trail on the device with given color.
Args:
img : cv2 read image of device.
trail_data : data of trail data of the agent
rgb : (r,g,b) tuple of rgb color
Returns:
img : updated image ... | 37,987 |
def illustrateGraph(graphconfig, promps, IllustrationsDirectory):
"""
Draws the state graph and illustrates the learned promps.
Files get placed in IllustrationsDirectory
"""
if not os.path.exists(IllustrationsDirectory):
os.makedirs(IllustrationsDirectory)
_plotStateGraph(graphconfig, ... | 37,988 |
def get_total_received_items(scorecard):
""" Gets the total number of received shipments in the period (based on Purchase Receipts)"""
supplier = frappe.get_doc('Supplier', scorecard.supplier)
# Look up all PO Items with delivery dates between our dates
data = frappe.db.sql("""
SELECT
SUM(pr_item.received_q... | 37,989 |
def read_addrbook(addrbook, fname):
"""Read existing address book file or creates a new one if fname does not
exist.
"""
try:
with open(fname, "rb") as fopen:
addrbook.ParseFromString(fopen.read())
except IOError:
print("[!] Address book file \"{}\" doesn't exist.".format... | 37,990 |
def noisy_circuit_demo(amplitude_damp):
"""Demonstrates a noisy circuit simulation.
"""
# q = cirq.NamedQubit('q')
q = cirq.LineQubit(0)
dm_circuit = cirq.Circuit(
cirq.X(q),
)
dm_result = cirq.DensityMatrixSimulator(noise=cirq.ConstantQubitNoiseModel(cirq.amplitude_damp(amplitude_d... | 37,991 |
def test_get_all_highest_utilizations() -> None:
"""Tests getting highest utilization when
timestamp is near 'now time'."""
delete_all_collections_datas()
prep_db_if_not_exist()
add_fake_datas(12, 5, False, False)
device_name: str = "fake_device"
iface_name: str = "1/1"
prev_utilizatio... | 37,992 |
def copy_all_files(src_path: str, dst_path: str, exist_ok: bool=True, verbose: bool=False):
"""Will copy everything from `src_path` to `dst_path`.
Both can be a folder path or a file path.
"""
copy_func = shutil.copy2
if verbose:
print("Copying {} -> {}".format(src_path, dst_path))
if o... | 37,993 |
def check_bottom(score: Union[CollegeScoring, HSScoring], seq: Set[str]):
"""Checks if next move is valid in bottom position.
Args:
score: Either CollegeScoring or HSScoring instance.
seq (Dict): HS_SEQUENCES or COLLEGE_SEQUENCES to check the 'score' against.
"""
if score.formatted_lab... | 37,994 |
def generate_default_filters(dispatcher, *args, **kwargs):
"""
Prepare filters
:param dispatcher: for states
:param args:
:param kwargs:
:return:
"""
filters_list = []
for name, filter_data in kwargs.items():
if filter_data is None:
# skip not setted filter name... | 37,995 |
def linear_map(x, init_mat_params=None, init_b=None, mat_func=get_LU_map,
trainable_A=True, trainable_b=True, irange=1e-10,
name='linear_map'):
"""Return the linearly transformed, y^t = x^t * mat_func(mat_params) + b^t,
log determinant of Jacobian and inverse map.
Args:
... | 37,996 |
def e(
tag: str, attrib: t.Dict[str, str] = {}, text: str = "", parent: ET.Element = None
) -> t.Generator[t.Callable[[str, t.Dict[str, str], str], t.Any], None, t.Any]:
"""Create a XML element and pass a new context for sub elements."""
if parent is not None:
element = ET.SubElement(parent, tag, at... | 37,997 |
async def squery(ctx, *, raw: str):
"""Make a simple query"""
try:
raw = json.loads(raw)
except:
raw = {'raw': raw}
res = await ctx.bot.storcord.simple_query(raw)
await ctx.send(repr(res)) | 37,998 |
def isolated_70():
"""
Real Name: b'Isolated 70'
Original Eqn: b'INTEG ( isolation rate symptomatic 70+isolation rate asymptomatic 70-isolated recovery rate 70\\\\ -isolated critical case rate 70, init Isolated 70)'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
retur... | 37,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.