content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def columns_not_changed(df, col_to_keep):
"""
insert the clean columns as features without changing the columns
:param df: dataframe
:param col_to_keep: columns that are clean and should not be changed
:return unchanged columns plus SK_ID_CURR
"""
df = df.loc[:, ['SK_ID_CURR'] + col_to_ke... | 1,200 |
def removeRestaurantFromList(update: Update, context: CallbackContext) -> int:
"""Removes the current restaurant from the current preferred list."""
query = update.callback_query
query.answer()
# Removing the restaurant from the list in the database
removeRestaurantFromListDb(
context.chat_... | 1,201 |
def _process_null(_):
"""
Placeholder for an efficient replacement for when no columns of a
`WaveformReducer` are activated.
"""
return dict() | 1,202 |
def GenerateRst(proto_file):
"""Generate a RST representation from a FileDescriptor proto."""
source_code_info = SourceCodeInfo(proto_file.name, proto_file.source_code_info)
# Find the earliest detached comment, attribute it to file level.
# Also extract file level titles if any.
header, comment = FormatHeade... | 1,203 |
def make_padded_batch(items):
"""
Pads sequences in a batch, so they are all the same length as the longest.
"""
max_len = max(len(d["input_ids"]) for d in items)
if max_len == 0:
return {k: torch.zeros((0, 0), dtype=torch.long) for k in items[0]}
return {
k: pad_sequence([d[k] f... | 1,204 |
def hlmlEventSetCreate() -> hlml_t.HLML_EVENT_SET.TYPE:
""" Create an empty set of events
Parameters: None.
Returns:
st (HLML_EVENT_SET) - An empty set of events.
"""
global _hlmlOBJ
st = hlml_t.HLML_EVENT_SET.TYPE
fn = _hlmlOBJ.get_func_ptr("hlml_event_set_create")
... | 1,205 |
def is_ip_addr(value):
"""
Check that the supplied value is an Internet Protocol address, v.4,
represented by a dotted-quad string, i.e. '1.2.3.4'.
>>> vtor.check('ip_addr', '1 ')
'1'
>>> vtor.check('ip_addr', ' 1.2')
'1.2'
>>> vtor.check('ip_addr', ' 1.2.3 ')
'1.2.3'
>>> vt... | 1,206 |
async def do_work(number):
"""
# 此方法在调用时不会立即被执行,而是返回一个协程对象
:param number:
:return:
"""
print('Number:', number) | 1,207 |
def batchEuclid (features, patterns, knowledge):
"""
Classifies whole dataset via euclidean distance. Returns score.
"""
dists = euclidean_distances (knowledge, features)
preds = np.array (dists).argmin (axis = 0)
truthVector = (preds.T.astype (float) == patterns)
pos = truthVector.sum ()
... | 1,208 |
def upload_plans_for_template(request):
"""
Allow user to upload a csv file to create plans based on a previously selected template
"""
ctxd = {}
context = RequestContext(request, ctxd)
return render_to_response("rundb/plan/modal_batch_planning_upload.html", context_instance=context) | 1,209 |
def calculate_total_correlativity(coefficient_array):
""" Returns the total correlativity of the coefficient_array. The total
correlativity is the sum of the absolute values and a measure of how
correlated to timeseries are. The greater the value the more correlated."""
return sum(map(abs, coefficient... | 1,210 |
def merge_by_name(out_file_name, in_file_names):
""" Merge name-sorted bam files into bam file sorted by name"""
args = ['samtools', 'merge', '-n', out_file_name]
args.extend(in_file_names)
log_subprocess.check_call(args) | 1,211 |
def test_execute_command():
"""
Execute "SELECT 1;"
Assert:
A result of 1 is returned
"""
cur = create_connection(host=host, port=port, user=usr, password=paswd, db=db)
assert type(cur) == pymysql.cursors.Cursor
stmt = "SELECT 1"
result = execute_command(cur, stmt)
assert r... | 1,212 |
def mosmix_example():
"""Retrieve Mosmix mosmix data by DWD."""
# A. MOSMIX-L -- Specific stations_result - each station with own file
Settings.tidy = True
Settings.humanize = True
request = DwdMosmixRequest(
parameter=["DD", "ww"],
start_issue=DwdForecastDate.LATEST, # automatical... | 1,213 |
def hide_topic(topic_id: TopicID, moderator_id: UserID) -> BoardTopicHidden:
"""Hide the topic."""
topic = _get_topic(topic_id)
moderator = _get_user(moderator_id)
now = datetime.utcnow()
topic.hidden = True
topic.hidden_at = now
topic.hidden_by_id = moderator.id
db.session.commit()
... | 1,214 |
def shell():
"""
Starts an interactive shell with app object imported.
"""
# Local vars defined/imported will be available in shells global scope
import IPython
from app.main import app
IPython.embed() | 1,215 |
def argmax(a, axis=None, out=None):
""" Returns the indices of the maximum values along an axis.
Parameters
----------
a: array_like
axis: int, optional
By default, the index is into the flattened array, otherwise along the specified axis.
out: ... | 1,216 |
def FlowBalance_rule(model, node):
"""Ensures that flows into and out of a node are equal
"""
return model.Supply[node] \
+ sum(model.Flow[i, node] for i in model.NodesIn[node]) \
- model.Demand[node] \
- sum(model.Flow[node, j] for j in model.NodesOut[node]) \
== 0 | 1,217 |
def evaluate_perfs(num_images, duration):
"""
Calculate and print the inference duration.
"""
#fps = float(num_images / duration)
#print("Throughput=%.2f fps, total frames = %.0f , time=%.4f seconds" %(fps, num_images, duration))
print("Duration = %.2f ms" %(duration * 1000)) | 1,218 |
def test_config_merging_missing():
"""
If we have set a boolean value in the TOML file, but not on the CLI, we
want the TOML value to be taken.
"""
toml = StringIO(
dedent(
"""\
[tool.vulture]
verbose = true
ignore_names = ["name1"]
"""
)
... | 1,219 |
def abcd(actual, predicted, distribution, as_percent=True):
"""
Confusion Matrix:
|`````````````|`````````````|
| TN[0][0] | FP[0][1] |
| | |
|`````````````|`````````````|
| FN[1][0] | TP[1][1] |
| | |
````````````````````... | 1,220 |
def get_gene_name(protein_id, web_fallback=True):
"""Return the gene name for the given UniProt ID.
This is an alternative to get_hgnc_name and is useful when
HGNC name is not availabe (for instance, when the organism
is not homo sapiens).
Parameters
----------
protein_id : str
Uni... | 1,221 |
def AddEventTypePositionalArg(parser):
"""Adds event type positional arg."""
parser.add_argument(
'event_type',
help='Type of event (e.g. com.google.gc.object.finalize).') | 1,222 |
def summarize():
""" Returns summary of articles """
if request.method == 'POST':
url = request.form['pageurl']
parser = HtmlParser.from_url(url, Tokenizer(LANGUAGE))
stemmer = Stemmer(LANGUAGE)
summarizer = Summarizer(stemmer)
summarizer.stop_words = get_stop_words(LANG... | 1,223 |
def _env_constructor(loader, node):
"""
Replaces environment variables in YAML file
"""
value = loader.construct_scalar(node)
for group in env_pattern.findall(value):
try:
value = value.replace(f"${{{group}}}", os.environ.get(group))
except TypeError as error:
... | 1,224 |
def version(include_copyright=False):
"""Get the version number of ``ssocr``.
Equivalent of running: ``ssocr --version``
Parameters
----------
include_copyright : :class:`bool`, optional
Whether to include the copyright information.
Returns
-------
:class:`str`
The ver... | 1,225 |
def intersection(n: np.ndarray,
d: float,
A: np.ndarray,
b: np.ndarray) -> List[np.ndarray]:
"""Return the intersection of the plane and convex ployhedron.
Returns a list of points which define the intersection between the plane
nx = d and the convex ployh... | 1,226 |
def create_session(checkpoint_path, target_device):
"""Create ONNX runtime session"""
if target_device == 'GPU':
providers = ['CUDAExecutionProvider']
elif target_device == 'CPU':
providers = ['CPUExecutionProvider']
else:
raise ValueError(
f'Unsupported target device... | 1,227 |
def V_eN_int(cgf_1, cgf_2, mol):
"""
Compute electron-nuclear integral between two contracted gaussian functions.
"""
v = 0
for i, _ in enumerate(cgf_1.alpha):
for j, _ in enumerate(cgf_2.alpha):
for k in range(mol.num_atoms):
v += cgf_1.co[i] * cgf_2.co[j] * pote... | 1,228 |
def create_subword_vocab(input_data,
subword_size):
"""create subword vocab from input data"""
def generate_subword(word,
subword_size):
"""generate subword for word"""
subwords = []
chars = list(word)
char_length = len(chars)
... | 1,229 |
def main() -> None:
"""Create a map of nodes with available SSH connection."""
map_ssh = folium.Map(location=[45.523, -122.675], zoom_start=2)
with open("lib/base_data.txt") as tsv:
for row in csv.reader(tsv, delimiter="\t"):
name = row[0]
try:
x = float(row[... | 1,230 |
def request_json(input_data):
"""Request JSON data from full node, given request data input.
More info: http://docs.python-requests.org/en/master/"""
requested_data = None # Prevent no state if all servers fail!
for full_node_url in full_node_list_http:
try:
requested_data = requests.get(full_node_url, dat... | 1,231 |
def rrange(x, y = 0):
""" Creates a reversed range (from x - 1 down to y).
Example:
>>> rrange(10, 0) # => [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
"""
return range(x - 1, y - 1, -1) | 1,232 |
def registry_auth_gcloud(deployment, project, service_key):
"""
Setup GCR authentication with a service_key
This changes *global machine state* on where docker can push to!
"""
encrypted_service_key_path = os.path.join(
'deployments', deployment, 'secrets', service_key
)
with decryp... | 1,233 |
def einsum_outshape(subscripts, *operants):
"""Compute the shape of output from `numpy.einsum`.
Does not support ellipses.
"""
if "." in subscripts:
raise ValueError(f"Ellipses are not supported: {subscripts}")
insubs, outsubs = subscripts.replace(",", "").split("->")
if outsubs == ""... | 1,234 |
def random_points(region, color="00FFFF", points=100, seed=0):
"""Generates a specified number of random points inside a given area.
Args: region(feature): region to generate points
color(color code): default is red, I think
points(numeric): how many points do you want? Default is 100
... | 1,235 |
def test_init_smart_sleep_mode():
"""Test that the new state array is populated correctly."""
const = get_const("1.4")
sensor_id = 1
sensor = Sensor(sensor_id)
sensor.add_child_sensor(0, const.Presentation.S_LIGHT_LEVEL)
sensor.add_child_sensor(1, const.Presentation.S_LIGHT_LEVEL)
assert n... | 1,236 |
def GridSearch(X_train_df, Y_train_df, hps_NaN_dict, features_l,
hps_models_dict, cv=5, n_jobs=-1, randomise=True):
"""Launch a grid search over different value of the hps."""
# Compute all the possible combinations of hps
tuples_hp = BuildHpTuples(X_train_df, hps_NaN_dict,
... | 1,237 |
def atm():
"""Fixture to compute atmospheric properties just once before tests.
Returns:
Atmosphere object
"""
return Atmosphere(h_geom_truth_arr) | 1,238 |
def toPaf(inputFile, fileformat):
"""
This function converts the file (input) into a Preference-based Argumentation Framework.
Here the PAF is represented by one set and 3 dictionnaries:
- the set contains the arguments
- the first dictionnary contains the attacks from an argument a to anoth... | 1,239 |
def get_key(my_dict: dict, val):
"""Get key value form dictionary using key value.
Args:
collection_name: dict: collection in dictionary format
val: Value in dictionary
Returns:
Key from dictionary.
"""
for key, value in my_dict.items():
if val == value:
ret... | 1,240 |
def test_get_mesh_grid_as_point_cloud_downsample():
"""
Sample a regular grid and return the (x,y) coordinates
of the sampled points.
"""
min_x = -3 # integer, minimum x-coordinate of 2D grid
max_x = 0 # integer, maximum x-coordinate of 2D grid
min_y = 2 # integer, minimum y-coordinate o... | 1,241 |
def closest(point, points):
"""works, but @@DEPRECATED!!
return index into points of closest-to-point
"""
da = dist_array(point, points)
return N.argmin(da) | 1,242 |
def generate_provenance_json(script="unknown", params={}):
"""Generate the provenance in a format which can later be output as valid json.
Inputs:
string: The name of the script used to trigger the data generation/deidentification/synthesis process
dict: The parameters used to tune the data gen... | 1,243 |
def dot(v, w):
"""v_1 * w_1 + ... + v_n * w_n"""
return sum(v_i * w_i for v_i, w_i in zip(v, w)) | 1,244 |
def get_users():
"""Query for user accounts."""
return JsonResponse(queryFor(UserAccount)) | 1,245 |
def test_create_project_pi_too_short(client):
"""Create a project with too short PI."""
create_unit_admins(num_admins=2)
current_unit_admins = models.UnitUser.query.filter_by(unit_id=1, is_admin=True).count()
assert current_unit_admins == 3
proj_data_short_pi = proj_data.copy()
proj_data_short... | 1,246 |
def get_added_and_removed_pitches(
chord_root_tpc: int,
chord_type: ChordType,
changes: str,
key_tonic_tpc: int,
key_mode: KeyMode,
) -> Dict[str, str]:
"""
Get a mapping of pitch alterations from the given chord. Pitches are given
and returned with PitchType TPC because accidental-speci... | 1,247 |
def get_n_random_points_in_region(region_mesh, N, s=None):
"""
Gets N random points inside (or on the surface) of a mes
"""
region_bounds = region_mesh.bounds()
if s is None:
s = int(N * 2)
X = np.random.randint(region_bounds[0], region_bounds[1], size=s)
Y = np.random.randint(regio... | 1,248 |
def test_get_issues_for_org_merges_issues_pull_requests(github, requests_mock):
"""
The '_get_issues_for_org' helper should merge both issues with
pull requests and treat them both as issues
"""
repo1 = fixtures.repository(
issues=[fixtures.issue(), fixtures.issue(), fixtures.issue()],
... | 1,249 |
def create_computer_query(tx, computer, query, value, rel):
"""Creates the queries for a computer.
Arguments:
tx {neo4j.Session} -- Neo4j session
computer {dict} -- Single computer object.
query {str} -- Query to use.
value {[type]} -- Value to read from: LocalAdmins, DcomUsers ... | 1,250 |
def make_octad_tables(basis):
"""Return tables for encoding an decoding octads.
Octads are numbered in the lexicographical order as given by the
numbers of the corresponding Golay codewords in 'gcode'
representation.
The function returns a triple
(oct_enc_table, oct_dec_table, oct_enc_... | 1,251 |
def fetch_profile(request):
""" attaches the user.profile object into the request object"""
context = {}
if request.user.is_authenticated():
profile_module_name = get_my_profile_module_name()
profile = getattr(request, profile_module_name, None)
if profile != None:
conte... | 1,252 |
def storeLabledImagesInFile():
"""Consolidates the images in the emotion directories and stores them in data.npy and lables.npy
file. Does virtual sampling for classes which do not have sufficient samples"""
data = []
labels = []
if os.path.exists(OUTPUT_DIRECTORY):
images = []
n... | 1,253 |
def test_device_put_method_empty_model_name(flask_app, db): # pylint: disable=unused-argument
""" To verify that registration device
method is working properly and response is correct"""
registration = create_registration(REG_REQ_DATA, uuid.uuid4())
registration.update_status('Pending Review')
... | 1,254 |
def to_local_op(input):
"""Returns the local tensor of a consistent tensor.
Args:
input (Tensor): the input tensor.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> np_arr = np.array([0.5, 0.6, 0.7]).astype(np.float32)
... | 1,255 |
def col_round(x):
"""
As Python 3 rounds 0.5 fraction to closest even,
floor and cell round methods used here to round 0.5
up to next digit and 0.4 down back to previos.
"""
frac = x - math.floor(x)
if frac < 0.5:
return math.floor(x)
return math.ceil(x) | 1,256 |
def _create_notebook(client, headers: dict[str, str]) -> str:
"""Create a notebook.
:param client: Test API client.
:param headers: Headers with the access token.
:return: Notebook ID.
"""
n = {"name": "Test Notebook"}
r = client.post("/notebooks/notebook", headers=headers, json=n)
ret... | 1,257 |
def iterate_steps(n):
"""Calculate derivatives for different parameter classes, and plot"""
for vary in ['bary', 'halo', 'progenitor']:
print(n, vary)
step_convergence(n, Nstep=10, vary=vary)
choose_step(n, Nstep=10, vary=vary) | 1,258 |
def createTables():
""" Populate the array with names of sql DDL files """
for sqlFileName in ["Address.sql", "Electricity.sql", "CodeViolationsReport.sql",
"FireRescueEMSResponse.sql", "NaturalGasReport.sql",
"WaterReport.sql"]:
try:
runSqlFil... | 1,259 |
def plot_range_range_rate(x_sat_orbdyn_stm:np.ndarray, x_obs_multiple:np.ndarray, t_sec: np.array):
""" Plots range and range relative to the station
Args:
x_sat_orbdyn_stm (np.ndarray): satellite trajectory array.
x_obs_multiple (np.ndarray): observer positions.
t_sec (np.ndarray): arr... | 1,260 |
def parse_autostep(rule):
"""
Parse the autostep line
"""
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
parser.add_argument("--autoscreenshot", dest="autoscreenshot", action="store")
args = clean_args(vars(parser.parse_args(rules)))
parser = None
retu... | 1,261 |
def AUTO_TECHSUPPORT_GLOBAL_state(db, state):
""" Knob to make techsupport invocation event-driven based on core-dump generation """
table = "AUTO_TECHSUPPORT"
key = "GLOBAL"
data = {
"state": state,
}
try:
update_entry_validated(db.cfgdb, table, key, data, create_if_not_exists=... | 1,262 |
def _make_tag(tagname: str, content: str = "", **attrs) -> str:
"""Creates a tag."""
tag = f"<{tagname} "
for key, value in attrs.items():
if key == "raw":
tag += " " + value
continue
if key == "cls":
key = "class"
if isinstance(value, float):
... | 1,263 |
def download(url: str, dest: Optional[str] = None, extract: bool=True, ignore_if_exists: bool = False,
compression: Optional[str] = None):
"""
Download a file from the internet.
Args:
url: the url to download
dest: destination file if extract=False, or destionation dir if extra... | 1,264 |
def action_functions(action_id: str):
"""Determines which function needs to be run."""
action_mappings = {
NewIncidentSubmission.form_slack_view: [report_incident_from_submitted_form],
UpdateParticipantCallbacks.submit_form: [update_participant_from_submitted_form],
UpdateParticipantCall... | 1,265 |
def get_default_sender():
"""
Determines the sender / to address for outgoing emails.
"""
try:
return os.environ["EMAIL"]
except KeyError:
pass
else:
# Guess.
# Not sure if euid is the right one to use here.
user = pwd.getpwuid(os.geteuid()).pw_name
... | 1,266 |
def setup_function(function):
"""
Make sure there are no adapters defined before start of test
"""
clear_adapters()
# Setup a basic int adapter for all tests
@adapter((str, float, int), (int, str))
def to_int(obj, to_cls):
return to_cls(obj) | 1,267 |
def get_best_response_actions_as_string(best_response_actions):
"""Turns a dict<bytes, int> into a bytestring compatible with C++.
i.e. the bytestring can be copy-pasted as the brace initialization for a
{std::unordered_,std::,absl::flat_hash_}map<std::string, int>.
Args:
best_response_actions: A dict map... | 1,268 |
def rank_velocity_genes(adata, vkey="velocity_S", prefix_store="rank", **kwargs):
"""Rank genes based on their raw and absolute velocities for each cell group.
Parameters
----------
adata: :class:`~anndata.AnnData`
AnnData object that contains the gene-wise velocities.
vkey: str... | 1,269 |
def build_genome(tree, genome):
"""
Goes through a tree and builds a genome from all codons in the subtree.
:param tree: An individual's derivation tree.
:param genome: The list of all codons in a subtree.
:return: The fully built genome of a subtree.
"""
if tree.codon:
# If th... | 1,270 |
def fixture_yaml_formatting_fixtures(fixture_filename: str) -> Tuple[str, str, str]:
"""Get the contents for the formatting fixture files.
To regenerate these fixtures, please run ``test/fixtures/test_regenerate_formatting_fixtures.py``.
Ideally, prettier should not have to change any ``formatting-after``... | 1,271 |
def test_partial_trace_4_by_4():
"""Test for 4-by-4 matrix."""
test_input_mat = np.arange(1, 17).reshape(4, 4)
pt_1 = partial_trace(test_input_mat, [1], [2, 2])
pt_2 = partial_trace(test_input_mat, [2], [2, 2])
expected_pt_1 = np.array([[12, 14], [20, 22]])
bool_mat = np.isclose(expected_pt_1,... | 1,272 |
def get_base_parser(*args, **kwargs):
"""
Main parser
"""
parser=argparse.ArgumentParser(*args, **kwargs)
# formatter_class=argparse.ArgumentDefaultsHelpFormatter,
# )
# parser.add_argument('--help_all', '--help_model', '--help_dataset', '--help_strategy', '--help_task', '--help_ptr... | 1,273 |
def MakeBuildDirectory(context=None):
"""Prepares the build and work directories."""
if context is None:
raise ValueError("context can't be None")
build_dir = config.CONFIG.Get("PyInstaller.build_dir", context=context)
work_path = config.CONFIG.Get("PyInstaller.workpath_dir", context=context)
CleanDirec... | 1,274 |
def conv_bboxinfo_bboxXYHW_to_centerscale(bbox_xyhw, bLooseBox = False):
"""
from (bbox_xyhw) -> (center, scale)
Args:
bbox_xyhw: [minX,minY,W,H]
bLooseBox: if true, draw less tight box with sufficient margin (SPIN's default setting)
Output:
center: bbox center
scale: sca... | 1,275 |
def add_video(db: Session, video: schemas.Video):
"""
Adds video to table video_library
model used is Video.
Attributes:
- video_user_id: int, non-nullable, foreign_key
- video_link: string, non-nullable, unique
- video_name: string, non-nullable,
- video_height: int, non... | 1,276 |
def compute_principal_axes(xyz_centered, weights=None, twodim=True):
"""
:param xyz_centered: [list_of_xs, lst_of_ys, list_of_zs]
:param weights: weights of each pixel
:param twodim: whether to compute two main axes in xy plane, or three axes in 3D image.
:return: ax1, ax2, (ax3 if not twodim else ... | 1,277 |
def stream_http_get(S, dest):
"""Get contents of http://dest/ via HTTP/1.0 and
samclasses.StreamSession S."""
C = S.connect(dest)
C.send('GET / HTTP/1.0\r\n\r\n')
while True:
line = stream_readline(C).strip()
if line.find('Content-Length: ') == 0:
clen = int(line.split()[1])
if line == ... | 1,278 |
def get_definition(division_id, path=None):
"""
Returns the expected contents of a definition file.
"""
config = {}
division = Division.get(division_id, from_csv=ocd_division_csv)
# Determine slug, domain and authority.
name = division.name
if not name:
print('%-60s unknown nam... | 1,279 |
def api_last_blog_update(request):
"""Return the date of the last blog update.
This is a PRIVATE API.
Format: __lastblogupdate.json
JSON return:
{'lastupdate': '2019-01-31'}
or if none available:
{'lastupdate': None}
"""
api_code = enter_api_call('api_last_blog_update', ... | 1,280 |
def main():
"""
测试当前类的方法的主方法入口
:return:
"""
# DataProcessing("../data_example/test.tsv","../data_example/test.tfrecords").test_txt2tfrecords()
# DataProcessing("../data_example/train.tsv","../data_example/train.tfrecords").train_txt2tfrecords()
# DataProcessing("../feature_data/tsz_submission_12.tfrecords","../s... | 1,281 |
def pearson(arr1, arr2):
"""
calculate pearson correlation between two numpy arrays.
:param arr1: one array, the feature is a column. the shape is `m * n`
:param arr2: the other array, the feature is a column. the shape is `m * k`
:return: a pearson score np.array , the shape is `k * n`
"""
... | 1,282 |
def check_input(image):
"""Check that the provided image consists of a single connected domain of pixels.
"""
# Check that the input image has no floating pixels.
labeled_array, num_features = label(image.astype(int)+1)
assert num_features==1, "The input image must contain a single solid domain of c... | 1,283 |
def exact_match_filter(query_set, field, values):
"""Check if a field exactly matches a value."""
return field_filter(lambda x, y: Q(**{x: y}), query_set, field, values) | 1,284 |
def clean_savepoints(using=None):
"""
Resets the counter used to generate unique savepoint ids in this thread.
"""
get_connection(using).clean_savepoints() | 1,285 |
def get_move_descriptions(get_moved_ids, initial_state, current_state, obj_stuff, sort_attributes, obj_attributes):
"""
Get all 'move' descriptions from the current state (if any).
Parameters
----------
get_moved_ids: function
Function that extracts the id of objects that are being moved.
... | 1,286 |
def reliability_diagram(labels,
probs,
class_conditional=False,
y_axis='accuracy',
img=False):
"""Reliability Diagram plotting confidence against accuracy.
Note that this reliability diagram is created by looking at the... | 1,287 |
def GuessSlugFromPath(path):
"""Returns the slug."""
if path.endswith('index.md'):
# If it ends with index, get the second last path component.
return path.split('/')[-2]
else:
# Otherwise, just get the filename.
return path.split('/')[-1].split('.')[0] | 1,288 |
def get_file(fname, origin, cache_subdir='datasets', file_hash=None):
"""Downloads a file from a URL if not already in the cache.
ref: https://github.com/keras-team/keras/blob/7a39b6c62d43c25472b2c2476bd2a8983ae4f682/keras/utils/data_utils.py#L123
By default the file at the url `origin` is downloaded to th... | 1,289 |
def simplified_fit(train_loader, val_loader, model, loss_fn, optimizer, n_epochs, is_cuda_available, metrics=[],
start_epoch=0, scheduler = None, log_interval=1):
"""
TODO
"""
train_list = []
valid_list = []
log_interval = len(train_loader)//2
if scheduler != None:
for epoch ... | 1,290 |
def _onenorm_matrix_power_nnm(A, p):
"""
Compute the 1-norm of a non-negative integer power of a non-negative matrix.
Parameters
----------
A : a square ndarray or matrix or sparse matrix
Input matrix with non-negative entries.
p : non-negative integer
The power to which the mat... | 1,291 |
def _stiff_terms_null(states, *args, **kwargs):
"""Dummy function"""
return states | 1,292 |
def add_dataset(dset_fp, dset_fromroot, list_ids, up3d_fp, # pylint: disable=too-many-locals, too-many-arguments, too-many-statements, too-many-branches
train_list_f, val_list_f, train_val_list_f, test_list_f, scale_f,
train_spec, val_spec, test_spec,
target_person_size,... | 1,293 |
def _compute_non_batch_kl(mu_a, sigma_a, mu_b, sigma_b):
"""Non-batch KL for N(mu_a, sigma_a), N(mu_b, sigma_b)."""
# Check using numpy operations
# This mostly repeats the tensorflow code _kl_mvn_mvn(), but in numpy.
# So it is important to also check that KL(mvn, mvn) = 0.
sigma_b_inv = np.linalg.inv(sigma_... | 1,294 |
def wait_until(fn, timeout, period, message):
"""
:param fn: callable function
:param timeout:
:param period:
:param message:
:return: bool
"""
mustend = time() + timeout
while time() < mustend:
if fn():
return True
sleep(period)
raise TimeoutError(mes... | 1,295 |
def test_atomic_normalized_string_length_nistxml_sv_iv_atomic_normalized_string_length_1_4(mode, save_output, output_format):
"""
Type atomic/normalizedString is restricted by facet length with value
0.
"""
assert_bindings(
schema="nistData/atomic/normalizedString/Schema+Instance/NISTSchema-... | 1,296 |
def proxy_wasm_cpp_host_fetch_remote_crates():
"""This function defines a collection of repos and should be called in a WORKSPACE file"""
maybe(
http_archive,
name = "proxy_wasm_cpp_host__addr2line__0_16_0",
url = "https://crates.io/api/v1/crates/addr2line/0.16.0/download",
type ... | 1,297 |
def single_test(model, testdata, max_seq_len=20):
"""Get accuracy for a single model and dataloader.
Args:
model (nn.Module): MCTN2 Model
testdata (torch.utils.data.DataLoader): Test Dataloader
max_seq_len (int, optional): Maximum sequence length. Defaults to 20.
Returns:
_... | 1,298 |
def generate_tiled_html_result(slide_nums, tile_summaries_dict, data_link):
"""
Generate HTML to view the tiled images.
Args:
slide_nums: List of slide numbers.
tile_summaries_dict: Dictionary of TileSummary objects keyed by slide number.
data_link: If True, add link to tile data csv file.
"""
sl... | 1,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.