content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def update_document(sender, **kwargs):
"""Update document on added/changed records."""
app_label = sender._meta.app_label
model_name = sender._meta.model_name
if app_label == "resources_portal":
if model_name in ["resources_portal_user", "organization", "material"]:
registry.update(... | 63,700 |
def create_remote_executor(
channel: GRPCChannel,
cardinalities: Mapping[placements.PlacementLiteral, int],
) -> _executor_bindings.Executor:
"""Constructs a RemoteExecutor proxying service on `channel`."""
uri_cardinalities = data_conversions.convert_cardinalities_dict_to_string_keyed(
cardinalities)... | 63,701 |
def complex_abs(data):
"""
Compute the absolute value of a complex valued stacked input array.
Args:
data (numpy.array): A complex valued array with real and
imaginary parts stacked,where the size of the final dimension should be
2.
Returns:
numpy.array: Absolute value of data
"""
... | 63,702 |
def _build_batch_norm_params(batch_norm, is_training):
"""Build a dictionary of batch_norm params from config.
Args:
batch_norm: hyperparams_pb2.ConvHyperparams.batch_norm proto.
is_training: Whether the models is in training mode.
Returns:
A dictionary containing batch_norm parameters.
"""
batc... | 63,703 |
def _slice_chr22(in_bam, data):
"""
return only one BAM file with only chromosome 22
"""
sambamba = config_utils.get_program("sambamba", data["config"])
out_file = "%s-chr%s" % os.path.splitext(in_bam)
if not utils.file_exists(out_file):
bam.index(in_bam, data['config'])
with con... | 63,704 |
def reset():
"""Clear all compile caches and restore initial state"""
for code in convert_frame.input_codes.seen + convert_frame.output_codes.seen:
reset_code(code)
convert_frame.input_codes.clear()
convert_frame.output_codes.clear()
resume_execution.ContinueExecutionCache.cache.clear() | 63,705 |
def search_abstracts(search_terms, reldate):
"""
:arg list search_terms:
:arg int reldate:
:returns object:
"""
query = '"{}"'.format('" OR "'.join(search_terms))
return Entrez.read(Entrez.esearch(
db='pubmed', term=query, reldate=reldate, datetype='pdat',
usehistory='y')) | 63,706 |
def tokenize(string: str) -> [str]:
"""Tokenize a string.
:param string: [description]
:type string: str
"""
return string.split(" ") | 63,707 |
def get_liste_match(nb_jour):
"""
Fonction permettant de chercher les matchs qui vont avoir lieu entre aujourd'hui et un horizon en paramètre.
:param nb_jour: Le nombre de jour à parcourir
:return: Un dictionnaire contenant pour chaque date la liste des matchs du jour
:rtype: dict
"""
# Init... | 63,708 |
def test_home_returns_200_ok(testapp, fill_the_db):
"""List view should always return 200 ."""
response = testapp.get('/')
assert response.status_code == 200 | 63,709 |
def setBvar(value):
"""If `value` is a dict returns a generic_json object, otherwise it returns the value
- - - - -
**Args**:
- `value` (any type): value to assing
**Returns**
- `generic_json` if value is a dict, otherwise it returns the value
"""
if type(value) == dict:
retur... | 63,710 |
def convex_attributes(variables):
"""Returns a list of the (constraint-generating) convex attributes present
among the variables.
"""
return attributes_present(variables, CONVEX_ATTRIBUTES) | 63,711 |
def LMStep4InitializePyBrainNetworkForLearning(fNetwork):
"""
This function realize Learning mode step:
4. Initialize empty PyBrain network for learning or reading network configuration from file.
fNetwork is a PyBrain format neural network, created at 1st step.
Function returns True if all operatio... | 63,712 |
def is_installed(service):
"""Check whether the Snips service `service` is installed.
Args:
service (str): The Snips service to check.
Returns:
bool: True if the service is installed; False otherwise.
Example:
>>> is_installed('snips-nlu')
True
.. versionadded:: ... | 63,713 |
def recreate_db():
"""
Recreates a local database. You probably should not use this on
production.
"""
db.drop_all()
db.create_all()
for theme in loan_themes:
data = {}
data["loan_theme"] = theme
t = Theme(data)
db.session.add(t)
for partner in partner_nam... | 63,714 |
def trunc(s, length):
"""Truncate a string to a given length.
The string is truncated by cutting off the last (length-4) characters
and replacing them with ' ...'
"""
if s and len(s) > length:
return s[:length - 4] + ' ...'
return s or '' | 63,715 |
def user_preference_form_builder(instance, preferences=[], **kwargs):
"""
A shortcut :py:func:`preference_form_builder(UserPreferenceForm, preferences, **kwargs)`
:param user: a :py:class:`django.contrib.auth.models.User` instance
"""
return preference_form_builder(
UserPreferenceForm,
... | 63,716 |
def get_parser(subparsers, parent=None):
""" "Define and return a subparser for the tune subcommand."""
parser = subparsers.add_parser(
"tune",
description="Tune model using the ML on MCU flow.",
parents=[parent] if parent else [],
add_help=(parent is None),
)
parser.set_... | 63,717 |
def find_prime(bits: int) -> int:
"""Returns a prime number with the specified amount of bits."""
p = random_odd(bits)
while True:
# if p is not coprime with M then it isn't prime.
if gcd(p, M) != 1:
p += 2
continue
if miller_rabin(p, 10):
return p... | 63,718 |
def run(_config, _log, _run):
"""
this is the main function that runs evaluation of the model best model for a given run_id once
"""
# checks on the config
# check_config(_config)
np.random.seed(_config['data_generation']['seed'])
tf.random.set_seed(_config['data_generation']['seed'])
e... | 63,719 |
def stop_configuration_recorder(ConfigurationRecorderName=None):
"""
Stops recording configurations of the AWS resources you have selected to record in your AWS account.
See also: AWS API Documentation
:example: response = client.stop_configuration_recorder(
ConfigurationRecorderName='... | 63,720 |
def sort_values(values: list[tuple]) -> list[tuple]:
"""Returns a list of tuples sorted by x value (the value at index 0 of the inner tuple."""
return sorted(values, key=operator.itemgetter(0)) | 63,721 |
def test_get_bucket_name_and_file_path( moto_boto, path, url, ftype,expected):
"""
Check if the bucket name and path is extracted correctly for file and folders
"""
trans = S3Transput(path, url, ftype)
assert trans.get_bucket_name_and_file_path() == expected | 63,722 |
def calc_rank(age, is_veteran=False, has_disability=False):
"""
Calculate a participant's rank. A higher number is higher ranked (top of the list).
(i.e., Reverse this when sorting.)
Change this function to change the ranking algorithm.
The code in the comments below is a ranking system based ... | 63,723 |
def say(text: str) -> str:
"""Return an ASCII art skeleton with a speech bubble
Args:
text: What to put in the speech bubble
>>> print(say("Hello")[1:28])
-------
( Hello )
-------
"""
template = Template(template_path.read_text())
return template.render(text=text) | 63,724 |
def clean_lines(text):
"""Clear out comments, blank lines, and leading/trailing whitespace."""
lines = (line.strip() for line in text.splitlines())
lines = (line.partition('#')[0].rstrip()
for line in lines
if line and not line.startswith('#'))
glob_all = f'{GLOB_ALL} '
... | 63,725 |
def jwtauth(handler_class):
"""
Class decorator to check for authorization
"""
# pylint: disable=W0613
def wrap_execute(handler_execute):
def require_auth(handler, kwargs):
auth = handler.request.headers.get('Authorization')
token_validation_res = validate_toke... | 63,726 |
def js_prerelease(command):
"""decorator for building minified js/css prior to another command"""
class DecoratedCommand(command):
def run(self):
print('inner runnn.....')
try:
self.distribution.run_command('jsdeps')
except Exception as e:
... | 63,727 |
def is_sequence(obj):
"""Check if `obj` is a sequence, but not a string or bytes."""
return isinstance(obj, Sequence) and not BinaryClass.is_valid_type(obj) | 63,728 |
def list_geo_file(folder=""):
"""Lists all the files in the folder named "folder"
contained in GeoWatch Labs Agricultural Maps.
Args:
folder (str): folder name in which to search in GeoWatch Labs Agricultural
Maps folder.
Returns:
list_data_file (list): list of files in GeoWatc... | 63,729 |
def is_user_stasised(nick):
"""Checks if a user is in stasis. Returns a tuple of two items.
First parameter is True or False, and tells if the user is in stasis.
If the first parameter is False, the second will always be None.
If the first parameter is True, the second is an integer of the amount
o... | 63,730 |
def set_crl_distribution_point_extension(exts, cert):
"""Specify URI(s) for CRL distribution point(s)."""
uris = cert.get('extensions', {}).get('crlDistributionPoints')
if not uris:
return
exts.append(OpenSSL.crypto.X509Extension(b'crlDistributionPoints', False, (','.join(uris)).encode('utf-8')... | 63,731 |
def expose(class_method):
"""
Decorator which exposes given method into interface
:param class_method: method to expose
:return: given method with modifications
"""
class_method.is_exposed = True
return class_method | 63,732 |
def merge_length_list(lists):
"""
Merge the list that demonstrates the word length
"""
res_list = []
for l in lists:
if len(res_list) < len(l):
res_list[len(res_list):] = [0] * (len(l)-len(res_list))
for length, num in enumerate(l):
res_list[length] += num
... | 63,733 |
def func(pseudo_state, a1, a2, b1, b2, c1, c2, d1, d2):
"""
quadratic fit function for the Bellman value at given pseudo-state
:param pseudo_state: list(float) - list of the four state variables for a given state
:param a1, a2, ... d2: float - parameters of the quadratic fit function
"""
sum = a1*pseudo_state[0... | 63,734 |
def _parallel_for(sequence, produce, retire, num_threads=num_cores, queue_size=num_cores):
"""Multi-threaded for loop
See the implementation of `_sequential_for` to get the basic idea. This parallel
version is functionally identical but executes on multiple threads simultaniously
thanks to C++. The `pr... | 63,735 |
async def fav_(request:Request,user_id:int=None,authorization: str = Header(None),info : dict=Depends(is_valid_token),insert:str=None,delete:str=None,toggle:str=None):
"""gallerys endpoint"""
token_user_id=int(info['id'])
token_user_secret=info["secret"]
username=None
if user_id:
resp=... | 63,736 |
def validateMembership(likelihood, p, mc_source_id=1):
"""
Plot membership probabilities and MC source ids together.
"""
cut_mc_source_id = (likelihood.catalog.mc_source_id == mc_source_id)
# Spatial
projector = ugali.utils.projector.Projector(likelihood.kernel.lon, likelihood.kernel.lat)
... | 63,737 |
async def setup_bot_commands(dispatcher: Dispatcher):
"""
Here we setup bot commands to make them visible in Telegram UI
"""
bot_commands = [
types.BotCommand(command="/id", description="Tell your ID or group's ID"),
types.BotCommand(command="/help", description="Help and source code")
... | 63,738 |
def download_sentinel_from_creodias(scene_id: str, file_path: str):
"""Download sentinel image from CREODIAS provider.
Args:
scene_id Sentinel scene id
file_path Path to save sentinel
"""
credentials = get_credentials().get('aws')
if credentials is None:
raise RuntimeError(... | 63,739 |
def intersection(box1, box2):
"""
Args:
box1: bounding box
box2: bounding box
Returns:
float: the area that intersects the two boxes
"""
y_min1, x_min1, y_max1, x_max1 = box1
y_min2, x_min2, y_max2, x_max2 = box2
min_ymax = min(y_max1, y_max2)
max_ymin = max(y_mi... | 63,740 |
def make_json_buffer(json_obj):
"""Returns a file-like object containing json_obj serialized to JSON
>>> f = make_json_buffer([1, 2, 3, True, {u'distance': 4.5}])
>>> f.read()
'[1, 2, 3, true, {"distance": 4.5}]'
"""
return make_string_buffer(json.dumps(json_obj)) | 63,741 |
def remove_emoji(string):
"""
Remove emoticons from a text string and
return a cleaned string
"""
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"... | 63,742 |
def delete_project():
"""
删除项目
:return:
"""
data = request.get_json()
project_id = data["project_id"]
project = Project.objects.filter(id=project_id).first_or_404()
project.delete()
devices = Device.objects.filter(project_id=project_id).get_or_404()
for device in devices:
... | 63,743 |
async def request_transactions(
config, web3: Web3, contract, abi, start_height
) -> AsyncIterator[Tuple[Dict, TxContext]]:
"""Continuously request data from the Ethereum blockchain.
TODO: support websocket API.
"""
logs = get_logs(config, web3, contract, start_height + 1)
async for log in log... | 63,744 |
def verify_proof(request: VerifyProofRequest) -> bool:
"""Verifies the proof
Args:
request: Request for the proof verification operation
Return:
True if verification was successful, False if not
"""
handle = bbs_verify_proof.bbs_verify_proof_context_init()
bbs_verify_proof.bbs_v... | 63,745 |
def _wrapAngle360(lon):
"""wrap angle to [0, 360[."""
lon = np.array(lon)
return np.mod(lon, 360) | 63,746 |
async def purge_all(ctx, amount, *args, **kwargs):
"""
Removes messages in given channel
Args:
ctx:
amount:
*args:
**kwargs:
Returns:
"""
channel = ctx.channel
num = int(amount) + 1 # call is additional
if num >= 1:
def check_true(m):
... | 63,747 |
def extended_5_3_predict(t, power_anaerobic_alactic, power_anaerobic_decay,
cp, tau_delay, cp_delay, cp_decay, cp_decay_delay, tau):
"""
Credits to Damien Grauser. Source:
https://github.com/GoldenCheetah/GoldenCheetah/blob/master/src/Metrics/ExtendedCriticalPower.cpp
"""
model ... | 63,748 |
def tuplesums(tuplelist):
# type: (List[Tuple[int, int]]) -> Tuple[int, ...]
"""[(a, b), (c, d), (e, f)] -> [sum(a, c, e), sum(b, d, f)]
"""
return tuple(sum(x) for x in zip(*tuplelist)) | 63,749 |
def remove_emoji(data: str) -> str:
"""Remove the emoji from the 'data' string."""
return demoji.replace(data) | 63,750 |
def evaluateVariableResults(variable, timeColumnRef, timeColumnData, refData, testData, starts, ends, weightFactors,
timeIndicator):
"""
Performance difference calculation between variable data sets.
we use different statistical metrics to perform deep comparisions
of the different... | 63,751 |
def test_mult():
"""Simple multiplication testcase. Check types and semantic equivalence."""
mod = tvm.IRModule()
shape = (15, 15)
dtype = "float32"
t = relay.TensorType(shape, dtype)
x = relay.var("x", t)
# f(x) = x*x
y = relay.Function([x], x * x)
mod["main"] = y
mod = trans... | 63,752 |
def session_login_basic(response: Response,
request: Request,
client_id:int=Depends(get_client_id),
session_info=Depends(login_via_pads)
):
"""
## Function
<b>Basic login Authentication.</b>
Supply us... | 63,753 |
def get_header_value(header_list, key):
# type: (List[Tuple[str, str]], str) -> List[str]
"""Filter the header_list with provided key value.
This method is used to parse through the header list obtained from the
SMAPI response header object and retrieve list of specific tuple objects
with keys like... | 63,754 |
def data_by_variable(datalines, variable):
"""
This function takes in a list of datalines and returns
a new list of datalines for a specified variable.
Parameters:
-----------
datalines : list
This is a list of datalines output by Temoa.
variable : string
This is the variabl... | 63,755 |
def compute_gradient_penalty(D, real_samples, fake_samples, opt):
"""Calculates the gradient penalty loss for WGAN GP"""
# Random weight term for interpolation between real and fake samples
alpha = torch.tensor(np.random.random((real_samples.size(0), 1, 1, 1))).float()
if opt.cuda:
alpha = alpha... | 63,756 |
def update_temporal_coverage(hdf_file, start_time, end_time):
"""Update the temporal extents of the S-111 file.
:param hdf_file: The S-111 HDF file.
:param start_time: The new start time.
:param time_file: The new end time.
"""
if 'dateTimeOfFirstRecord' in hdf_file.attrs:
dateTime... | 63,757 |
def remove_skipped_echo_direct_transfer(df, fn):
"""Remove wells that were reported as skipped in the Echo protocol (xml).
This functions works with Echo direct transfer protocols.
Function supports using wildcards in the filename, the first file will be used.
Returns a new dataframe without the skipped... | 63,758 |
def test_pure_strategy_deviation_gains():
"""Test pure strategy deviation gains"""
profiles = [[2, 0, 2, 0],
[2, 0, 1, 1],
[2, 0, 0, 2],
[1, 1, 2, 0],
[1, 1, 1, 1],
[1, 1, 0, 2],
[0, 2, 2, 0],
[0, 2, ... | 63,759 |
def log_access(request, location=None, reason=None):
"""
Checkin form used by LNL members when accessing a storage location (contact tracing)
:param location: The name of the location (must match a location that contains equipment)
:param reason: Should be set to "OUT" if user is checking out of a loca... | 63,760 |
def stg_log(msg = "test log", level="info", filename = "./vc.log", do_print = 1):
"""
msg: info message to be printed
level: info or warning or error
"""
from datetime import datetime
std_log_msg = f"vc: {datetime.now().isoformat(timespec='seconds')}: [{level}]: {msg}"
if (do_print):
... | 63,761 |
def test_create_as_anonymous_user(default_client, user, event):
"""An anonymous user should not be able to create a registration."""
data = _get_registration_post_data(user, event)
url = _get_registration_url(event=event)
response = default_client.post(url, data=data)
assert response.status_code ==... | 63,762 |
def compute_microstructure(molten_salt_system, ensemble, start, stop, step, nbins=500, rdf_flag=True, cn_flag=True, adf_flag=True):
"""
Description:
compute microstructure info including radial distribution fuction(rdf), coordination number(cn) and angle distribution function(adf) using MDAnalysis module. adf ... | 63,763 |
def oep(atoms,orbs,energy_func,grad_func=None,**kwargs):
"""oep - Form the optimized effective potential for a given energy expression
oep(atoms,orbs,energy_func,grad_func=None,**kwargs)
atoms A Molecule object containing a list of the atoms
orbs A matrix of guess orbitals
energy_func... | 63,764 |
def generate(conn: znc.Socket, save_path: str) -> Generator[None, None, str]:
"""Dump latest Signal interface description to file.
See ``jeepney.bindgen.generate``.
"""
from jeepney.bindgen import code_from_xml # type: ignore[import]
message = yield from send_dbus_message(conn, "Signal", "Introsp... | 63,765 |
def deepfool(image, net, device, num_classes=10, overshoot=0.02, max_iter=50):
"""
:param image: 输入图像:1x1x28x28
:param net: network
:device: cuda or cpu
:param num_classes: num_classes (limits the number of classes to test against, by default = 10)
:param overshoot: used as a ter... | 63,766 |
def preprocess_cost_reward(data, ind_trace, steps_per_epoch, window=1):
"""Preprocess the given cost and the given reward and return
the mean, mean+std and mean-std values as metrics. This function
requires data from a single trace (execution). EVolution with respect
to the number of epochs.
"""
... | 63,767 |
def is_valid_url(string: str) -> bool:
"""Returns boolean describing if the provided string is a url"""
result = urlparse(string)
return all((result.scheme, result.netloc)) | 63,768 |
def test_import_wire_transfer(with_bootcamp_title, with_run_title):
"""import_wire_transfer should store a wire transfer in the database and create an order for it"""
user = User.objects.create(email="hdoof@odl.mit.edu")
title = "How to be Evil"
run = BootcampRunFactory.create(
**{"title": title... | 63,769 |
def check_nan(data_dict):
"""Remove the curve if ``nan`` is in ``x`` or ``y`` data.
Parameters
----------
data_dict : dict
Report data dictionary.
Returns
-------
data_dict : dict
Checked report data dictionary.
"""
for plot_name in data_dict.keys():
for t... | 63,770 |
def MLP(
input_shape,
output_size,
loss,
optimizer,
hidden_layers=[32, 16, 8],
dropout=0.0,
activation="linear",
out_activation="linear",
):
"""Multi Layer Perceptron.
Args:
input_shape (tuple): Shape of the input data
output_size (int): Number of neurons of the ... | 63,771 |
def _get_crm_resource_v1(credentials):
"""
Instantiates a Google Compute Resource Manager v1 resource object to call the Resource Manager API.
See https://cloud.google.com/resource-manager/reference/rest/.
:param credentials: The GoogleCredentials object
:return: A CRM v1 resource object
"""
... | 63,772 |
def line_intersection(lines, lines2, abs_tolerance = 1e-14, full_output = False):
"""
Generic Line to line intersection function
:param lines: The first set of lines, with shape [n_lines, 2, 2] where lines[i, 0, :] is the first point of the ith line
:type line: np.ndarray
:param lines2: Th... | 63,773 |
def drop_archive(database):
"""
drop (delete) a scene database
Parameters
----------
database: isos.database.Database
the database to be deleted
Returns
-------
See Also
--------
:func:`sqlalchemy_utils.functions.drop_database()`
Examples
--------
>>> pguse... | 63,774 |
def read_dictionary():
"""
This function open the dictionary file and categorize words by the first two characters
of every word.
"""
global dic
# a, i, o are words with single character
dic["a"] = ["a"]
dic["i"] = ["i"]
dic["o"] = ["o"]
alphabet = ["a", "b", "c", "d", "e", "f", ... | 63,775 |
def get_tag_name(tag):
"""
Get the name field of a tag:
{#x:name_field:t}
Parameters
----------
tag: str
Returns
-------
name: str
"""
name = re.findall(NAME_REGEX, tag)[0]
return name | 63,776 |
def makeBody():
"""
Create HTML for the body element content. This is done as a demo to show
that the code in htmltree.py works in Transcrypted JS as well as in Python.
It could have been accomplished just as easily on the server side.
"""
banner = H1("Nearly Pure Python Web App Demo", style=dic... | 63,777 |
def snap_array_registry(
file_pointer: h5py.File, data_source: str, name_map: Dict[str, str] = None,
) -> Dict[str, Callable]:
"""Generate snap array registry.
Parameters
----------
file_pointer
The h5py file pointer to the snap file.
data_source
The SPH code that produced the d... | 63,778 |
def books_with_missing_labels_with_title():
"""Find English books with missing labels, but with a title
Missing labels are identified by checking if the label is equal to
the QID
Returns an iterable of (book QID, title)
"""
query = f"""
SELECT ?book ?bookLabel ?title WHERE {{
?book w... | 63,779 |
def get_storage(dictionary, index=None):
"""Get a unique storage point within a class method.
Parameters
----------
dictionary : dict
A dictionary used for storage.
index : hashable
An index under which to load the element. Needs to be hashable.
This is useful for functions ... | 63,780 |
def sample_hyperparameters():
"""
Yield possible hyperparameter choices.
"""
return {
"no_components": np.random.randint(5, 64),
"learning_schedule": np.random.choice(["adagrad", "adadelta"]),
"loss": np.random.choice(["bpr", "warp", "warp-kos"]),
"learning_rate": np.ran... | 63,781 |
def download_blob(bucket_name, source_blob_name, destination_file_name):
"""Downloads a blob from the bucket."""
# bucket_name = "your-bucket-name"
# source_blob_name = "storage-object-name"
# destination_file_name = "local/path/to/file"
storage_client = storage.Client()
bucket = storage_clien... | 63,782 |
def waypoint_sampling(X, n_waypoints=100):
"""
Min-max sampling of waypoints in a two dimensional embedding.
:param X:
:param n_waypoints:
:return:
"""
# store waypoints and initiate distances
wps = []
N = X.shape[0]
dists = np.zeros((N, n_waypoints))
# random sampling of f... | 63,783 |
def threadpool_waited_join(thread_object, timeout):
"""
Call threadpool.join() with timeout. If join completed return True, otherwise False
Notice: This function creates another daemon thread and kills it, use with care.
:param thread_object: Thread to join
:param float timeout: timeout in seconds ... | 63,784 |
def write_json(filename, data):
"""Write as json to a temporary file, and afterwards move the file into place."""
with open(filename + ".new", "w") as f:
json.dump(data, f)
os.rename(filename + ".new", filename) | 63,785 |
def processSua(db, filename):
"""Add all entries from the SUA geojason file to the ``SUA`` collection.
Args:
db (object): Handle to database.
filename (str): Should be ``U.S._Special_Use_Airspace.geojson`` possibly
with a path in front.
"""
# Remove all ... | 63,786 |
def create_nation_population_table():
"""Build a nation population table."""
if not isfile(join(OUTPUT_DIR, FIPS_POPULATION_OUT_FILENAME)):
create_fips_population_table()
census_pop = pd.read_csv(join(OUTPUT_DIR, FIPS_POPULATION_OUT_FILENAME), dtype={"fips": str, "pop": int})
nation_pop = pd.Da... | 63,787 |
def get_relevant_terms(
phi: Union[ndarray, DataFrame],
topic: int,
lambda_: float = 0.6) -> Series:
"""Select relevant terms.
Parameters
----------
phi : Union[np.ndarray, DataFrame]
Words vs topics matrix (phi).
topic : int
Topic index.
lambda_ : float ... | 63,788 |
def GetCudaToolkitVersion(vm):
"""Get the CUDA toolkit version on the vm, based on nvcc.
Args:
vm: the virtual machine to query
Returns:
A string containing the active CUDA toolkit version,
None if nvcc could not be found
Raises:
NvccParseOutputError: On can not parse nvcc output
"""
stdo... | 63,789 |
def divided_by_sentences(abstract):
"""Divides abstracts by sentences
:param abstract:load
:return: list of sentences of the abstract
"""
nlp_l = English()
nlp_l.add_pipe(nlp_l.create_pipe('sentencizer'))
doc = nlp_l(abstract)
sentences = [sent.string.strip() for sent in doc.... | 63,790 |
def deep_getsizeof(data, ids=None):
"""
Returns the memory footprint of a (essentially) any object;
based on sys.getsizeof, but uses a recursive method to handle collections
of objects.
"""
if ids is None:
ids = set()
if id(data) in ids:
return 0
size = sys.getsizeof(da... | 63,791 |
def write_submission_pool(outputs, args, dataset,
conf_thresh=0.1,
horizontal_flip=False,
max_workers=20):
"""
For accelerating filter image
:param outputs:
:param args:
:param dataset:
:param conf_thresh:
:param horizontal_flip:... | 63,792 |
def transform_one(transformer, X=None, y=None):
"""Transform the data using one estimator."""
def prepare_df(out):
"""Convert to df and set correct column names and order."""
use_cols = inc or [c for c in X.columns if c not in exc]
# Convert to pandas and assign proper column names
... | 63,793 |
def calculateHeaders(tokens: list, rawHeaders: tuple) -> tuple:
"""
Takes sanitised, tokenised URCL code and the rawHeaders.
Calculates the new optimised header values, then returns them.
"""
BITS = rawHeaders[0]
bitsOperator = rawHeaders[1]
MINREG = 0
MINHEAP = rawHeaders[3]
... | 63,794 |
def lpar_console(cmd_ctx, cpc, lpar, **options):
"""
Establish an interactive session with the console of the operating system
running in an LPAR.
In addition to the command-specific options shown in this help text, the
general options (see 'zhmc --help') can also be specified right after the
'... | 63,795 |
def from_file():
"""try to load the configuration from file"""
try:
return toml.load(Config.get_path_to_conf())
except FileNotFoundError:
logging.info(f"Configuration file '{Config.get_path_to_conf()}' not found.") | 63,796 |
def synthetic_data(w, b, num_examples):
"""
y = Xw + b + noise
"""
X = tf.zeros((num_examples, w.shape[0]))
X += tf.random.normal(shape=X.shape)
y = tf.matmul(X, tf.reshape(w, (-1, 1))) + b
y += tf.random.normal(shape=y.shape, stddev=0.01)
y = tf.reshape(y, (-1, 1))
return X, y | 63,797 |
def weg(m) -> str:
"""capture multiple "weg"s"""
return m | 63,798 |
def list_gateways(Marker=None, Limit=None):
"""
Lists gateways owned by an AWS account in an AWS Region specified in the request. The returned list is ordered by gateway Amazon Resource Name (ARN).
By default, the operation returns a maximum of 100 gateways. This operation supports pagination that allows yo... | 63,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.