content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _feature_properties(feature, layer_definition, whitelist=None, skip_empty_fields=False):
""" Returns a dictionary of feature properties for a feature in a layer.
Third argument is an optional list or dictionary of properties to
whitelist by case-sensitive name - leave it None to include eve... | 482e42a9f4761cd0273dfb4e5f70bdb55ce168d9 | 3,650,900 |
def reverse_search(view, what, start=0, end=-1, flags=0):
"""Do binary search to find `what` walking backwards in the buffer.
"""
if end == -1:
end = view.size()
end = find_eol(view, view.line(end).a)
last_match = None
lo, hi = start, end
while True:
middle = (lo + hi) / 2
... | 7b8d95a987b9b986fb0e334cf3a9bc74014be67d | 3,650,901 |
def formatLookupLigatureSubstitution(lookup, lookupList, makeName=makeName):
""" GSUB LookupType 4 """
# substitute <glyph sequence> by <glyph>;
# <glyph sequence> must contain two or more of <glyph|glyphclass>. For example:
# substitute [one one.oldstyle] [slash fraction] [two two.oldstyle] by onehalf;... | 3804d7c38564459b6f0cf19cbbac5e96642e61a2 | 3,650,902 |
import pathlib
def convert_raw2nc(path2rawfolder = '/nfs/grad/gradobs/raw/mlo/2020/', path2netcdf = '/mnt/telg/data/baseline/mlo/2020/',
# database = None,
start_date = '2020-02-06',
pattern = '*sp02.*',
sernos = [1032, 1046],
... | 16313b1a7abc05fac469d9a0c5003eebb7ef2a8c | 3,650,903 |
import requests
def get_curricula(course_url, year):
"""Encodes the available curricula for a given course in a given year in a vaguely sane format
Dictionary fields:
- constant.CODEFLD: curriculum code as used in JSON requests
- constant.NAMEFLD: human-readable curriculum name"""
curricula =... | 878f2a54e41624887aed720de52dea15bdbf6528 | 3,650,904 |
def conv3x3(in_planes, out_planes, stride=1, groups=1):
"""3x3 conv with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, groups=groups, bias=False) | 4e53568bb4bf88998020b0804770895b67e9e018 | 3,650,905 |
import stewi
def extract_facility_data(inventory_dict):
"""
Returns df of facilities from each inventory in inventory_dict,
including FIPS code
:param inventory_dict: a dictionary of inventory types and years (e.g.,
{'NEI':'2017', 'TRI':'2017'})
:return: df
"""
facility_map... | b0298b915c0511841d607f7d88a90d64c7e9da59 | 3,650,906 |
import numpy
def zeros(shape, dtype=None):
"""
Create a Tensor filled with zeros, closer to Numpy's syntax than ``alloc``.
"""
if dtype is None:
dtype = config.floatX
return alloc(numpy.array(0, dtype=dtype), *shape) | 9d1d70f59b585d06623d41c18acc67ec16572307 | 3,650,907 |
from typing import Optional
import types
import numpy
from typing import cast
def station_location_from_rinex(rinex_path: str) -> Optional[types.ECEF_XYZ]:
"""
Opens a RINEX file and looks in the headers for the station's position
Args:
rinex_path: the path to the rinex file
Returns:
... | e7fc390a36f34aed04d30becd544d58ea3f6aa41 | 3,650,908 |
def get_profiles():
"""Return the paths to all profiles in the local library"""
paths = APP_DIR.glob("profile_*")
return sorted(paths) | 729b78daa1d259a227147698a2d4d4c9c5126f29 | 3,650,909 |
def split(array, nelx, nely, nelz, dof):
"""
Splits an array of boundary conditions into an array of collections of
elements. Boundary conditions that are more than one node in size are
grouped together. From the nodes, the function returns the neighboring
elements inside the array.
"""
if l... | 1dbc48402e7124e3384bc56538b05f073fe64370 | 3,650,910 |
def sanitize_app_name(app):
"""Sanitize the app name and build matching path"""
app = "".join(c for c in app if c.isalnum() or c in ('.', '_')).rstrip().lstrip('/')
return app | fca922d8b622baa1d5935cd8eca2ffca050a4c86 | 3,650,911 |
import pathlib
def get_rinex_file_version(file_path: pathlib.PosixPath) -> str:
""" Get RINEX file version for a given file path
Args:
file_path: File path.
Returns:
RINEX file version
"""
with files.open(file_path, mode="rt") as infile:
try:
version ... | c7060e8eb32a0e5539323c7334221d4b1967bb1f | 3,650,912 |
import socket
def get_hm_port(identity_service, local_unit_name, local_unit_address,
host_id=None):
"""Get or create a per unit Neutron port for Octavia Health Manager.
A side effect of calling this function is that a port is created if one
does not already exist.
:param identity_ser... | 6cde426643219f4fc3385a36e3c20503b8c41a9e | 3,650,913 |
def total_length(neurite):
"""Neurite length. For a morphology it will be a sum of all neurite lengths."""
return sum(s.length for s in neurite.iter_sections()) | 854429e073eaea49c168fb0f9e381c71d7a7038a | 3,650,914 |
def _solarize(img, magnitude):
"""solarize"""
return ImageOps.solarize(img, magnitude) | d588068f42930872775e62a619333439d8aa47d8 | 3,650,915 |
def calculateCurvature(yRange, left_fit_cr):
"""
Returns the curvature of the polynomial `fit` on the y range `yRange`.
"""
return ((1 + (2 * left_fit_cr[0] * yRange * ym_per_pix + left_fit_cr[1]) ** 2) ** 1.5) / np.absolute(
2 * left_fit_cr[0]) | af1cd81c3eeb85297bcfcb44779bf86b4c6b8dc9 | 3,650,916 |
import os
def find_file_in_sequence(file_root: str, file_number: int = 1) -> tuple:
"""
Returns the Nth file in an image sequence where N is file_number (-1 for first file).
Args:
file_root: image file root name.
file_number: image file number in sequence.
Returns:
tuple (fil... | 276838d6c8673f68182a9daded60762cddbf54d2 | 3,650,917 |
def testing_server_error_view(request):
"""Displays a custom internal server error (500) page"""
return render(request, '500.html', {}) | 84055f37d1ba215ae0e439c1f9d96260208133ff | 3,650,918 |
def main_epilog() -> str:
"""
This method builds the footer for the main help screen.
"""
msg = "To get help on a specific command, see `conjur <command> -h | --help`\n\n"
msg += "To start using Conjur with your environment, you must first initialize " \
"the configuration. See `conjur in... | ecf4167535b5f1e787d286a3b2194816790a7e6a | 3,650,919 |
def sigma_M(n):
"""boson lowering operator, AKA sigma minus"""
return np.diag([np.sqrt(i) for i in range(1, n)], k=1) | 532a082ed5fd3094044162c85042bf963dad4461 | 3,650,920 |
def windowing_is(root, *window_sys):
"""
Check for the current operating system.
:param root: A tk widget to be used as reference
:param window_sys: if any windowing system provided here is the current
windowing system `True` is returned else `False`
:return: boolean
"""
windowing = r... | fd021039686b1971f8c5740beb804826a7afdf80 | 3,650,921 |
def init_columns_entries(variables):
"""
Making sure we have `columns` & `entries` to return, without effecting the original objects.
"""
columns = variables.get('columns')
if columns is None:
columns = [] # Relevant columns in proper order
if isinstance(columns, str):
columns ... | 49a12b0561d0581785c52d9474bc492f2c64626c | 3,650,922 |
from typing import Tuple
def _run_ic(dataset: str, name: str) -> Tuple[int, float, str]:
"""Run iterative compression on all datasets.
Parameters
----------
dataset : str
Dataset name.
name : str
FCL name.
Returns
-------
Tuple[int, float, str]
Solution size, ... | e041cb9c0ca5af98d1f8d23a0e6f3cbe7f5a34a4 | 3,650,923 |
def notch(Wn, Q=10, analog=False, output="ba"):
"""
Design an analog or digital biquad notch filter with variable Q.
The notch differs from a peaking cut filter in that the gain at the
notch center frequency is 0, or -Inf dB.
Transfer function: H(s) = (s**2 + 1) / (s**2 + s/Q + 1)
Parameter
... | a9b4e488bb5a849459bf843abe2bd9d6d18f662d | 3,650,924 |
def Torus(radius=(1, 0.5), tile=(20, 20), device='cuda:0'):
"""
Creates a torus quad mesh
Parameters
----------
radius : (float,float) (optional)
radii of the torus (default is (1,0.5))
tile : (int,int) (optional)
the number of divisions of the cylinder (default is (20,20))
... | 79c7934cabecdf3a4c9c28de7193ccae1ce037de | 3,650,925 |
def check_new_value(new_value: str, definition) -> bool:
"""
checks with definition if new value is a valid input
:param new_value: input to set as new value
:param definition: valid options for new value
:return: true if valid, false if not
"""
if type(definition) is list:
if new_va... | d7204c7501e713c4ce8ecaeb30239763c13c1f18 | 3,650,926 |
def covid_API(cases_and_deaths: dict) -> dict:
"""
Imports Covid Data
:param cases_and_deaths: This obtains dictionary from config file
:return: A dictionary of covid information
"""
api = Cov19API(filters=england_only, structure=cases_and_deaths)
data = api.get_json()
return data | 8429c35770d25d595a6f51a2fe80d2eac585c785 | 3,650,927 |
def cnn(train_x, train_y, test1_x, test1_y, test2_x, test2_y):
"""
Train and evaluate a feedforward network with two hidden layers.
"""
# Add a single "channels" dimension at the end
trn_x = train_x.reshape([-1, 30, 30, 1])
tst1_x = test1_x.reshape([-1, 30, 30, 1])
tst2_x = test2_x.reshape([... | e2607c35d2236188a2ec7fc797c43f6970665d12 | 3,650,928 |
def gather_gltf2(export_settings):
"""
Gather glTF properties from the current state of blender.
:return: list of scene graphs to be added to the glTF export
"""
scenes = []
animations = [] # unfortunately animations in gltf2 are just as 'root' as scenes.
active_scene = None
for blende... | 6a382349a1a2aef3d5d830265b0f7430440ac6ef | 3,650,929 |
import time
def getOneRunMountainCarFitness_modifiedReward(tup):
"""Get one fitness from the MountainCar or MountainCarContinuous
environment while modifying its reward function.
The MountainCar environments reward only success, not progress towards
success. This means that individuals that are tryi... | f17e768755d0b4862ee70a0fe7d317a8074d7852 | 3,650,930 |
def ArtToModel(art, options):
"""Convert an Art object into a Model object.
Args:
art: geom.Art - the Art object to convert.
options: ImportOptions - specifies some choices about import
Returns:
(geom.Model, string): if there was a major problem, Model may be None.
The string will... | 3130471f7aa6b0b8fd097c97ca4916a51648112e | 3,650,931 |
def simulate_data(N, intercept, slope, nu, sigma2=1, seed=None):
"""Simulate noisy linear model with t-distributed residuals.
Generates `N` samples from a one-dimensional linear regression with
residuals drawn from a t-distribution with `nu` degrees of freedom, and
scaling-parameter `sigma2`. The true ... | a88e7f1958876c3dd47101da7f2f1789e02e4d18 | 3,650,932 |
import os
def _link_irods_folder_to_django(resource, istorage, foldername, exclude=()):
"""
Recursively Link irods folder and all files and sub-folders inside the folder to Django
Database after iRODS file and folder operations to get Django and iRODS in sync
:param resource: the BaseResource object ... | c0ff6fdbfae40f6c3e0cc462b924ff835dd6b20a | 3,650,933 |
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""
52ms 93.76%
13.1MB 83.1%
:param self:
:param head:
:param n:
:return:
"""
if not head:
return head
dummy = ListNode(0)
dummy.next = head
fast = dummy
while n:
fast = fast.next
... | 5b9fa939aec64425e7ca9932fe0cc5814fd0f608 | 3,650,934 |
from ..model.types import UnresolvedTypeReference
from typing import Any
from typing import Tuple
import warnings
def validate_template(
template: Any, allow_deprecated_identifiers: bool = False
) -> Tuple[PackageRef, str]:
"""
Return a module and type name component from something that can be interpreted... | 32630bf3ebfd2626791bbb68dacc402d11b99c9a | 3,650,935 |
import logging
def call_status():
"""
Route received for webhook about call
"""
if 'mocean-call-uuid' in request.form:
call_uuid = request.form.get('mocean-call-uuid')
logging.info(f'### Call status received [{call_uuid}] ###')
for k, v in request.form.items():
l... | 700af190ae3b7b74a361728b8907683db0e9338f | 3,650,936 |
import os
def read_data(filename,**kwargs):
"""Used to read a light curve or curve object in pickle format.
Either way, it'll come out as a curve object.
Parameters
----------
filename : str
Name of the file to be read (ascii or pickle)
Returns
-------
curve : :class:`~sn... | 3bf7af7342d2e1d6ea110e30ffbd55fd383885f4 | 3,650,937 |
import logging
def get_masters(domain):
""" """
content = request.get_json()
conf = {
'check_masters' : request.headers.get('check_masters'),
'remote_api' : request.headers.get('remote_api'),
'remote_api_key' : request.headers.get('remote_api_key')
}
masters = pdns_get_mast... | dd006d889ee9f11a8f522a111ce7a4db4f5ba039 | 3,650,938 |
def SplitGeneratedFileName(fname):
"""Reverse of GetGeneratedFileName()
"""
return tuple(fname.split('x',4)) | 0210361d437b134c3c24a224ab93d2ffdcfc32ec | 3,650,939 |
def chooseBestFeatureToSplit(dataSet):
"""
选择最优划分特征
输入: 数据集
输出: 最优特征
"""
numFeatures = len(dataSet[0])-1
baseEntropy = calcShannonEnt(dataSet) #原始数据的熵
bestInfoGain = 0
bestFfeature = -1
for i in range(numFeatures): #循环所有特征
featList = [example[i] for example in dataSet]
... | 1e9935cf280b5bf1a32f34187038301109df7d19 | 3,650,940 |
import torch
import tqdm
def evaluate_model(model: torch.nn.Module, dataloader: torch.utils.data.DataLoader, device: torch.device):
"""Function for evaluation of a model `model` on the data in `dataloader` on device `device`"""
# Define a loss (mse loss)
mse = torch.nn.MSELoss()
# We will accumulate t... | e550c469d0b66cc0a0ef32d2907521c77ed760fa | 3,650,941 |
def get_DOE_quantity_byfac(DOE_xls, fac_xls, facilities='selected'):
"""
Returns total gallons of combined imports and exports
by vessel type and oil classification to/from WA marine terminals
used in our study.
DOE_xls[Path obj. or string]: Path(to Dept. of Ecology transfer dataset)
faci... | 371fd9b2bc0f9e45964af5295de1edad903729c9 | 3,650,942 |
import re
def number_finder(page, horse):
"""Extract horse number with regex."""
if 'WinPlaceShow' in page:
return re.search('(?<=WinPlaceShow\\n).[^{}]*'.format(horse), page).group(0)
elif 'WinPlace' in page:
return re.search('(?<=WinPlace\\n).[^{}]*'.format(horse), page).group(0) | 483067fcfa319a7dfe31fdf451db82550fd35d03 | 3,650,943 |
from ...data import COCODetection
def ssd_300_mobilenet0_25_coco(pretrained=False, pretrained_base=True, **kwargs):
"""SSD architecture with mobilenet0.25 base networks for COCO.
Parameters
----------
pretrained : bool or str
Boolean value controls whether to load the default pretrained weigh... | 5c234e824d60a116b7640eff4c50adba98792927 | 3,650,944 |
def get_project_by_id(client: SymphonyClient, id: str) -> Project:
"""Get project by ID
:param id: Project ID
:type id: str
:raises:
* FailedOperationException: Internal symphony error
* :class:`~psym.exceptions.EntityNotFoundError`: Project does not exist
:return: Project
:rt... | 72904b1f72eb2ce3e031df78d8f00cef8d5b5791 | 3,650,945 |
def write_trans_output(k, output_fname, output_steps_fname, x, u, time, nvar):
"""
Output transient step and spectral step in a CSV file"""
# Transient
if nvar > 1:
uvars = np.split(u, nvar)
results_u = [np.linalg.norm(uvar, np.inf) for uvar in uvars]
results = [
time... | 5681902519af79777f8fb5aa2a36f8445ee4cf32 | 3,650,946 |
def browser(browserWsgiAppS):
"""Fixture for testing with zope.testbrowser."""
assert icemac.addressbook.testing.CURRENT_CONNECTION is not None, \
"The `browser` fixture needs a database fixture like `address_book`."
return icemac.ab.calendar.testing.Browser(wsgi_app=browserWsgiAppS) | 47c9a0d4919be55d15a485632bca826183ba92b2 | 3,650,947 |
def mixture_fit(samples,
model_components,
model_covariance,
tolerance,
em_iterations,
parameter_init,
model_verbosity,
model_selection,
kde_bandwidth):
"""Fit a variational Bayesian non-p... | 807f0ef2028a5dcb99052e6b86558f8b325405db | 3,650,948 |
import yaml
import logging
def apply_k8s_specs(specs, mode=K8S_CREATE): # pylint: disable=too-many-branches,too-many-statements
"""Run apply on the provided Kubernetes specs.
Args:
specs: A list of strings or dicts providing the YAML specs to
apply.
mode: (Optional): Mode indicates how the resourc... | 6420b08b8198ba59594c165b973b97161dd4bac3 | 3,650,949 |
def local_coherence(Q, ds=1):
""" estimate the local coherence of a spectrum
Parameters
----------
Q : numpy.array, size=(m,n), dtype=complex
array with cross-spectrum, with centered coordinate frame
ds : integer, default=1
kernel radius to describe the neighborhood
Returns
... | deb0d52e6852e02e1a92e64a7979585b888753f7 | 3,650,950 |
def find_best_lexer(text, min_confidence=0.85):
"""
Like the built in pygments guess_lexer, except has a minimum confidence
level. If that is not met, it falls back to plain text to avoid bad
highlighting.
:returns: Lexer instance
"""
current_best_confidence = 0.0
current_best_lexer = ... | 57cffae3385886cc7841086697ce30ff10bb3bd8 | 3,650,951 |
def volta(contador, quantidade):
"""
Volta uma determinada quantidade de caracteres
:param contador: inteiro utilizado para determinar uma posição na string
:param quantidade: inteiro utilizado para determinar a nova posição na string
:type contador: int
:type quantidade: int
:return: retorn... | 4183afebdfc5273c05563e4675ad5909124a683a | 3,650,952 |
from operator import and_
def keep_room(session, worker_id, room_id):
"""Try to keep a room"""
# Update room current timestamp
query = update(
Room
).values({
Room.updated: func.now(),
}).where(
and_(Room.worker == worker_id,
Room.id == room_id)
)
proxy... | b4dbbc972d7fd297bf55b205e92d2126a5a68e6e | 3,650,953 |
from typing import List
def get_rounds(number: int) -> List[int]:
"""
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
return list(range(number, number + 3)) | 9bf55545404acd21985c1765906fc439f5f4aed6 | 3,650,954 |
from bs4 import BeautifulSoup
from datetime import datetime
def parse_pasinobet(url):
"""
Retourne les cotes disponibles sur pasinobet
"""
selenium_init.DRIVER["pasinobet"].get("about:blank")
selenium_init.DRIVER["pasinobet"].get(url)
match_odds_hash = {}
match = None
date_time = None
... | 5cda34741f4e6cc26e2ecccec877c9af2426084a | 3,650,955 |
def create_toolbutton(parent, icon=None, tip=None, triggered=None):
"""Create a QToolButton."""
button = QToolButton(parent)
if icon is not None:
button.setIcon(icon)
if tip is not None:
button.setToolTip(tip)
if triggered is not None:
button.clicked.connect(triggered)
re... | dfff516f498f924ca5d5d6b15d94907ed2e06029 | 3,650,956 |
import select
def __basic_query(model, verbose: bool = False) -> pd.DataFrame:
"""Execute and return basic query."""
stmt = select(model)
if verbose:
print(stmt)
return pd.read_sql(stmt, con=CONN, index_col="id") | eb9c44eb64144b1e98e310e2dd026e5b1e912619 | 3,650,957 |
def format_data_preprocessed(data, dtype = np.float):
"""
The input data preprocessing
data the input data frame
preprocessing whether to use features preprocessing (Default: False)
dtype the data type for ndarray (Default: np.float)
"""
train_flag = np.array(data['train_flag'])
print '... | a5785ef81a0f5d35f8fb73f72fbe55084bc5e2b0 | 3,650,958 |
def route_yo(oauth_client=None):
"""Sends a Yo!
We can defer sender lookup to the Yo class since it should be obtained
from the request context. Requiring an authenticated user reduces the
likelihood of accidental impersonation of senders.
Creating pseudo users is handled here. It should be limite... | c729da43a9d4c2ed86c6e9a2e3ddb187b4af6eef | 3,650,959 |
def get_word_idxs_1d(context, token_seq, char_start_idx, char_end_idx):
"""
0 based
:param context:
:param token_seq:
:param char_start_idx:
:param char_end_idx:
:return: 0-based token index sequence in the tokenized context.
"""
spans = get_1d_spans(context,token_seq)
idxs ... | b279a3baea0e9646b55e598fd6ae16df70de5100 | 3,650,960 |
import binascii
def create_b64_from_private_key(private_key: X25519PrivateKey) -> bytes:
"""Create b64 ascii string from private key object"""
private_bytes = private_key_to_bytes(private_key)
b64_bytes = binascii.b2a_base64(private_bytes, newline=False)
return b64_bytes | 3abd69bcd3fc254c94da9fac446c6ffbc462f58d | 3,650,961 |
def create_fake_record(filename):
"""Create records for demo purposes."""
data_to_use = _load_json(filename)
data_acces = {
"access_right": fake_access_right(),
"embargo_date": fake_feature_date(),
}
service = Marc21RecordService()
draft = service.create(
data=data_to_u... | 744ed3a3b13bc27d576a31d565d846850e6640a3 | 3,650,962 |
import json
def load_configuration():
"""
This function loads the configuration from the
config.json file and then returns it.
Returns: The configuration
"""
with open('CONFIG.json', 'r') as f:
return json.load(f) | 91eae50d84ec9e4654ed9b8bcfa35215c8b6a7c2 | 3,650,963 |
import configparser
import os
import sys
def config_parse(profile_name):
"""Parse the profile entered with the command line. This profile is in the profile.cfg file.
These parameters are used to automate the processing
:param profile_name: Profile's name"""
config = configparser.ConfigParser()
co... | 45e56c4a5d55b46d11bf9064c6b72fed55ffa4c9 | 3,650,964 |
def scrape(webpage, linkNumber, extention):
"""
scrapes the main page of a news website using request and beautiful soup and
returns the URL link to the top article as a string
Args:
webpage: a string containing the URL of the main website
linkNumber: an integer point... | f04cb8c8583f7f242ce70ec4da3e8f2556af7edb | 3,650,965 |
def Scheduler(type):
"""Instantiate the appropriate scheduler class for given type.
Args:
type (str): Identifier for batch scheduler type.
Returns:
Instance of a _BatchScheduler for given type.
"""
for cls in _BatchScheduler.__subclasses__():
if cls.is_scheduler_for(type):
... | 21074ecf33383b9f769e8dd63786194b4678246b | 3,650,966 |
def event_detail(request, event_id):
"""
A View to return an individual selected
event details page.
"""
event = get_object_or_404(Event, pk=event_id)
context = {
'event': event
}
return render(request, 'events/event_detail.html', context) | 6fda0906e70d88839fbcd26aa6724b5f2c433c07 | 3,650,967 |
from typing import Optional
from typing import Iterable
from typing import Tuple
import numpy
def variables(
metadata: meta.Dataset,
selected_variables: Optional[Iterable[str]] = None
) -> Tuple[dataset.Variable]:
"""Return the variables defined in the dataset.
Args:
selected_variables: The v... | 6175ad712996a30673eb2f5ff8b64c76d2f4a66b | 3,650,968 |
def builder(tiledata, start_tile_id, version, clear_old_tiles=True):
"""
Deserialize a list of serialized tiles, then re-link all the tiles to
re-create the map described by the tile links
:param list tiledata: list of serialized tiles
:param start_tile_id: tile ID of tile that should be used as th... | 235df5c953705fbbbd69d8f1c7ed1ad282b469ba | 3,650,969 |
import base64
def data_uri(content_type, data):
"""Return data as a data: URI scheme"""
return "data:%s;base64,%s" % (content_type, base64.urlsafe_b64encode(data)) | f890dc1310e708747c74337f5cfa2d6a31a23fc0 | 3,650,970 |
def next_line(ionex_file):
"""
next_line
Function returns the next line in the file
that is not a blank line, unless the line is
'', which is a typical EOF marker.
"""
done = False
while not done:
line = ionex_file.readline()
if line == '':
return line
... | 053e5582e5146ef096d743973ea7069f19ae6d4d | 3,650,971 |
def last(value):
"""
returns the last value in a list (None if empty list) or the original if value not a list
:Example:
---------
>>> assert last(5) == 5
>>> assert last([5,5]) == 5
>>> assert last([]) is None
>>> assert last([1,2]) == 2
"""
values = as_list(value)
ret... | f3a04f0e2544879639b53012bbd9068ae205be18 | 3,650,972 |
import numpy
def levup(acur, knxt, ecur=None):
"""
LEVUP One step forward Levinson recursion
Args:
acur (array) :
knxt (array) :
Returns:
anxt (array) : the P+1'th order prediction polynomial based on the P'th
order prediction polynomial, acur, and the... | 182102d03369d23d53d21bae7209cf49d2caecb4 | 3,650,973 |
def gradient_output_wrt_input(model, img, normalization_trick=False):
"""
Get gradient of softmax with respect to the input.
Must check if correct.
Do not use
# Arguments
model:
img:
# Returns
gradient:
"""
grads = K.gradients(model.output, model.input)[0]
... | ed45fccb0f412f8f8874cd8cd7f62ff2101a3a40 | 3,650,974 |
def response_GET(client, url):
"""Fixture that return the result of a GET request."""
return client.get(url) | b4762c9f652e714cc5c3694b75f935077039cb02 | 3,650,975 |
import sys
def load_python_object(name):
"""
Loads a python module from string
"""
logger = getLoggerWithNullHandler('commando.load_python_object')
(module_name, _, object_name) = name.rpartition(".")
if module_name == '':
(module_name, object_name) = (object_name, module_name)
try... | ba8db72c56929560b72de8330a3f703f96613763 | 3,650,976 |
import tqdm
def twitter_preprocess():
"""
ekphrasis-social tokenizer sentence preprocessor.
Substitutes a series of terms by special coins when called
over an iterable (dataset)
"""
norm = ['url', 'email', 'percent', 'money', 'phone', 'user',
'time', 'date', 'number']
ann = {"hashtag", "elongated", "allca... | 18bcd48cff7c77480cd76165fef02d0e39ae19cc | 3,650,977 |
import math
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis / math.sqrt(np.dot(axis, axis))
a = math.cos(theta / 2.0)
b, c, d = -axis * math.sin(the... | cd940b60096fa0c92b8cd04d36a0d62d7cd46455 | 3,650,978 |
from typing import Type
from typing import List
def get_routes(interface: Type[Interface]) -> List[ParametrizedRoute]:
"""
Retrieves the routes from an interface.
"""
if not issubclass(interface, Interface):
raise TypeError('expected Interface subclass, got {}'
.format(interface.__name__))
route... | 9d3baf951312d3027e2329fa635b2425dda579e5 | 3,650,979 |
import os
import logging
import gzip
def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):
"""A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is ... | a26fca118fe5ca146356b2fa949e1e346640ea46 | 3,650,980 |
def _get_realm(response):
"""Return authentication realm requested by server for 'Basic' type or None
:param response: requests.response
:type response: requests.Response
:returns: realm
:rtype: str | None
"""
if 'www-authenticate' in response.headers:
auths = response.headers['www... | 346b3278eb52b565f747c952493c15820eece729 | 3,650,981 |
import math
def exp_mantissa(num, base=10):
"""Returns e, m such that x = mb^e"""
if num == 0:
return 1, 0
# avoid floating point error eg log(1e3, 10) = 2.99...
exp = math.log(abs(num), base)
exp = round(exp, FLOATING_POINT_ERROR_ON_LOG_TENXPONENTS)
exp = math.floor(exp) # 1 <= manti... | b0fd7a961fbd0f796fc00a5ce4005c7aa9f92950 | 3,650,982 |
from typing import Callable
def decide_if_taxed(n_taxed: set[str]) -> Callable[[str], bool]:
"""To create an decider function for omitting taxation.
Args:
n_taxed: The set containing all items, which should not be taxed.
If empty, a default set will be chosen.
Returns:
D... | c13c7e832b86bd85e2cade03cbc84a43893dfe17 | 3,650,983 |
def generate_two_cat_relation_heat_map():
"""
A correlation matrix for categories
"""
data = Heatmap(
z=df_categories.corr(),
y=df_categories.columns,
x=df_categories.columns)
title = 'Correlation Distribution of Categories'
y_title = 'Category'
x_title = 'Category'
... | 90efbffd54c723eef9297ba0abba71d55a500cd0 | 3,650,984 |
def build_phase2(VS, FS, NS, VT, VTN, marker, wc):
"""
Build pahase 2 sparse matrix M_P2 closest valid point term with of source vertices (nS)
triangles(mS) target vertices (nT)
:param VS: deformed source mesh from previous step nS x 3
:param FS: triangle index of source mesh mS * 3
:param NS: t... | ab3622f5b4377b1a60d34345d5396f66d5e3c641 | 3,650,985 |
def voronoi_to_dist(voronoi):
""" voronoi is encoded """
def decoded_nonstacked(p):
return np.right_shift(p, 20) & 1023, np.right_shift(p, 10) & 1023, p & 1023
x_i, y_i, z_i = np.indices(voronoi.shape)
x_v, y_v, z_v = decoded_nonstacked(voronoi)
return np.sqrt((x_v - x_i) ** 2 + (y_v - y_i) ** 2 + (z_v - z_i) ... | 38c2630d45b281477531fcc845d34ea7b2980dab | 3,650,986 |
def post_update_view(request):
"""View To Update A Post For Logged In Users"""
if request.method == 'POST':
token_type, token = request.META.get('HTTP_AUTHORIZATION').split()
if(token_type != 'JWT'):
return Response({'detail': 'No JWT Authentication Token Found'}, status=status.HTTP... | 8044e12328c5bb63c48f673971ae1ed8727b02b7 | 3,650,987 |
from typing import List
def _is_binary_classification(class_list: List[str]) -> bool:
"""Returns true for binary classification problems."""
if not class_list:
return False
return len(class_list) == 1 | 82ada7dd8df93d58fad489b19b9bf4a93ee819c3 | 3,650,988 |
def create_post_like(author, post):
"""
Create a new post like given an author and post
"""
return models.Like.objects.create(author=author, post=post) | f8e07c10076015e005cd62bb3b39a5656ebc45a3 | 3,650,989 |
def translate_entries(yamldoc, base_url):
"""
Reads the field `entries` from the YAML document, processes each entry that is read using the
given base_url, and appends them all to a list of processed entries that is then returned.
"""
if 'entries' in yamldoc and type(yamldoc['entries']) is list:
entries =... | 0c949939020b3bb1017fca5543be8dcc77d03bbf | 3,650,990 |
def get_in(obj, lookup, default=None):
""" Walk obj via __getitem__ for each lookup,
returning the final value of the lookup or default.
"""
tmp = obj
for l in lookup:
try: # pragma: no cover
tmp = tmp[l]
except (KeyError, IndexError, TypeError): # pragma: no cover
... | 73dfcaadb6936304baa3471f1d1e980f815a7057 | 3,650,991 |
import six
def GetSpec(resource_type, message_classes, api_version):
"""Returns a Spec for the given resource type."""
spec = _GetSpecsForVersion(api_version)
if resource_type not in spec:
raise KeyError('"%s" not found in Specs for version "%s"' %
(resource_type, api_version))
spec =... | ece9dd996c52f01bb985af9529b33bb7b12fbfdc | 3,650,992 |
def ips_between(start: str, end: str) -> int:
"""
A function that receives two IPv4 addresses,
and returns the number of addresses between
them (including the first one, excluding the
last one).
All inputs will be valid IPv4 addresses in
the form of strings. The last address will
always be greater than the first o... | aa523ec8a127e2224b7c9fc7a67d720ac4d100ed | 3,650,993 |
def tmNstate(trTrg):
"""Given (newq, new_tape_sym, dir),
return newq.
"""
return trTrg[0] | 17db0bc5cae4467e7a66d506e1f32d48c949e5eb | 3,650,994 |
import argparse
def parse_arguments(args):
"""
Parse the arguments from the user
"""
parser = argparse.ArgumentParser(
description= "Create UniRef database for HUMAnN2\n",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
"-v","--verbose",
h... | d547c0017904d91a930f149a6b085d2e0c87fe88 | 3,650,995 |
def _preprocess_continuous_variable(df: pd.DataFrame, var_col: str, bins: int,
min_val: float = None,
max_val: float = None) -> pd.DataFrame:
"""
Pre-processing the histogram for continuous variables by splitting the variable in buckets.
... | 9c2844497dbe55727f6b2aea17cf7a23e60a3002 | 3,650,996 |
import itertools
def get_pairs(labels):
"""
For the labels of a given word, creates all possible pairs
of labels that match sense
"""
result = []
unique = np.unique(labels)
for label in unique:
ulabels = np.where(labels==label)[0]
# handles when a word sense has on... | 454de57eedf6f272fef2c15b40f84de57ed3fa64 | 3,650,997 |
def iredv(tvp,tton):
""" makes sop tvp irredundant relative to onset truth table"""
res = []
red = list(tvp)
for j in range(len(tvp)):
tvj=tvp[j]&tton #care part of cube j
if (tvj&~or_redx(red,j)) == m.const(0): # reduce jth cube to 0
red[j]=m.const(0)
else: #keep cub... | 5fdb9ed97216b668110908419b364107ed3b7c37 | 3,650,998 |
def ridder_fchp(st, target=0.02, tol=0.001, maxiter=30, maxfc=0.5, config=None):
"""Search for highpass corner using Ridder's method.
Search such that the criterion that the ratio between the maximum of a third order
polynomial fit to the displacement time series and the maximum of the displacement
tim... | ee3198c443885fa9524d12c30aa277d8cd843d27 | 3,650,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.