content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_config_from_file(file: str) -> MachConfig:
"""Parse file into MachConfig object."""
click.echo(f"Parsing {file}...")
dictionary_config, encrypted = yaml.load(file)
try:
with warnings.catch_warnings():
# Suppress a 'Unknown type ForwardRef('Component')' warning from datacla... | 52,200 |
def build_birnn_multifeature_coattention_model(
voca_dim, time_steps, num_feature_channels, num_features, feature_dim, output_dim, model_dim, atten_dim, mlp_dim,
item_embedding=None, rnn_depth=1, mlp_depth=1,
drop_out=0.5, rnn_drop_out=0., rnn_state_drop_out=0.,
trainable_embedding=False... | 52,201 |
def main() -> None:
"""
:rtype: None
"""
import time
toaster = Win10Toaster()
toaster.show("Hello World!!!", "Python is 10 seconds awsm!", duration=10)
while toaster.notification_active: # Wait for threaded notification to finish
time.sleep(0.1) | 52,202 |
def splitext(value):
"""
Return a filename sans extension. Alias to os.splitext.
"""
return pathsplitext(value)[0] | 52,203 |
def normspec(*specs, smooth=False, span=13, order=1):
"""
Normalize a series of 1D signals.
**Parameters**\n
*specs: list/2D array
Collection of 1D signals.
smooth: bool | False
Option to smooth the signals before normalization.
span, order: int, int | 13, 1
Smoothing pa... | 52,204 |
def load():
"""
Load the bibmanager database of BibTeX entries.
Returns
-------
List of Bib() entries. Return an empty list if there is no database
file.
Examples
--------
>>> import bibmanager.bib_manager as bm
>>> bibs = bm.load()
"""
try:
with open(u.BM_DATABASE, 'rb') as handle:
... | 52,205 |
def write_out_csv(csv_file,fieldnames,values=[]):
"""write all values in csv format to outfile.
Values is list of dicts w/ keys matching fieldnames.
To write header to file, omit `values`
"""
log.info('Writing csv to {}'.format(csv_file))
try:
with open(csv_file, 'a') as csvout:
... | 52,206 |
def repeat_n_m(v):
"""Repeat elements in a vector .
Returns a vector with the elements of the vector *v* repeated *n* times,
where *n* denotes the position of the element in *v*. The function can
be used to order the coefficients in the vector according to the order of
spherical harmonics. If *v* i... | 52,207 |
def contingency(cont_table=None, alpha=0.05, precision=4):
"""
Check RULE of FIVE before running the test
>>> return chi2, p, dof, ex
"""
chi2, p, dof, ex = stats.chi2_contingency(cont_table, correction=False)
chi2_cv = stats.chi2.ppf(1 - alpha, dof)
flag = False
if p < alpha:
fl... | 52,208 |
def smp_dict():
"""Returns a dictionary containing typical options for a generic Sample object"""
out = base_dict()
out['mro']['current'] = ['Sample']
out['name']['current'] = 'Sample'
ao(out, 'idx', 'Integer', attr=['Hidden'])
ao(out, 'ii', 'Integer', attr=['Hidden'])
ao(out, 'initialDimens... | 52,209 |
def init():
"""
Intialize parameters that will be used in the program.
Parameters
----------
None
Returns
----------
dataset: ndarray
The whole dataset read from the input file.
outFileName: String
Name of output file.
iterNum: int
Number of iteration.
... | 52,210 |
def setup():
"""
Connect to the Arango database and Elasticsearch.
Returns
-------
Connection, Database, list
1. The connection to Elasticsearch
2. The ArangoDB database that holds the collection
3. The list of fields that are take over from ArangoDB to Elasticsearch
Ra... | 52,211 |
def avms():
""" Fonction qui permet de lancer le test avms
Paramètres : aucun
Return : rien
"""
change_text_button_avms()
main_avms() | 52,212 |
def test_timedelta_tests():
"""These test cases are taken from CPython's Lib/test/datetimetester.py"""
# Create compatibility functions so rest of test can be pasted with minimal
# changes
def eq(a, b):
assert a == b
def td(days=0, seconds=0, microseconds=0):
return TimeDelt... | 52,213 |
def auth():
"""
Test authentication using generated configuration
"""
app_dir = typer.get_app_dir(APP_NAME)
config_path: Path = Path(app_dir) / "config.yaml"
if not config_path.is_file():
typer.echo("Config file doesn't exist yet. Please run 'setup' command first.")
return
tr... | 52,214 |
async def channel_newmessage_handler(event: NewMessage.Event):
"""Continuously listen to channel updates, save new messages"""
if event.is_channel:
db.save_message(event.message) | 52,215 |
def test_fold_collect_recursion_limit():
"""Ensures that ``.collect_all`` method is recurion safe."""
limit = sys.getrecursionlimit() + 1
iterable = (Success(1) for _ in range(limit))
expected = Success((1,) * limit)
assert Fold.collect_all(iterable, Success(())) == expected | 52,216 |
def shorten_line(line: Line, intersections: list[Matchstick], gw: GameWindow) -> Line:
"""
Shorten a line so that it fits nicely within the row and doesn't get too close to adjacent sticks when drawn
:param line: the line to shorten
:param intersections: the sticks that the line intersects with
:param gw: th... | 52,217 |
def uprev_overlays(overlays, build_targets=None, chroot=None, output_dir=None):
"""Uprev the given overlays.
Args:
overlays (list[str]): The list of overlay paths.
build_targets (list[build_target_lib.BuildTarget]|None): The build targets
to clean in |chroot|, if desired. No effect unless |chroot| is... | 52,218 |
def find_closest_pucker(phi, theta, pucker_dict):
"""
Calculated based on cord length:
delta_x = sin(phi2) * cos(theta2) - cos(ph1)*cos(theta1)
delta_y = sin(phi2) * sin(theta2) - cos(phi1)*sin(theta1)
delta_z = cos(phi2) - cos(phi1)
chord_length = sqrt( delta_x^2 + delta_y^2 + delta_z^2)
... | 52,219 |
def auto_type_change():
""" Python automatically changes type of a variable. Also it's automatically provides extra precision
for large numbers.
"""
value = 62
print("This value can hold char variable: " + str(value))
value = 3 * (10 ** 5)
print("Now it's int: " + str(value))
... | 52,220 |
def signal_ramp(k_start):
"""Signal generator for a ramp signal
Parameters
----------
k_start : SignalUserTemplate
the sampling index as returned by counter() at which the ramp starts increasing.
Returns
-------
SignalUserTemplate
the output signal
Details
-------
... | 52,221 |
def test_quiet_option(run, runner):
"""sync command can be run with `--quiet` or `-q` flag."""
with open("requirements.txt", "w") as req_in:
req_in.write("six==1.10.0")
out = runner.invoke(cli, ["-q"])
assert not out.stderr_bytes
assert out.exit_code == 0
# for every call to pip ensur... | 52,222 |
def pooling_layer(inputs, pooling=constants.MAXPOOL, pool_size=2, strides=2,
name=None):
"""
Args:
inputs: (4d tensor) input tensor of shape
[batch_size, height, width, n_channels]
pooling: (Optional, {AVGPOOL, MAXPOOL}, defaults to MAXPOOL) Type of
pooling to be used, which... | 52,223 |
def test_equal_ImageDecoderSlice_ImageDecoder():
"""
Comparing results of pipeline: (ImageDecoder -> Slice), with the same operation performed by fused operator
"""
batch_size =128
eii = ExternalInputIterator(128)
pos_size_iter = iter(eii)
class NonFusedPipeline(Pipeline):
def _... | 52,224 |
def count_tiles(reader_or_writer: Union[BioReader, BioWriter]) -> int:
""" Returns the number of tiles in a BioReader/BioWriter.
"""
tile_size = TILE_SIZE_2D if reader_or_writer.Z == 1 else TILE_SIZE_3D
num_tiles = (
len(range(0, reader_or_writer.Z, tile_size)) *
len(range(0, reader_or_w... | 52,225 |
def main():
"""Entry point."""
config = init_app()
uvicorn.run(
'omoide.presentation.app:app',
host=config.app.host,
port=config.app.port,
debug=config.app.debug,
reload=config.app.reload,
) | 52,226 |
def async_resend_permission_slip(slip_id):
"""Resend notification for specific field trip."""
slip = PermissionSlip.objects.get(id=slip_id)
emails = slip.generate_emails()
send_mass_mail(tuple(emails)) | 52,227 |
def workflow(sheetid, tablename):
"""Process"""
cursor = pgconn.cursor()
cursor.execute(f"DROP TABLE IF EXISTS {tablename}")
sheet = ss.Reports.get_report(sheetid, page_size=1000)
cols = []
for col in sheet.columns:
cols.append(cleaner(col.title))
cursor.execute(
(
... | 52,228 |
def fn(groups, lsv_fn):
"""Regular expression did not contain a match"""
field, pattern = groups
route_regex = re.compile(pattern)
return lambda data: route_regex.search(str(lsv_fn(data, field))) == None | 52,229 |
def airq_data_loader(normalize="none"):
"""Function to load the Air Quality dataset into TF dataset objects
The data is loaded, normalized, padded, and a mask channel is generated to indicate missing observations
The raw csv files can be downloaded from:
https://archive.ics.uci.edu/ml/datas... | 52,230 |
def get_living_neighbors(i, j, generation):
"""
returns living neighbors around the cell
"""
living_neighbors = 0 # count for living neighbors
neighbors = [(i-1, j), (i+1, j), (i, j-1), (i, j+1),
(i-1, j+1), (i-1, j-1), (i+1, j+1), (i+1, j-1)]
for k, l in neighbors:
... | 52,231 |
def hook_makeOutline(VO, blines):
"""Return (tlines, bnodes, levels) for Body lines blines.
blines is either Vim buffer object (Body) or list of buffer lines.
"""
Z = len(blines)
tlines, bnodes, levels = [], [], []
tlines_add, bnodes_add, levels_add = tlines.append, bnodes.append, levels.append
... | 52,232 |
def display_features():
"""
Cut-down version of the Map Viewing Client.
Used as a link from the RHeader.
URL generated server-side
Shows all locations matching a query.
@ToDo: Most recent location is marked using a bigger Marker.
@ToDo: Move to S3Method (will then... | 52,233 |
def domain_min():
""" Variable evaluator that represents the minimum value in the current domain
of the variable chosen by the search.
Returns:
An evaluator of integer variable
"""
return CpoFunctionCall(Oper_domain_min, Type_IntVarEval, ()) | 52,234 |
def StrToList(val):
""" Takes a string and makes it into a list of ints (<= 8 bits each)"""
return [ord(c) for c in val] | 52,235 |
def our_completion_DFA(states, alphabet, transitions,
initialState, finalStates):
""" For every transition (from, to, c) adds every transition
(from, to, s') where s' represents c plus every other symbol """
table = powerset_table(alphabet)
new_alphabet = alphabe... | 52,236 |
def createCopy(source):
"""Link the source set to the destination
If one does not find the value in the destination set,
search will go on to the source set to get the value.
Value from source are copy-on-write. i.e. any try to
modify one of them will end up putting the modified value
in t... | 52,237 |
def serviceCIDR(runner: Runner):
"""
Get service IP range, based on heuristic of constructing CIDR from
existing Service IPs. We create more services if there are less
than 8, to ensure some coverage of the IP range.
"""
def get_service_ips():
services = json.loads(
runner.g... | 52,238 |
def generate_data(network_list, data_set, Lb, Ub, total_data_num, NUM):
"""
NUM为需要生成的数据量
"""
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = "cpu"
# 网络使用
total_predicts_data = []
for k in range(len(data_set)):
model = network_list[k]
da... | 52,239 |
def fail():
"""
Function for manually failing a test in case you want a specific test that does not fit any check function
"""
check_test_in_progress()
global n_failed_tests, test_failed
if not test_failed:
n_failed_tests += 1
test_failed = True | 52,240 |
def lint_all_wsgi_entrypoint_imports(files_to_lint):
"""Enforce that every WSGI entrypoint imports appengine_config first.
On App Engine Standard, appengine_config is guaranteed to be imported
before anything else. But this isn't guaranteed on VM, which is bad
because our code assumes it! So we requi... | 52,241 |
def convert_audio(
in_sound: ArrayLike, in_rate: int, *, out_rate: int, out_format: DTypeLike, out_channels: int
) -> NDArray[Any]:
"""Convert an audio sample into a format supported by this device.
Returns the converted array. This might be a reference to the input array if no conversion was needed.
... | 52,242 |
def normalize_tags(string):
"""Return a list of normalized tags from a string with comma separated
tags"""
tags = string.split(',')
result = []
for tag in tags:
normalized = normalize(tag)
if normalized and not normalized in result:
result.append(normalized)
return r... | 52,243 |
def basemz(df):
"""
The mz of the most abundant ion.
"""
# returns the
d = np.array(df.columns)[df.values.argmax(axis=1)]
return Trace(d, df.index, name='basemz') | 52,244 |
def M_matrix_old(s, c, m, l_max):
"""Legacy function. Same as :meth:`M_matrix` except trying to be cute
with ufunc's, requiring scope capture with temp func inside
:meth:`give_M_matrix_elem_ufunc`, which meant that numba could not
speed up this method. Remains here for testing purposes. See
document... | 52,245 |
def save_hybrid_code_in_output_directory(whole_ast_info: WholeASTInfoClass) -> None:
"""
Write copied_module_for_analysis which is hybrid code to hybrid_code directory
"""
logger.info("Save hybrid code to hybrid_code directory")
if whole_ast_info.offloading_whole_application:
logger.info("... | 52,246 |
def create_model(modelfunc, fname='', listw=[], outfname=''):
""":modelfunc: is a function that takes a word and returns its
splits. for ngram model this function returns all the ngrams of a
word, for PCFG it will return te split of the password.
@modelfunc: func: string -> [list of strings]
@fnam... | 52,247 |
def shred(filepath: Union[str, Path], erase_function: callable = erase_helpers.shred):
"""
Function to shred file content.
If filepath is symbolic link, file will be shred that symlink points to.
File operation exceptions are not handled.
:param filepath: Path to file specified with Path class or... | 52,248 |
def iterable_to_wikitext(items: Collection[object]) -> str:
"""Convert iterable to wikitext."""
if len(items) == 1:
return f"{next(iter(items))}"
text = ""
for item in items:
text += f"\n* {item}"
return text | 52,249 |
def ElemMatch(q, *conditions):
"""
The ElemMatch operator matches documents that contain an array field with at
least one element that matches all the specified query criteria.
"""
new_condition = {}
for condition in conditions:
if isinstance(condition, (Condition, Group)):
... | 52,250 |
def get_links(client: SymphonyClient) -> List[Link]:
"""This function returns all existing links
Returns:
List[ `pyinventory.common.data_class.Link` ]
Example:
```
all_links = client.get_links()
```
"""
links = LinksQuery.execute(client, firs... | 52,251 |
def read_inference_command():
"""
read inputs from the command line
:return:
"""
cprint('[INFO]', bc.dgreen, 'read inputs from the command')
try:
parser = ArgumentParser()
parser.add_argument("--deezy_mode",
help="DeezyMatch mode",
... | 52,252 |
def set(data,c):
"""
Set Data to a Constant
Parameters:
* data Array of spectral data.
* c Constant to set data to (may be complex)
"""
data[...,:]=c
return data | 52,253 |
def browse_announcements():
"""
This function is used to browse Announcements Department-Wise
made by different faculties and admin.
@variables:
cse_ann - Stores CSE Department Announcements
ece_ann - Stores ECE Department Announcements
me_ann - Stores ME Department Announcement... | 52,254 |
def set_point_restraint(self,point,restraints):
"""
params:
point: str, name of point
restraints: bool, list of 6 to set restraints
return:
status of success
"""
try:
assert len(restraints)==6
pt=self.session.query(Point).filter_by(name=point).first()
... | 52,255 |
def test_devices_success(flask_app, app, db):
""" To verify that de_registration device
method is working properly and response is correct"""
headers = {'Content-Type': 'multipart/form-data'}
request_data = copy.deepcopy(DE_REG_REQ_DATA)
request_data['file'] = 'de-reg-test-file.txt'
de_regi... | 52,256 |
def create_blank_file(dirpath):
"""Create a directory from the project directory."""
path = os.path.join(PROJECT_DIRECTORY, dirpath)
LOGGER.debug("Creating blank file %s", path)
Path(path).touch() | 52,257 |
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6) -> float:
"""Numpy implementation of the Frechet Distance.
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
and X_2 ~ N(mu_2, C_2) is
d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
S... | 52,258 |
def get_meta(instance: Any) -> Dict[str, Any]:
"""
Returns object pjrpc metadata.
"""
return getattr(instance, '__pjrpc_meta__', {}) | 52,259 |
def initial_pop(size, password):
"""
Generate a population consisting of random words, each with the same
length as the password, and the population has the size specified.
"""
return [word_generate(len(password)) for _ in range(size)] | 52,260 |
def getAllComicImagePaths(source = "./comic_pages"):
"""Collect an ordered list of comic page images."""
p = Path(source)
files = [x for x in p.iterdir() if x.is_file()]
return [f for f in sorted(files) if _isImage(f)] | 52,261 |
def job_use(jobs, d_from, target, d_to='', use_unit='cpu', job_state='all',
time_ref='', grouper_interval='S', usage_interval='H', serialize_queued='', serialize_running='',
serialize_dist=''):
"""Takes a DataFrame full of job information and
returns usage based on specified unit.
... | 52,262 |
def login():
"""[summary]
Returns:
[type]: [description]
"""
if current_user.is_authenticated:
return flask.redirect(flask.url_for("bp.index"))
if flask.request.method == "POST":
if flask.request.form["submit_button"] == "GOOGLE LOGIN":
# Find out what URL to hi... | 52,263 |
def settings_page():
"""
The data web pages where you can download/delete the raw gnss data
"""
return render_template("settings.html") | 52,264 |
def SaveNumResults(doc:NexDoc, fileName):
"""Saves the numerical results to a text file with the specified name."""
return NexRun("SaveNumResults", locals()) | 52,265 |
def load_laplacian(n=0):
"""
Laplacians have these normalizations (from Ashish Raj):
n=0: L0 = diag(rowdegree) - C;
n=1: L1 = eye(nroi) - diag(1./(rowdegree+eps)) * C;
n=2: L2 = eye(nroi) - diag(1./(sqrt(rowdegree)+eps)) * C* diag(1./(sqrt(coldegree)+eps)) ;
n=3: L3 = eye(nroi) -... | 52,266 |
def parse_host_port(address, default_port=None):
"""
Parse an endpoint address given in the form "host:port".
"""
if isinstance(address, tuple):
return address
def _fail():
raise ValueError("invalid address %r" % (address,))
def _default():
if default_port is None:
... | 52,267 |
def free_residents(residents_prefs_dict, matched_dict):
"""
In this function, we return a list of resident who do not have empty prefrences list and unmatched with any hospital.
"""
fr = []
for res in residents_prefs_dict:
if residents_prefs_dict[res]:
if not (any(res in mat... | 52,268 |
def test_social_constructor():
"""Testting that social works properly"""
assert user1.name.lower() == 'nick'
assert user2.name.lower() == 'devin'
assert user1.location.lower() == 'arizona'
assert user2.location.lower() == 'ohio'
assert user1.upvotes == 0
assert user2.upvotes == 250 | 52,269 |
def com_roboto_fonts_check_vertical_metrics(ttFont):
"""Check vertical metrics are correct"""
failed = []
expected = {
# Android values come from v2.136 android fonts
# https://github.com/googlefonts/roboto/releases/tag/v2.136
("head", "yMin"): -555,
("head", "yMax"): 2163,
... | 52,270 |
def com_google_guava_guava(**kwargs):
"""grpc java plugin and jars
"""
name = "com_google_guava_guava"
artifact = get_artifact(name, "com.google.guava:guava:20.0", kwargs)
sha1 = get_sha1(name, "89507701249388e1ed5ddcf8c41f4ce1be7831ef", kwargs)
jar(name, artifact, sha1) | 52,271 |
def index():
"""View of providing a feedback from the client side"""
form = FeedbackForm()
if form.validate_on_submit():
try:
data = {
'email': form.email.data,
'title': form.title.data,
'content': form.content.data,
}
... | 52,272 |
def predict_increment(big_n, obs_t, mu, basis_lag, coef):
"""
This should return predicted increments
between successive observations
"""
rate_hat = predict_intensity(
big_n, obs_t, mu, basis_lag, coef
)
increment_size = np.diff(obs_t)
return rate_hat * increment_size | 52,273 |
def get_drive_path(volumename, alldrivelist, drive_type=None):
"""Return the drive letter (windows) or mount point (linux) of a volume's name
volumename is the name of the volume you want the mount point.
alldrivelist is a list of drives or volume:
- Windows: The list should be a list of list, like [['M6... | 52,274 |
async def runCmdWithUser(cmd, addToEnv=None) :
"""Runs a command allowing the users to interact with the command and
then returns the return code. Based upon the Python asyncio subprocesses
documentation. """
if addToEnv is not None :
for aKey, aValue in addToEnv.items() :
os.environ[aKey] = aValue
... | 52,275 |
def test_file_upload_with_users(svc_client):
"""Check successful file upload and listing based on user auth header."""
headers_user1 = {'Renku-User-Id': '{0}'.format(uuid.uuid4().hex)}
headers_user2 = {'Renku-User-Id': '{0}'.format(uuid.uuid4().hex)}
response = svc_client.post(
'/cache.files_up... | 52,276 |
def _dualprf_error_unwrap(data_ma, ref_ma, err_mask, pvel_arr, prf_arr):
"""
Finds the correction factor that minimises the difference between
the gate velocity and the reference velocity
Parameters
----------
data_ma : masked array
Data
ref_ma : masked array
Reference data
... | 52,277 |
def segmentTubes(rir_image, vascularModelFile, output_prefix,
vess_seed_prob=0.95, vess_scale=0.1):
"""Extract the tubes from an image. rir_image is the original image,
but (R)esampled (I)f (R)equested.
"""
# compute seed image
vessProbImageFile = output_prefix + "_vess_prob.mha"
... | 52,278 |
def revoke_privilege_from_role_via_user_with_grant_option(self, table_type, node=None):
"""Check that user is unable to revoke a column they dont have acces to from a role.
"""
user_name = f"user_{getuid()}"
role_name = f"role_{getuid()}"
table_name = f"table_{getuid()}"
if node is None:
... | 52,279 |
def load(directory):
"""Loads pkl file from directory"""
with open(directory, 'rb') as f:
data = pickle.load(f)
return data | 52,280 |
def choose(
chooser: Callable[[_TSource], Option[_TResult]]
) -> Callable[[Iterable[_TSource]], Iterable[_TResult]]:
"""Choose items from the sequence.
Applies the given function to each element of the list. Returns
the list comprised of the results x for each element where the
function returns `So... | 52,281 |
def model_classification(actual, predicted):
"""
Prints out RSME, MAE and explained variance score
"""
print('-'*20)
print(f'RMSE: {round(np.sqrt(mean_squared_error(actual, predicted)),2)}')
print('-'*20)
print(f'MAE: {round(mean_absolute_error(actual, predicted),2)}')
print(f'Explaine... | 52,282 |
def TestLagData():
"""Use some simple data to make sure that the LagData routine is working."""
input_data = np.arange(20).reshape((10, 2))
print "Input array:", input_data
(new_data, good_rows) = LagData(input_data, np.arange(-1, 2))
print "Output array:", new_data
print "Good rows:", good_rows | 52,283 |
def main(opts):
"""
SQLdiff
Usage:
sqldiff (<source.sql> <destination.sql>) [--keys] [--constraints]
[--collation] [--include=<NAME>... | --exclude=<NAME>...]
[--drop-tables] [--alter-tables] [--instant]
Options:
--keys Compare keys.
... | 52,284 |
def connect_fast(ntwkA: Network, k: int, ntwkB: Network, l: int) -> Network:
"""
Connect two n-port networks together (using C-implementation)
Specifically, connect ports `k` on `ntwkA` to ports
`l` thru on `ntwkB`. The resultant network has
`(ntwkA.nports + ntwkB.nports - 2)` ports. The port indi... | 52,285 |
def interleave(left, right):
"""Convert two mono sources into one stereo source."""
return numpy.ravel(numpy.vstack((left, right)), order='F') | 52,286 |
def load_jupyter_server_extension(nb_server_app):
"""
Called when the extension is loaded.
Args:
nb_server_app (NotebookWebApplication): handle to the Notebook webserver instance.
"""
web_app = nb_server_app.web_app
host_pattern = '.*$'
route_pattern = url_path_join(web_app.settings... | 52,287 |
async def split_lines(stream):
"""Split the chunks of bytes on new lines.
"""
leftover = ''
async for chunk in stream:
chunk_str = chunk.decode('utf-8')
chunk_str = leftover + chunk_str
chunk_str = chunk_str.lstrip('\n')
lines = chunk_str.split('\n')
# Everything ... | 52,288 |
def DIN(
item_seq_feat_group: EmbdFeatureGroup,
other_feature_group: FeatureGroup,
dnn_hidden_units: Tuple[int] = (64, 32, 1),
dnn_activation: str = "dice",
dnn_dropout: float = 0,
dnn_bn: bool = False,
l2_dnn: float = 0,
lau_dnn_hidden_units: Tuple[int] = (32, 1),
lau_dnn_activation... | 52,289 |
def get_seconds(time_string):
"""
Convert e.g. 1m5.928s to seconds
"""
minutes = float(time_string.split("m")[0])
seconds = float(time_string.split("m")[1].split("s")[0])
return minutes * 60.0 + seconds | 52,290 |
def generate_features_for_all_nodes(n_feature, features_filename):
"""
generates node-list with features for RiWalk-NA
"""
# generate node-features-df
print("\tFeatures generation starts.")
start_time = time.time()
nodes_all_features_df = n_feature.gen_features_all_nodes()
nodes_... | 52,291 |
def sharesnet34(**kwargs):
"""
ShaResNet-34 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, ... | 52,292 |
def rose_fig(metdat, catinfo, category=None, vertloc=80, bins=6, nsector=36, ylim=None, noleg=False,normed=True):
"""**Get Wind Rose Figure**.
Plot the wind rose of a given variable (or category of variables) grouped by a given condition (or set of conditions).
Parameters:
1. metdat (Pandas Da... | 52,293 |
def query_spikeins(accession):
"""
Query spikeines IDs from Encode Websites
"""
query = f'https://www.encodeproject.org/experiments/{accession}/'
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
for div in soup.find_all('div'):
try:
if div['da... | 52,294 |
async def test_reauth_cannot_connect(hass: HomeAssistantType) -> None:
"""Check a reauth flow that fails to connect."""
config_data = {
CONF_HOST: TEST_HOST,
CONF_PORT: TEST_PORT,
}
add_test_config_entry(hass, data=config_data)
client = create_mock_client()
client.async_client_... | 52,295 |
def stack_snapshot(
name,
stack = None,
extra_deps = {},
vendored_packages = {},
snapshot = "",
local_snapshot = None,
packages = [],
flags = {},
haddock = True,
setup_deps = {},
tools = [],
components = {},
stack_up... | 52,296 |
def validate_mendatory_fields_for_grd(doc):
"""
Check all the mendatory fields are set by grd
"""
field_list = [{'Trade Name in Arabic':'one_fm_previous_company_trade_name_in_arabic'},{'Signatory Name':'one_fm_signatory_name'}]
mandatory_fields = []
for fields in field_list:
for fie... | 52,297 |
def get_ticket_status(message:str, socket:socket):
"""
get ticket status
"""
try:
result_factory = conMem.execute('select TicketNum, Status from ticket where TicketNum=?', (message['TicketNum'],))
result_array = result_factory.fetchone()
target_dict = dict(zip(('TicketNum', 'Stat... | 52,298 |
def _is_status_not_found(error):
"""Decodes the error from the API to check if status is NOT_FOUND.
Args:
error (errors.HttpError): The error response from the API.
Returns:
bool: True if the error is application not found, else False.
"""
if isinstance(error, errors.HttpError) and... | 52,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.