content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def hidden_state_embedding(hidden_states: torch.Tensor, layers: List[int],
use_cls: bool, reduce_mean: bool = True) -> torch.Tensor:
"""
Extract embeddings from hidden attention state layers.
Parameters
----------
hidden_states
Attention hidden states in the trans... | 5,330,400 |
def is_new_user(day: datetime.datetime, first_day: datetime.datetime):
"""
Check if user has contributed results to this project before
"""
if day == first_day:
return 1
else:
return 0 | 5,330,401 |
def to_ndarray(X):
"""
Convert to numpy ndarray if not already. Right now, this only converts
from sparse arrays.
"""
if isinstance(X, np.ndarray):
return X
elif sps.issparse(X):
print('Converting from sparse type: {}'.format(type(X)))
return X.toarray()
else:
... | 5,330,402 |
def _2d_gauss(x, y, sigma=2.5 / 60.0):
"""A Gaussian beam"""
return np.exp(-(x ** 2 + y ** 2) / (2 * sigma ** 2)) | 5,330,403 |
def copy_render_file(src_path, dst_path):
"""Create copy file of an image."""
if hasattr(os, "link"):
os.link(src_path, dst_path)
else:
shutil.copy(src_path, dst_path) | 5,330,404 |
def per_device_work(session, check_mode, enable_pass, settings_header):
"""
This function contains the code that should be executed on each device that this script connects to. It is called
after establishing a connection to each device in the loop above.
You can either put your own code here, or if t... | 5,330,405 |
def attach_task_custom_attributes(queryset, as_field="task_custom_attributes_attr"):
"""Attach a json task custom attributes representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the task custom attributes as an attribute with this name.
... | 5,330,406 |
def render_to_svg(path: str, cell_grid: List[List[GridCell]], save_png: bool):
"""
render a grid_cell as an svg file
:param path: path to the svg file that we will save to
:param cell_grid: the cell_grid object that can either be GridCells or WalledCells
:param save_png: if true will also save a png... | 5,330,407 |
def softmax_like(env, *, trajectory_model, agent_model, log=False):
"""softmax_like
:param env: OpenAI Gym environment
:param trajectory_model: trajectory probabilistic program
:param agent_model: agent's probabilistic program
:param log: boolean; if True, print log info
"""
Qs = torch.as_... | 5,330,408 |
def bulk_add(packages, user):
"""
Support bulk add by processing entries like:
repo [org]
"""
added = 0
i = 0
packages = packages.split('\n')
num = len(packages)
org = None
results = str()
db.set(config.REDIS_KEY_USER_SLOTNUM_PACKAGE % user, num)
results += "Add... | 5,330,409 |
def laser_heater_to_energy_spread(energy_uJ):
"""
Returns rms energy spread in induced in keV.
Based on fits to measurement in SLAC-PUB-14338
"""
return 7.15*sqrt(energy_uJ) | 5,330,410 |
def apparent_attenuation(og, fg):
"""Apparent attenuation
"""
return 100.0 * (float(og) - float(fg)) / float(og) | 5,330,411 |
def masked_greater(x: numpy.ndarray, value: int):
"""
usage.dask: 5
usage.matplotlib: 1
usage.scipy: 3
"""
... | 5,330,412 |
def most_similar(W, vocab, id2word, word, n=15):
"""
Find the `n` words most similar to the given `word`. The provided
`W` must have unit vector rows, and must have merged main- and
context-word vectors (i.e., `len(W) == len(word2id)`).
Returns a list of word strings.
"""
assert len(W) == ... | 5,330,413 |
async def on_message(message):
"""メンバー募集 (.rect@数字)"""
if message.content.startswith(".rect"):
mcount = int(message.content[6:len(message.content)])
text= "あと{}人 募集中\n"
revmsg = text.format(mcount)
#friend_list 押した人のList
frelist = []
msg = await client.send_messag... | 5,330,414 |
def getRecordsFromDb():
"""Return all records found in the database associated with :func:`dbFilePath()`.
List of records are cached using an application configuration entry identified
by ``_CACHED_RECORDS`` key.
See also :func:`openDb`.
"""
try:
records = flask.current_app.config["_CA... | 5,330,415 |
def build_cell(num_units,
num_layers,
cell_fn,
initial_state=None,
copy_state=True,
batch_size=None,
output_dropout_rate=0.,
input_shape=None,
attention_mechanism_fn=None,
memo... | 5,330,416 |
def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Use config values to set up a function enabling status retrieval."""
conf = config[DOMAIN]
host = conf[CONF_HOST]
port = conf[CONF_PORT]
apcups_data = APCUPSdData(host, port)
hass.data[DOMAIN] = apcups_data
# It doesn't really ... | 5,330,417 |
def _lagged_coherence_1freq(x, f, Fs, N_cycles=3, f_step=1):
"""Calculate lagged coherence of x at frequency f using the hanning-taper FFT method"""
# Determine number of samples to be used in each window to compute lagged coherence
Nsamp = int(np.ceil(N_cycles * Fs / f))
# For each N-cycle chunk, cal... | 5,330,418 |
def get_lengths(input_list):
"""Generator function that yields the
length of the strings in input_list."""
# Yield the length of a string
for person in input_list:
yield (person,len(person)) | 5,330,419 |
def test_process_incoming(capsys):
""" Test to determine that messages expected to be given to the blockchain
are added to the receive_queue.
"""
with capsys.disabled():
msg = ('to-blockchain', 'msg-data')
receive_queue = Queue()
address = ('0.0.0.0', 1)
process_incoming... | 5,330,420 |
def test_create_downloadable_file_from_metadata(clean_db, monkeypatch):
"""Try to create a downloadable file from artifact_core metadata"""
# fake file metadata
file_metadata = {
"object_url": "10021/Patient 1/sample 1/aliquot 1/wes_forward.fastq",
"file_size_bytes": 1,
"md5_hash": "... | 5,330,421 |
def mostrar_porcentaje_sexo():
"""
Muestra el porcentaje de varones y mujeres por cada aula.
"""
for aula in taller.aulas:
print(f"Aula: {aula.nombre}")
print(f"Porcentaje de varones: {aula.porcentaje('M'):.2%}")
print(f"Porcentaje de mujeres: {aula.porcentaje('F'):.2%}") | 5,330,422 |
def program_hash(p:Program)->Hash:
""" Calculate the hashe of a program """
string=";".join([f'{nm}({str(args)})' for nm,args in p.ops if nm[0]!='_'])
return md5(string.encode('utf-8')).hexdigest() | 5,330,423 |
def build_pages(config, site_navigation):
"""
Builds all the pages and writes them into the build directory.
"""
#site_navigation = nav.SiteNavigation(config['pages'])
loader = jinja2.FileSystemLoader(config['templates_dir'])
env = jinja2.Environment(loader=loader)
index = site_navigation.g... | 5,330,424 |
async def get_events(user_creds, client_creds, list_args, filter_func=None):
"""List events from all calendars according to the parameters given.
The supplied credentials dict may be updated if tokens are refreshed.
:param user_creds: User credentials from `obtain_user_permission`.
:param client_creds... | 5,330,425 |
def test_plugin_xmpp_general(tmpdir):
"""
NotifyXMPP() General Checks
"""
# Set success flag
apprise.plugins.SliXmppAdapter.success = True
# Enforce Adapter
apprise.plugins.NotifyXMPP._adapter = apprise.plugins.SliXmppAdapter
# Create a restore point
ca_backup = apprise.plugins.Sl... | 5,330,426 |
def process_file(input_file, input_type, index, is_parallel):
"""
Process an individual SAM/BAM file.
How we want to process the file depends on the input type and whether we
are operating in parallel. If in parallel the index must be loaded for each
input file. If the input is a BAM file it needs ... | 5,330,427 |
def add_dictionaries(coefficients, representatives, p):
""" Computes a dictionary that is the linear combination of `coefficients`
on `representatives`
Parameters
----------
coefficients : :obj:`Numpy Array`
1D array with the same number of elements as `representatives`. Each
entry ... | 5,330,428 |
def import_documentation_parts(restApiId=None, mode=None, failOnWarnings=None, body=None):
"""
See also: AWS API Documentation
:example: response = client.import_documentation_parts(
restApiId='string',
mode='merge'|'overwrite',
failOnWarnings=True|False,
body=b'byt... | 5,330,429 |
def dropsRowsWithMatchClassAndDeptRemainderIsZero(df, Col, RemainderInt, classToShrink):
"""
Takes as input a dataframe, a column, a remainder integer, and a class within the column.
Returns the dataframe minus the rows that match the ClassToShrink in the Col and have a depth from the DEPT col with a remain... | 5,330,430 |
def import_plugins(
plugins_to_import: Union[str, List[str], None] = None,
warn: bool = True,
) -> Union[
'ModuleType', Tuple['ModuleType', None]
]:
"""
Import the Meerschaum plugins directory.
:param plugins_to_import:
If provided, only import the specified plugins.... | 5,330,431 |
def _opendata_to_section_meeting(data, term_year):
"""Converts OpenData class section info to a SectionMeeting instance.
Args:
data: An object from the `classes` field returned by OpenData.
term_year: The year this term is in.
"""
date = data['date']
days = []
if date['weekdays'... | 5,330,432 |
def run_step(emr_engine, datastore, action, step_wrapper):
"""
:type emr_engine: dart.engine.emr.emr.EmrEngine
:type datastore: dart.model.datastore.Datastore
:type action: dart.model.action.Action
:type step_wrapper: dart.engine.emr.steps.StepWrapper
"""
cluster_id = datastore.data.extra_da... | 5,330,433 |
def get_token():
""" returns a session token from te internal API.
"""
auth_url = '%s/sessions' % local_config['INTERNAL_API_BASE_URL']
auth_credentials = {'eppn': 'worker@pebbles',
'password': local_config['SECRET_KEY']}
try:
r = requests.post(auth_url, auth_credenti... | 5,330,434 |
def setlist(L):
""" list[alpha] -> set[alpha] """
# E : set[alpha]
E = set()
# e : alpha
for e in L:
E.add(e)
return E | 5,330,435 |
def ek_8_fix(alts: List[str]) -> List[str]:
"""
Replace ek, 8 patterns in text.
This is google ASR specifc. Google gets confused between 1 and 8.
Therefore if alternatives only contain 8 and 1, we change everything to 8
pm.
TODO: Another really structurally bad piece of logic.
"""
cou... | 5,330,436 |
def _pixel_at(x, y):
"""
Returns (r, g, b) color code for a pixel with given coordinates (each value is in
0..256 limits)
"""
screen = QtGui.QGuiApplication.primaryScreen()
color = screen.grabWindow(0, x, y, 1, 1).toImage().pixel(0, 0)
return ((color >> 16) & 0xFF), ((color >> 8) & 0xFF), ... | 5,330,437 |
def reincarnatedCLI(nodeRegsForCLI, newLooper, tdir, cli):
"""
Creating a new cli instance is equivalent to starting and stopping a cli
"""
cli = newCLI(nodeRegsForCLI, newLooper, tdir, unique_name='reincarnate')
yield cli
cli.close() | 5,330,438 |
def parse_tibia_time(tibia_time: str) -> datetime:
"""Gets a time object from a time string from tibia.com"""
tibia_time = tibia_time.replace(",","").replace(" ", " ")
# Getting local time and GMT
t = time.localtime()
u = time.gmtime(time.mktime(t))
# UTC Offset
local_utc_offset ... | 5,330,439 |
def a3v(V: Vector3) -> np.ndarray:
"""Converts vector3 to numpy array.
Arguments:
V {Vector3} -- Vector3 class containing x, y, and z.
Returns:
np.ndarray -- Numpy array with the same contents as the vector3.
"""
return np.array([V.x, V.y, V.z]) | 5,330,440 |
def _p_value_color_format(pval):
"""Auxiliary function to set p-value color -- green or red."""
color = "green" if pval < 0.05 else "red"
return "color: %s" % color | 5,330,441 |
def rms(da, dim=None, dask='parallelized', keep_attrs=True):
"""
Reduces a dataarray by calculating the root mean square along the dimension
dim.
"""
# TODO If dim is None then take the root mean square along all dimensions?
if dim is None:
raise ValueError('Must supply a dimension alon... | 5,330,442 |
def check_blackouts():
"""Check blacked-out servers."""
zkclient = context.GLOBAL.zk.conn
try:
blacked_out_nodes = zkclient.get_children(z.BLACKEDOUT_SERVERS)
for server in blacked_out_nodes:
_LOGGER.warn('Server blackedout: %s', server)
except kazoo.client.NoNodeError:
... | 5,330,443 |
def generator(seed):
"""
build the generator network.
"""
weights_initializer = tf.truncated_normal_initializer(stddev=0.02)
# fully connected layer to upscale the seed for the input of
# convolutional net.
target = tf.contrib.layers.fully_connected(
inputs=seed,
num_outputs... | 5,330,444 |
def KFoldROC(k=5, batch_size=20, img_width=150, img_height=150, img_channels=150):
"""
Calculates and plots ROC curves for each of the cross-validated models.
@params:
k - Optional : number of splits (i.e. the 'K' in k-fold cross-validation)
batch_size - Optional : number of images to feed CPU/GPU p... | 5,330,445 |
def solve_fxdocc_root(iws, e_onsite, concentration, hilbert_trafo: Callable[[complex], complex],
beta: float, occ: float = None, self_cpa_iw0=None, mu0: float = 0,
weights=1, n_fit=0, restricted=True, **root_kwds) -> RootFxdocc:
"""Determine the CPA self-energy by solving... | 5,330,446 |
def getn_hidden_area(*args):
"""getn_hidden_area(int n) -> hidden_area_t"""
return _idaapi.getn_hidden_area(*args) | 5,330,447 |
def cdist(X: DNDarray, Y: DNDarray = None, quadratic_expansion: bool = False) -> DNDarray:
"""
Calculate Euclidian distance between two DNDarrays:
.. math:: d(x,y) = \\sqrt{(|x-y|^2)}
Returns 2D DNDarray of size :math: `m \\times n`
Parameters
----------
X : DNDarray
2D array of s... | 5,330,448 |
def popcount_u8(x: np.ndarray):
"""Return the total bit count of a uint8 array"""
if x.dtype != np.uint8:
raise ValueError("input dtype must be uint8")
count = 0
# for each item look-up the number of bits in the LUT
for elem in x.flat:
count += u8_count_lut[elem]
return count | 5,330,449 |
def split_errorRC(tr, t1, t2, q, Emat, maxdt, ddt, dphi):
"""
Calculates error bars based on a F-test and
a given confidence interval q.
Note
----
This version uses a Fisher transformation for
correlation-type misfit.
Parameters
----------
tr : :class:`~obspy.core.Trace`
... | 5,330,450 |
def filter_parts(settings):
"""
Remove grouped components and glyphs that have been deleted or split.
"""
parts = []
temp = copy.copy(settings['glyphs'])
for glyph in settings['glyphs']:
name = glyph['class_name']
if name.startswith("_split") or name.startswith("_group") or name.... | 5,330,451 |
def do_path():
"""Send the HTTP request (GET) and process to get the path to the user space on the cache."""
url = settings.XFC_API_URL + "user?name=" + settings.USER
response = requests.get(url, verify=settings.VERIFY)
if response.status_code == 200:
data = response.json()
sys.stdout.wr... | 5,330,452 |
def kernel_zz(Y, X, Z):
"""
Kernel zz for second derivative of the potential generated by a sphere
"""
radius = np.sqrt(Y ** 2 + X ** 2 + Z ** 2)
r2 = radius*radius
r5 = r2*r2*radius
kernel = (3*Z**2 - r2)/r5
return kernel | 5,330,453 |
def getAccentedVocal(vocal, acc_type="g"):
"""
It returns given vocal with grave or acute accent
"""
vocals = {'a': {'g': u'\xe0', 'a': u'\xe1'},
'e': {'g': u'\xe8', 'a': u'\xe9'},
'i': {'g': u'\xec', 'a': u'\xed'},
'o': {'g': u'\xf2', 'a': u'\xf3'},
... | 5,330,454 |
def env_initialize(env, train_mode=True, brain_idx=0, idx=0, verbose=False):
""" Setup environment and return info """
# get the default brain
brain_name = env.brain_names[brain_idx]
brain = env.brains[brain_name]
# reset the environment
env_info = env.reset(train_mode=train_mode)[brain_na... | 5,330,455 |
def lorentzianfit(x, y, parent=None, name=None):
"""Compute Lorentzian fit
Returns (yfit, params), where yfit is the fitted curve and params are
the fitting parameters"""
dx = np.max(x) - np.min(x)
dy = np.max(y) - np.min(y)
sigma = dx * 0.1
amp = fit.LorentzianModel.get_amp_from_amplitude(... | 5,330,456 |
def tf_quat(T):
""" Return quaternion from 4x4 homogeneous transform """
assert T.shape == (4, 4)
return rot2quat(tf_rot(T)) | 5,330,457 |
def download_folder_to_path(
bucket_name: str,
folder: str,
path: str,
suffix: str=None,
storage_client = None,
flatten=False,
asynchronous=False,
):
"""
Downloads a folder hosted in a bucket to the chosen path.
If flatten is set to True, then the hierarchy structure of the ... | 5,330,458 |
def isString(string):
""" Checks if the input argument is a string """
if not type(string) == str:
raise TypeError("The input argument has to be a string") | 5,330,459 |
def solve2(lines):
"""Solve the problem."""
result = 0
for group in parse_answers2(lines):
result += len(group)
return result | 5,330,460 |
def copy_file(source, target, compress=None):
"""
Copies a file from source to target, optionally compressing it before writing
it out.
Parameters
----------
source : str
target : str
compress : str, optional
The compression algorithm to use. Currently only ".gz" is supported. If
set, targe... | 5,330,461 |
def execute_on_hosts(hosts, commands):
"""Execute Shell command on hosts over SSH.
:param hosts: A list of host names.
:param commands: A list of Shell commands.
"""
commands_merged = ''
for command in commands:
commands_merged += 'echo $ ' + command + ';'
commands_merged += com... | 5,330,462 |
def copy_local_textfile_tree_to_container(local_source_dir, container_host_connection, container_config, container_target_dir):
"""
Copy the contents of a local directory to a container directory.
"""
dir_content = fileutil.get_dir_content(local_source_dir)
for item in dir_content:
source_pa... | 5,330,463 |
def get_contract_type(timestamp: int, due_timestamp: int) -> str:
"""Get the contract_type
Input the timestamp and due_timestamp. Return which contract_type is.
Args:
timestamp: The target timestamp, you want to know.
due_timestamp: The due timestamp of the contract.
Returns:
... | 5,330,464 |
def is_sequence_of(obj: Any,
types: Optional[Union[Type[object],
Tuple[Type[object], ...]]] = None,
depth: Optional[int] = None,
shape: Optional[Sequence[int]] = None
) -> bool:
"""
Test if objec... | 5,330,465 |
def cnf_create(cnf_fs, cids):
""" create a new cnf filesys using list of cids
"""
for cid in cids:
cnf_fs[-1].create([cid]) | 5,330,466 |
def anonymize_dicom(dicom_file,patient_name='anonymous',
fields_to_anonymize=ANONYMIZATION_FIELDS,
fields_to_return=None,path_to_save='.',
new_dicom_name='anonymous.dcm'):
""" Given a dicom file, alter the given fields, anonymizing the
patient name sep... | 5,330,467 |
def _parse_tree_height(sent):
"""
Gets the height of the parse tree for a sentence.
"""
children = list(sent._.children)
if not children:
return 0
else:
return max(_parse_tree_height(child) for child in children) + 1 | 5,330,468 |
def inject_js(in_file, out_file, dataset):
"""parse the html and inject code"""
with open(in_file) as rfh:
content = rfh.read()
sub = os.path.splitext(
os.path.basename(in_file))[0]
out_lines = []
infname = False
lastfield = None
nextinject = None
finished = None
fo... | 5,330,469 |
def assert_array_almost_equal(x: bool, y: bool):
"""
usage.scipy: 4
"""
... | 5,330,470 |
def pandas_loss_p_g_i_t(c_m, lgd, ead, new):
""" Distribution of losses at time t.
long format (N_MC, G, K, T)."""
mat_4D = loss_g_i_t(c_m, lgd, ead, new)
names = ['paths', 'group_ID', 'credit_rating_rank', 'time_steps']
index = pds.MultiIndex.from_product([range(s)for s in mat_4D.shape], names=... | 5,330,471 |
def get_file_if_unique(location, ext):
"""Find file if unique for the provided extension."""
files = glob(os.path.join(location, ext))
if len(files) == 1:
return files[0]
else:
print("Multiple/No " + ext[1:] +
" files found in the working directory."
"Specify ... | 5,330,472 |
def _task_cleanup(result, task_id, task_status, obj, **kwargs):
"""
Cleanup after task is revoked.
"""
apiview = result['meta']['apiview']
view = apiview['view']
if view == 'vm_snapshot':
from vms.models import Vm, Snapshot
from api.vm.snapshot.tasks import _vm_snapshot_cb_faile... | 5,330,473 |
async def test_invalid_characters(hass, aioclient_mock):
"""Test that we replace bad characters with placeholders."""
aioclient_mock.get(
"http://1.1.1.1",
text="""
<root>
<device>
<deviceType>ABC</deviceType>
<serialNumber>\xff\xff\xff\xff</serialNumber>
</device>
</root>
""",
... | 5,330,474 |
def pdtb2_make_splits_xval(path, write_path):
"""Make 12 cross-validation splits for PDTB 2.0"""
sections = ['00', '01', '02', '03', '04', '05', '06', '07', '08',
'09', '10', '11', '12', '13', '14', '15', '16', '17',
'18', '19', '20', '21', '22', '23', '24']
dev_sections = ... | 5,330,475 |
def test_dice_type():
"""
test DiceType instance
"""
dice_type = DiceType.to_list()
assert type(dice_type) == list
assert len(dice_type) == len(DiceType) | 5,330,476 |
def find_available_pacs(pacs, pac_to_unstuck=None, pac_to_super=None, pac_to_normal=None):
"""
Finds the available pacs that are not assigned
"""
available_pacs = pacs['mine']
if pac_to_unstuck is not None:
available_pacs = [x for x in available_pacs if x['id'] not in pac_to_unstuc... | 5,330,477 |
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends(),
):
"""
Log in to your account using oauth2 authorization.
In response we get an jwt authorization token
which is used for granting access to data
"""
is_auth, scope = await authenticate_authority(
for... | 5,330,478 |
def retag(tag, msg):
"""
Retag a tag with a new message
"""
local('git tag %s %s -f -m "%s"' % (tag, tag, msg))
local('git push --tags') | 5,330,479 |
def get_plain_expressions(s):
"""Return a list of plain, non-nested shell expressions found in the shell
string s. These are shell expressions that do not further contain a nested
expression and can therefore be resolved indenpendently.
For example::
>>> get_plain_expressions("${_pyname%${_pyname#?... | 5,330,480 |
def register_modelzoo(backend):
"""Import and register modelzoo automatically."""
if backend != "pytorch":
return
from .torch_vision_model import import_all_torchvision_models
import logging
try:
import_all_torchvision_models()
except Exception as e:
logging.warn("Failed ... | 5,330,481 |
def _do_dspam(ids, result):
"""
:param ids: 学习的ID列表
:param result: 结果
:return:
"""
keys = {}
# redis = get_redis_connection()
for k, v in deal_with_ids(ids).iteritems():
mail_model = get_mail_model(k)
servers = mail_model.objects.filter(id__in=v).values_list('server_id', ... | 5,330,482 |
def test_runner(self, namespace, record_size, array_size, thread_per_size=4):
"""Perform simultaneous writes of varying record size to a container.
Args:
self (Test): avocado test object
namespace (str): location from which to read the pool parameters
record_size (list): list of differe... | 5,330,483 |
def create_indices(dims):
"""Create lists of indices"""
return [range(1,dim+1) for dim in dims] | 5,330,484 |
def observed_property(property_name, default, cast=None):
"""Default must be immutable."""
hidden_property_name = "_" + property_name
if cast is None:
if cast is False:
cast = lambda x: x
else:
cast = type(default)
def getter(self):
try:
return... | 5,330,485 |
def query_helper(
source: S3Ref, query: str, dest: S3Ref = None, transform: Callable = None
) -> StringIO:
"""
query_helper runs the given s3_select query on the given object.
- The results are saved in a in memory file (StringIO) and returned.
- If dest is specified, the file is copied to the pro... | 5,330,486 |
def indicator_selector(row, indicator, begin, end):
"""Return Tons of biomass loss."""
dasy = {}
if indicator == 4:
return row[2]['value']
for i in range(len(row)):
if row[i]['indicator_id'] == indicator and row[i]['year'] >= int(begin) and row[i]['year'] <= int(end):
dasy[s... | 5,330,487 |
def xy_from_range_bearing(range: float, bearing: float) -> map_funcs.Point:
"""Given a range in metres and a bearing from the camera this returns the x, y position in metres relative to the runway
start."""
theta_deg = bearing - google_earth.RUNWAY_HEADING_DEG
x = CAMERA_POSITION_XY.x + range * math.cos... | 5,330,488 |
def flask_get_modules():
"""Return the list of all modules
---
tags:
- Modules
responses:
200:
description: A list of modules
"""
db_list = db.session.query(Module).all()
return jsonify(db_list) | 5,330,489 |
def p_rbrace(p):
"""rbrace : RIGHT_CURLY_BRACKET"""
global LAST_POPPED_TABLE
# p[0] = ("rbrace",) + tuple(p[-len(p) + 1 :])
s = pop_scope()
p[0] = {"popped_table": s}
LAST_POPPED_TABLE = s | 5,330,490 |
def create_user(username, password):
"""Registra um novo usuario caso nao esteja cadastrado"""
if User.query.filter_by(username=username).first():
raise RuntimeError(f'{username} ja esta cadastrado')
user = User(username=username, password=generate_password_hash(password))
db.session.add(user)
... | 5,330,491 |
def extract_pubmed_data(log: WarningLog, pubmed_data_node: etree.Element, article: Article):
""" Extracts information from a <PubmedData> node to add into the given article. """
reference_pmids: list[int] = []
reference_list_node = extract_single_node_by_tag(pubmed_data_node, "ReferenceList")
if refere... | 5,330,492 |
def _get_mesh_colour_scheme():
"""Returns colour scheme for MESH (maximum estimated size of hail).
:return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.
:return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.
"""
colour_list = [
[152, 152, 152], [15... | 5,330,493 |
def index():
"""
Serve index page.
"""
try:
data = get_latest_covid_stats()
except FailedRequestError as err:
# Log error response to logger
logger.debug(
f"Request to Public Health England COVID-19 API failed: {err}.")
flash("An error occurred obtaining l... | 5,330,494 |
def parse_setting_file(filename):
"""parse the setting file. Refer to the leading comment for more details"""
setting = [ ]
f = open(filename)
for ind, line in enumerate(f):
ind += 1
params = {
"ispin": {
"reg_exp":re.compile("ispin\s*=\s*([1-2])"),
... | 5,330,495 |
def get_files(directory, include_hidden, include_empty):
"""Returns all FILES in the directory which apply to the filter rules."""
return (os.path.join(dir_path, filename)
for dir_path, _, file_names in os.walk(directory)
for filename in file_names
if not os.path.islink(os.pa... | 5,330,496 |
def cp_chmod(src, dst, mode):
"""
helper function to copy a file and set chmod
"""
shutil.copyfile(src, dst)
os.chmod(dst, mode) | 5,330,497 |
def write_webhook(unique_id, webhook):
"""
writes webhook string (url) to corresponding file.
:param unique_id: unique_id
:param webhook: webhook string
"""
if webhook and isinstance(webhook, str):
open(os.path.join(RAM_DIR, unique_id + ".webhook"), "w").write(webhook)
else:
... | 5,330,498 |
async def test_update_system_data_v2(
event_loop, v2_server, v2_settings_json, v2_subscriptions_json):
"""Test getting updated data for a v2 system."""
async with v2_server:
v2_server.add(
'api.simplisafe.com',
'/v1/users/{0}/subscriptions'.format(TEST_USER_ID), 'get',
... | 5,330,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.