content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
current_dir = pathlib.Path(__file__).parent.absolute()
return (resources.GetResource(f'{current_dir}/ball_in_cup_explore.xml'),
common.ASSETS) | 55,300 |
def _index_argv(argument):
"""Returns the location of the argument in sys.argv, or None.
Since long options can be passed as either '--option value' or '--option=value' we need to check for both forms.
"""
for i, arg in enumerate(sys.argv):
if arg.split('=')[0] == argument:
return i... | 55,301 |
def render_file(path: str, **kwargs):
"""
Renders a file at the specified absolute path. The file can reside
anywhere on the local disk as Cauldron's template environment path
searching is ignored.
:param path:
Absolute path to a template file to render
:param kwargs:
Named argu... | 55,302 |
def find_file(value: str) -> bool:
"""
Find a file in the system explorer.
value: str corresponding to the dbfid (just the int part).
returns True if the file was found, and False otherwise.
"""
# Ensure that the id is a number.
try:
float(value)
except ValueError:
retu... | 55,303 |
async def export_books_csv():
"""export `Book`s to csv file"""
session = Session()
books = session.query(
BookTable.title,
BookTable.author,
BookTable.publisher,
BookTable.shorthand,
BookTable.number,
BookTable.category,
BookTable.isbn,
).all()
... | 55,304 |
def export_videos(videos, email):
"""
Exporting videos is done in a seperate Celery process from the Flask handler.
Args:
videos (array): Array of video objects (See README.md for general idea of formats).
email (string): Email address (string) where a download link of the export results wi... | 55,305 |
def update_requirements():
"""
Update virtual env with requirements packages.
"""
virtualenv.update_requirements() | 55,306 |
def test_slugify():
"""Test the slugify helper method."""
assert slugify(u'Hello world') == u'hello-world'
assert slugify(u'¿Cómo está?') == u'como-esta' | 55,307 |
def install_requirements(context):
"""Install the local package requirements"""
if context.obj.get('target_dir', None) is None:
raise NotInPackageError(context.command.name)
params = ['./bin/pip', 'install', '-r', 'requirements.txt', '--upgrade']
echo('\nRUN: {0}'.format(' '.join(params)), fg='... | 55,308 |
def test_process_line_350_2(pdb_id, bioassembly_id):
"""Make sure that ProcessRemark350 correctly parses bioassembly data in PDBs.
Only validates for the presence of the bioassembly id in bioassembly_data.
"""
pdb_url = DEFAULT_ROUTES["rcsb"](pdb_id, "pdb")
with open_url(pdb_url) as ifh:
da... | 55,309 |
def register_unpack_format(name, extensions, function, extra_args=None,
description=''):
"""Registers an unpack format.
`name` is the name of the format. `extensions` is a list of extensions
corresponding to the format.
`function` is the callable that will be
use... | 55,310 |
def validate_primitive(primitive_json_structure: typing.Dict) -> None:
"""
Validates that the primitive description is valid for the purpose of insertion in the metalearning database.
If not, an exception is raised.
Generally, metalearning database has additional requirements not captured by JSON schem... | 55,311 |
def text_words(tree, show_traces=False):
"""Print just the words in the tree."""
text = []
for node in tree:
if node.is_terminal():
if node.is_trace() and not show_traces:
continue
text.append(node.word)
return ' '.join(text) | 55,312 |
def patch_gevent():
"""Call gevent monkey patch right after ``post_fork``.
"""
global gevent_patched
if gevent_patched:
logger.warn("Gevent is already patched, skipping")
return
if 'threading' in sys.modules:
logger.warn('Threading imported before gevent patching.')
impor... | 55,313 |
def edit_protocol(protocol_id):
"""Edit details of a protocol."""
current_protocol = Protocol.query.filter_by(id=protocol_id).first()
if current_protocol.user != current_user:
flash('Not your protocol!', 'danger')
return redirect('.')
form = ProtocolForm(request.form)
if form.valid... | 55,314 |
def get_win_drives():
""" Return list of detected drives """
assert NT
drives = []
bitmask = windll.kernel32.GetLogicalDrives()
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
if (bitmask & 1) and win32file.GetDriveType('%s:\\' % letter) in DRIVES:
drives.append(letter)
bitma... | 55,315 |
def query_grakn(session, query_object) -> dict:
"""
Purpose:
Gateway to the grakn queries
Args:
session: The Grakn session
query_object: the query_object
Returns:
answers_df_map: Answers to the queries by entity
"""
answers = {}
if query_object.action == "Find... | 55,316 |
def skewa(s):
"""
SKEWA creates augmented skew-symmetric matrix
:param s: 3 or 6 vector
:return: augmented skew-symmetric matrix
SKEWA(V) is an augmented skew-symmetric matrix formed from V.
If V (1x3) then S =
| 0 -v3 v1 |
| v3 0 v2 |
| 0 0 0 |
... | 55,317 |
def test_parse_returns_external_dependency():
"""Test parse returns external dependency."""
assert 'markdown_generator' in parse() | 55,318 |
def generate_server_uuid(input_string):
""" Create your own server_uuid
@param input_string (str): information to be encoded as server_uuid
@returns server_uuid (str): your unique server_uuid
"""
s = hashlib.sha256()
data = (input_string+SALT).encode("utf-8")
s.update(data)
server_uuid =... | 55,319 |
def get_subject_data(layout: BIDSLayout, subject: str):
"""
Gathers subject specific experimental data
"""
# Get the high resolution T1-weighted anatomical MRI scan
"""
In addition to the functional scan, a high resolution T1-weighted anatomical MRI scan was
made (3D gradient echo sequence,... | 55,320 |
def test_upload_move_available_delete_file(client, boto3_session):
"""Test delete a file once project has been made available"""
project_1 = project_row(project_id="file_testing_project")
assert project_1
assert project_1.current_status == "In Progress"
response = client.post(
tests.DDSEndp... | 55,321 |
def multi_point(point_gdf):
"""Create a multi-point GeoDataFrame."""
multi_point = point_gdf.unary_union
out_df = GeoDataFrame(
geometry=GeoSeries(
[multi_point, Point(2, 5), Point(-11, -14), Point(-10, -12)]
),
crs="EPSG:4326",
)
out_df["attr"] = ["tree", "anothe... | 55,322 |
def get_service_auth(context, endpoint, service_auth):
"""Create auth plugin wrapping both user and service auth.
When properly configured and using auth_token middleware,
requests with valid service auth will not fail
if the user token is expired.
Ideally we would use the plugin provided by auth_... | 55,323 |
def download_topo_land(load=True): # pragma: no cover
"""Download topo land dataset.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
Returns
-------
pyvista.Poly... | 55,324 |
def protusion(obverts, obpolygons, minHeight, maxHeight, minTaper, maxTaper):
"""function to generate the protusions"""
verts = []
for vertex in obverts:
verts.append(vertex.co)
for polygon in obpolygons:
if(polygon.select is True):
if(len(polygon.vertices) == 4):
... | 55,325 |
def wait(msg='', exceptions=None, timeout=10):
"""
Decorator to handle generic waiting situations.
Will handle StaleElementReferenceErrors.
:param msg: Error message
:param exceptions: Extra exceptions to handle
:param timeout: time to keep trying (default: 10 seconds)
:return: the result ... | 55,326 |
def transform_skycoordinates_to_radec(df, names, move_to_rad=True):
"""
Transform ``SkyCoordinate`` column to ``sindec``, ``sinra``, ``cosra``.
:param df:
Data frame with ``SkyCoordinate`` column.
:param names:
Iterable with names of columns with ``SkyCoordinate``s.
:param move... | 55,327 |
def rot13(encoded: str) -> str:
"""
>>> rot13("har crefbaar abeznyr crafr dh’ha xvyb-bpgrg rfg étny à 1000 bpgrgf, ha vasbezngvpvra rfg pbainvaph dh’haxvybzèger rfg étny à 1024 zègerf.")
'une personne normale pense qu’un kilo-octet est égal à 1000 octets, un informaticien est convaincu qu’unkilomètre est ég... | 55,328 |
def create_scene(gym, sim, props, assets_biotac, assets_indenters, biotac_offset=0.05, indenter_offset=0.01785938):
"""Create a scene (i.e., ground plane, environments, BioTac actors, and indenter actors)."""
plane_params = gymapi.PlaneParams()
gym.add_ground(sim, plane_params)
env_handles = []
ac... | 55,329 |
def tidyxacts(df):
"""
Fix formats of columns for transactions in dataframe df
Parameters
----------
df : Dataframe
Returns
-------
Date formatted as Date
Amounts as numeric
Top and sub level categories as category
Adds columns for year, month, quarter, week number... | 55,330 |
def ni_parse(*, df_list, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param args: dictionary, used to run flowbyactivity.py
('year' and 'source')
:return: df, parsed and partially formatted to flowbyactivity
... | 55,331 |
def run(dx, Tf, generator="cython", sorder=None, withPlot=True):
"""
Parameters
----------
dx: double
spatial step
Tf: double
final time
generator: pylbm generator
sorder: list
storage order
withPlot: boolean
if True plot the solution otherwise just c... | 55,332 |
def send_ticket_pdf_email(request, order):
"""
Sends a pdf for the tickets in a given order via email on the order.
Parameters:
request (Request): The request object
order (Order): The order to send tickets for
"""
ticket_pdf = generate_ticket_pdf(request, order)
order_basket = get_tick... | 55,333 |
def get_policy(arn: str, configuration: Configuration = None,
secrets: Secrets = None) -> bool:
"""
Get a policy by its ARN
"""
client = aws_client("iam", configuration, secrets)
return client.get_policy(PolicyArn=arn) | 55,334 |
def soft_crossentropy(predicted_logprobs, target_probs):
"""
Cross-entropy loss capable of handling soft target probabilities.
"""
return -(target_probs * predicted_logprobs).sum(1).mean(0) | 55,335 |
def is_slashable_attestation_data(data_1: AttestationData, data_2: AttestationData) -> bool:
"""
Check if ``data_1`` and ``data_2`` are slashable according to Casper FFG rules.
"""
return (
# Double vote
(data_1 != data_2 and data_1.target.epoch == data_2.target.epoch) or
# Surro... | 55,336 |
def temporary_dir(root_dir=None, cleanup=True):
"""
A with-context that creates a temporary directory.
You may specify the following keyword args:
:param str root_dir: The parent directory to create the temporary directory.
:param bool cleanup: Whether or not to clean up the temporary directory.
... | 55,337 |
def compile_lexicon(spec):
"""
Read the lexicon and put into the form of featureized rules.
Use the same datastructure as for the CFG rules, except that
the rhs is a single string.
Note: the format for the lexicon is more rigid than is ideal,
and intolerant of extra/missing whitespace. Fixable, but hardly
wort... | 55,338 |
def trunc(x):
"""
Truncate the values to the integer value without rounding
"""
if isinstance(x, UncertainFunction):
mcpts = np.trunc(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.trunc(x) | 55,339 |
def _mine_store(mine_data, clear=False):
"""
Helper function to store the provided mine data.
This will store either locally in the cache (for masterless setups), or in
the master's cache.
:param dict mine_data: Dictionary with function_name: function_data to store.
:param bool clear: Whether o... | 55,340 |
def _check_residues_are_well_defined(prot: protein.Protein):
"""Checks that all residues contain non-empty atom sets."""
if (prot.atom_mask.sum(axis=-1) == 0).any():
raise ValueError(
"Amber minimization can only be performed on proteins with"
" well-defined residues. This protei... | 55,341 |
def register_extensions(fileextensions, appname):
"""register program with extensions for automatic loading of files"""
prefix = "Software\\Classes\\"
try:
key1 = RegistryCurrentUser('.%s'%fileextensions[0])
except:
print("Could not register file extension(s) - no registry access")
... | 55,342 |
def semivariogram(F, sites, xbin=None, robust=True, trimmed=True, cloud=False, counts=False, se=False):
"""
Classical semivariogram estimator with option for Cressie's robust
estimator. Can also return a semivariogram "cloud".
Parameters
----------
F : ndarray, (N, ...)
One or more sam... | 55,343 |
def wizard():
"""Routine for configuring an insalled volttron instance.
The function interactively sets up the instance for working with volttron
central and the discovery service.
"""
# Start true configuration here.
volttron_home = get_home()
print('\nYour VOLTTRON_HOME currently set to... | 55,344 |
def linelength(x0, y0, x1, y1):
"""Returns the length of the line."""
a = pow(abs(x0 - x1), 2)
b = pow(abs(y0 - y1), 2)
return sqrt(a+b) | 55,345 |
def train_cdmx(config={}, data_tensor=None, Y_trn=None, Y_val=None, trn_weights=None, args=None, param=None, num_classes=2):
"""
Train cdmx neural model
Args:
See other train_*
Returns:
trained model
"""
"""
NOT WORKING CURRENTLY [update code]
label = args['cd... | 55,346 |
def get_table_max_columns_width(table, column_mapping):
""" Returns a list with columns width
Args:
table (list): of dictionaries must correspond to column_mapping
column_mapping (list): of tuples: mapping of final table column names to actual `table keys`
.. code-block:: python
... | 55,347 |
def create_switch_with_ecobee_clear_hold_button(accessory):
"""Define setup button characteristics."""
service = accessory.add_service(ServicesTypes.OUTLET)
setup = service.add_char(CharacteristicsTypes.Vendor.ECOBEE_CLEAR_HOLD)
setup.value = ""
setup.format = "string"
cur_state = service.add... | 55,348 |
def extract_signal(fn):
"""
Extract raw data from the fast5 file.
Important parameter could be scale
If True, returns scaled floating point values in pA
if False, returns raw DAQ values as 16 bit integers
"""
f = Fast5File(fn, "r")
print("{}\t{}".format(fn,
','.... | 55,349 |
def infer_mime(
mime,
args,
vocab,
data,
fuzz_ops,
emotion=None,
format_data_output_path=None,
):
"""
Infer
"""
fuzzed_data = fuzz(data, {"ops": fuzz_ops})
formatter = MIMEPipeline(vocab)
formatter.format([[obj["fuzzed"]] for obj in fuzzed_data], emotion=emotion)
... | 55,350 |
def fill2mask(y, fill):
"""Create a masked array for a non-numeric fill value."""
# TODO: Write. Needed for ISOTime parameters with a fill value.
pass | 55,351 |
def init_collection():
""" 集合对象声明 """
# set集合:不重复无序列集合
set_collection = set()
set_collection1 = {'a', 'b', 'a'}
# 字典:有序列 key-value键值对,后面覆盖前面重复元素
dict_collection = dict()
dict_collection1 = {1: 'a', 2: 'b', 3: 'a', 3: 'c'}
# 数字:有序列集合,后面覆盖前面重复元素
list_collection = list()
list_colle... | 55,352 |
def request_priority_access(requester: str, trusted_by: str = None,
url: str = None):
"""(draft) Request priority to access data (eg Overloaded server allow you)
Example:
please = hxlm.routing.request_priority_access(
url='https://example.org/datase... | 55,353 |
def test_persist_param(root: Path) -> None:
"""Test that the loader works with persist_workers flag."""
dm = CelebADataModule(root=root, persist_workers=True, num_workers=1, train_batch_size=32)
dm.prepare_data()
dm.setup()
loader = dm.train_dataloader()
batch = next(iter(loader))
assert bat... | 55,354 |
def calcula_opcionais(opcional, diarias):
"""
Faz o cálculo de cada opcional que for solicitado pelo cliente
:param opcional: Opcional escolhido pelo cliente
:param diarias: Número de diárias contratadas
:return: retorna com os opcionais contratados dentro de um dicionário
"""
op_contratados... | 55,355 |
def trycmd(*args, **kwargs):
"""Convenience wrapper around oslo's trycmd() function."""
if 'run_as_root' in kwargs and 'root_helper' not in kwargs:
kwargs['root_helper'] = _get_root_helper()
return processutils.trycmd(*args, **kwargs) | 55,356 |
def mocked_fetch_next_version(mocker):
"""Return mocked 'nomenclator.utilities.fetch_next_version' function."""
import nomenclator.utilities
return mocker.patch.object(nomenclator.utilities, "fetch_next_version", ) | 55,357 |
def is_from_keyword(token):
"""
「FROM」判定
"""
return token.match(T.Keyword, "FROM") | 55,358 |
def plot_confusion_matrix(cm, labels,
normalize=True,
title='Confusion Matrix (Validation Set)',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`... | 55,359 |
def get_saved_state(model, optimizer, lr_scheduler, epoch, hyp):
"""Get the information to save with checkpoints"""
if hasattr(model, 'module'):
model_state_dict = model.module.state_dict()
else:
model_state_dict = model.state_dict()
utils_state_dict = {
'epoch': epoch,
'... | 55,360 |
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
return clean(number, ' -.').strip() | 55,361 |
def pretty_status_str(status,color,bold):
"""return pretty status string from status code"""
if bold:
bold_str='1'
else:
bold_str='0'
color_map = {
0: 32, # green
10: 32, # green
15: 37, # white
20: 31, # red
30: 31, # red
}
color_code=color_map.get(st... | 55,362 |
def test_quaternion_matrix():
"""
Tests the functions `matrix_from_quaternion` and `quaternion_from_matrix`
by creating a random unit quaternion and checking if the composition of
the two functions renders the identity.
"""
# creating a random unit quaternion with positive real part
known_qu... | 55,363 |
def check_package_spec(spec):
"""Check package specification."""
err = []
for e in v.iter_errors(spec):
err.append(_msg(e))
logging.error(_msg(e))
if err:
raise ValueError("Invalid component specification.") | 55,364 |
def dynamic_import(import_string):
"""
Dynamically import a module or object.
"""
# Use rfind rather than rsplit for Python 2.3 compatibility.
lastdot = import_string.rfind('.')
if lastdot == -1:
return __import__(import_string, {}, {}, [])
module_name, attr = import_string[:las... | 55,365 |
def get_list():
"""Supports starling/peafowl-style queue_<name>_items introspection via stats."""
conn = Client(CONN.split(';'))
queue_list = []
queue_re = re.compile(r'queue\_(.*?)\_total_items')
try:
for server in conn.get_stats():
for key in server[1].keys():
i... | 55,366 |
async def tidy_http_peers_job(config=None):
"""Check that HTTP peers are reacheable, else remove them from the list"""
from aleph.web import app
from aleph.services.p2p import singleton
from aleph.services.utils import get_IP
my_ip = await get_IP()
if config is None:
config = app["confi... | 55,367 |
def compute_correlations_of_each_k(data, predictions, model_name, year):
"""
Computes the correlations between the BERT or GPT2 Language Model with Q1
:param data: The actual data of the year stored on dictionary
:param predictions: A dict where the predictions from our experiments are saved
:param ... | 55,368 |
def net(n_ID):
"""
simple sample net to be used to train larger representations of given representations
while retaining the identity information
return: keras model
"""
model = Sequential()
model.add(Dense(256, input_shape=(128,), activation="relu", kernel_ini... | 55,369 |
def fullrank(X, r=None):
"""
Return a matrix whose column span is the same as X.
If the rank of X is known it can be specified as r -- no check
is made to ensure that this really is the rank of X.
"""
if r is None:
r = rank(X)
V, D, U = L.svd(X, full_matrices=0)
order = np.ar... | 55,370 |
def update_solution_set(thresholds, threshold_h, asked_no_solutions, campus_id, current_sol):
"""Updates the set of solutions stored when one of the thresholds changes."""
print("Running 'update_solution_set'.")
# Check that all thresholds are integers, otherwise do nothing.
if not all(map(lambda x: isi... | 55,371 |
def global_stock_update():
"""Task that updates every stock model with current data."""
stocks = Stock().from_db(many=True)
# if the db is empty the task just returns
if not stocks:
return
symbols = '+'.join([stock.symbol for stock in stocks])
data = current_stock_values(symbols)
f... | 55,372 |
def gwloss(constC, hC1, hC2, T):
""" Return the Loss for Gromov-Wasserstein
The loss is computed as described in Proposition 1 Eq. (6) in [12].
Parameters
----------
constC : ndarray, shape (ns, nt)
Constant C matrix in Eq. (6)
hC1 : ndarray, shape (ns, ns)
h1(C... | 55,373 |
def get_tag_by_storage_id(storage_id):
"""
根据storage_id查询地域tag
:param storage_id:
:return: None if not found
"""
return get_tag_by_target_id(STORAGE_CLUSTER, storage_id) | 55,374 |
def load_merged_with_style(dataset, style):
"""Load the merged dataframe for all the splits and then filter them
based on style."""
assert dataset in ['duke_ct','openi_cxr']
if dataset == 'duke_ct':
train_merged, test_merged, predict_merged = load_data_duke_ct()
elif dataset == 'openi_cxr':
... | 55,375 |
def with_inverse(points, noise, debug = False):
""" Smooths a set of points
It smooths them twice, once in given order, another one in the reverse order.
The the first half of the results will be taken from the reverse order and
the second half from the normal order.
Args:
points (:obj... | 55,376 |
def update_stats(preds, names, *args):
"""
Get the prediction of the best model and calculate
price per square meter and difference in price from
the previous parameters.
Notes
-----
Difference shows up after the user
changes the settings.
"""
area = args[2]
price = p... | 55,377 |
def tflops_per_second(flops, dt):
""" Computes an effective processing rate in TFLOPS per second.
TFLOP/S = flops * / (dt * 1E12)
Args:
flops: Estimated FLOPS in the computation.
dt: Elapsed time in seconds.
Returns:
The estimate.
"""
return flops / (1E12 * dt) | 55,378 |
def format_img(img, C):
""" formats an image for model prediction based on config """
img, ratio = format_img_size(img, C)
img = format_img_channels(img, C)
return img, ratio | 55,379 |
def register():
#构造要返回的字符串# 初始化返回的数据 [arg1, arg2, arg3, arg4] arg1=状态码(num)arg2=msg(str) arg3= count(num) arg4=tuple
"""
:return:
{
"code": 0,
"msg": "",
"count": 29,
"data": []
}
"""
code = 500
print('??????????????code type=', type(code))
msg = '注册失败,请重新尝试'
count =... | 55,380 |
def gff_view(params):
"""
Converts data to fastya
"""
print("##gff-version 3")
for param in params:
# GFF is a interval (record mode).
param.record = True
# Stop when data was not found.
if not param.json:
utils.error(f"data not found: {param.acc}")
... | 55,381 |
def get_instance_groups(context: models.Context) -> Mapping[str, InstanceGroup]:
"""Get a list of InstanceGroups matching the given context, indexed by name."""
groups: Dict[str, InstanceGroup] = {}
if not apis.is_enabled(context.project_id, 'compute'):
return groups
gce_api = apis.get_api('compute', 'v1', ... | 55,382 |
def collect_paper_data(password=None):
"""Collects, unzips, and cleans resources for the experiments."""
base = 'https://onyx.uvt.nl/sakuin/reap/'
print("Collecting resources...")
print(''.join((l.decode('utf-8') for l in
request.urlopen(base + 'README.md'))))
for _dir in ['src'... | 55,383 |
def generateReducScript(msNames='', step='calib', corrAntPos=True, timeBinForFinalData=0.,
refant='', bpassCalId='', chanWid=1, angScale=0, run=False, lowSNR=False,
projectCode='', schedblockName='', schedblockUid='', queue='', state='',
upToTim... | 55,384 |
def get_hosts(host_file):
""" Fetches host data from a specified host_file
Args:
host_file: Device host file in JSON format
Returns:
A dict mapping keys to the corresponding host data, as follows:
{u'Group-1':
{u'example-device-2':
{u'username': u'usern... | 55,385 |
def get_criteria_description(criterias, milestone_name):
"""Get implementation of the criteria, based on config.
This function checks for config criteria_name in config['criterias'],
gets class - realization of this criteria - and returns an instance
of this class.
"""
description = ""
for... | 55,386 |
def geo_to_bary(ra,dec,jd,epoch):
"""
For a given ra/dec, return the conversion from geocentric velocity to heliocentric
:ra: Decimal right ascension (degrees)
:dec: Decimal declination (degrees)
:jd: Modified (2000 = 51544) julian date
:epoch: Epoch of observations (e.g., 2000, 2008.202)
... | 55,387 |
def plot_precinct_scatterplot(ei_runs, run_names, candidate, demographic_group="all", ax=None):
"""
Given two RxC EI runs, plot precinct-by-precinct comparison of preferences
for a given candidate from a given demographic group.
Parameters
----------
ei_runs: array
Length = 2
El... | 55,388 |
def linear_cubic_interpolation(driver_array=(), divisions=20, interpolation='quadratic'):
"""
interpolate the cubic line between points.
:return: <tuple> the array of point dictionary.
"""
point_final = ()
if interpolation == 'quadratic':
for t in xrange(divisions):
v1 = Vect... | 55,389 |
def gf_edf_shoup(f, n, p, K):
"""
Gathen-Shoup: Probabilistic Equal Degree Factorization
Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and integer
``n`` such that ``n`` divides ``deg(f)``, returns all irreducible factors
``f_1,...,f_d`` of ``f``, each of degree ``n``. This is a complet... | 55,390 |
def create_wrappers_for_class_methods(klass):
"""Wraps all the functions and class methods of a class."""
for name, func in inspect.getmembers(klass, predicate=inspect.isfunction):
setattr(klass, name, strong(func))
return klass | 55,391 |
def eci2geodetic(eci, t):
"""
convert ECI to geodetic coordinates
inputs:
eci/ecef: Nx3 vector of x,y,z triplets in the eci or ecef system [meters]
t : length N vector of datetime OR greenwich sidereal time angle [radians].
output
------
lat,lon (degrees/radians)
alt (meters)
... | 55,392 |
def publish_notify(request, published_project):
"""
Notify authors and administrators when a project is published
"""
subject = 'Your project has been published: {0}'.format(
published_project.title)
content = {'published_project': published_project,
'domain': get_current_sit... | 55,393 |
def disconnect_request_handler(msg, gossiper):
"""Handles disconnection request events.
When a disconnection request message arrives, the replying node is
removed as a peer.
Args:
msg (message.Message): The received disconnection request message.
gossiper (Node): The local node.
""... | 55,394 |
def convert_to_circuit(image):
"""Encode truncated classical image into quantum datapoint."""
values = np.ndarray.flatten(image)
qubits = cirq.GridQubit.rect(4, 4)
circuit = cirq.Circuit()
for i, value in enumerate(values):
if value:
circuit.append(cirq.X(qubits[i]))
... | 55,395 |
def verify_email_change(userid, token):
"""
Verify a user's email change request, updating the `login` record if it validates.
Compare a supplied token against the record within the `emailverify` table, and provided
a match exists, copy the email within into the user's account record.
Parameters:
... | 55,396 |
def huber_fn_gradient(x, mu):
""" Huber function gradient """
y = torch.zeros_like(x)
with torch.no_grad():
mask = torch.abs(x) <= mu
y[mask] = x[mask]/mu
y[~mask] = x[~mask] / torch.abs(x[~mask])
return y | 55,397 |
def capbset_drop(cap: Cap) -> None:
"""
Remove the given capability from the current thread's bounding capability set.
(This requires the CAP_SETPCAP capability.)
This function will fail with ``EINVAL`` if the kernel does not support the specified capability.
"""
ffi.prctl(ffi.PR_CAPBSET_DROP,... | 55,398 |
def video_read(filename_full):
"""Reads a video from the specified file in ~/Physics Pics. Converts to grayscale to reduce filesize.
Parameters
----------
filename_full : string
The file name within /Physics Pics, include the file extension, i.e. '.mp4'.
Returns
-------
np.array
... | 55,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.