content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def select_text(table, col_names, version): """Generate a select statement for new or old values of this table.""" slt = "SELECT {tuple_str} FROM {table} WHERE rowid={version}.rowid".format( tuple_str=sqlite_list_text([col_pair_text(c, version) for c in col_names]), ...
28f22ad8478cd87d1d56c7a1a6b86d0b81e1d457
52,800
def predict(Theta1, Theta2, X): """ outputs the predicted label of X given the trained weights of a neural network (Theta1, Theta2) """ if X.ndim == 1: X = X.reshape(1, -1) # Useful values m = len(X) # ====================== YOUR CODE HERE ====================== # Instructions:...
ba3df784fdd2a76fc59f0f010a9a4eb4c5be035f
52,801
def aml_token(chain, team_multisig, token_name, token_symbol, initial_supply) -> Contract: """Create the token contract.""" args = [token_name, token_symbol, initial_supply, 0, True] # Owner set tx = { "from": team_multisig } contract, hash = chain.provider.deploy_contract('AMLToken', de...
b114cfc3abeeea9c600dccbc1bed78de60a7576f
52,802
def invr(): """ For taking space seperated integer variable inputs. """ return(list(map(int, input().split())))
9794b5c44a817cbd48709de99f16515c8684712b
52,803
def _path_residuals(X, y, train, test, path, path_params, alphas=None, l1_ratio=1, X_order=None, dtype=None): """Returns the MSE for the models computed by 'path' Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. y : arr...
0bfb35f3de8f5c8ba136a9cf29650667c110a039
52,804
def is_an_exact_imagined_object(predicate, imagined_object): """ Returns whether the imagined object matches exactly what the predicate describes. Inputs: predicate: WordPredicate instance imagined_object: RecognizedObject instance """ target = possible_reco...
06aef2d1fb87d02cf60baceff81d8b153d487967
52,805
def read_field__list(infile, varname, lon, lat): """Read point list and initialize field.""" # Read field ... if infile.endswith(".npz"): # ... from numpy archive with np.load(infile) as fi: pts_lon, pts_lat, pts_fld = fi["lon"], fi["lat"], fi[varname] fld = point_list_t...
1e1baafdab9fac5a43bb95d28fb8d7d0c9d8ba31
52,806
def CircuitHeaderStartConfigurationVector(builder, numElems): """This method is deprecated. Please switch to Start.""" return StartConfigurationVector(builder, numElems)
9ad0c7dd86a9f0cb90f573720802658616f81bff
52,807
def get_processed_masks_and_boundaries(mask_path: str, boundary_path: str) -> tuple[ndarray, ndarray]: """Utility function for loading and applying preprocessing to mask and boundary image array :param paths: :return: tuple[ndarray, ndarray] """ masks = np.array( cv2.imread( mask...
26def41a1e8dfe33d2d35b155164412374dfa30f
52,808
import warnings def nx_to_gdf(net, points=True, lines=True, spatial_weights=False, nodeID="nodeID"): """ Convert ``networkx.Graph`` to LineString GeoDataFrame and Point GeoDataFrame Parameters ---------- net : networkx.Graph ``networkx.Graph`` points : bool export point-based ...
1821d06896eb9b7bfafa81aa748521ff2153bd0f
52,809
def p2pkh(pubkey) -> Script: """Return Pay-To-Pubkey-Hash ScriptPubkey""" return Script(b'\x76\xa9\x14'+hashes.hash160(pubkey.sec())+b'\x88\xac')
2728805a090ddcd070b7454549018d538d71ee73
52,810
def _extract_center_face(image_shape, detected_faces): """Extracts the face that's the closest to the center of a image. ### Parameters image: image with the faces. detected_faces: list of resulting bounding boxes and keypoints from\ MTCNN().detect_faces(). ### Returns (bounding_b...
cbfb3bc4c90a62cb75eaa40854fe8829d76a18eb
52,811
from typing import Optional from typing import Union def get_county_polygons(county_ids: Optional[intseq], state_ids: Union[int, intseq]): """Get a dataframe with the polygons or multipolygons representing county borders The returned dataframe will have the county polygons for each county listed. `county_ids...
ad8a71ab0fc38658c4eff0f86030e3b14ac64a28
52,812
def add_xls_tag(file_name): """ Check the file_name to ensure it has ".xlsx" extension, if not add it """ if file_name[:-5] != ".xlsx": return file_name + ".xlsx" else: return file_name
e053d9f7dad8e638122e93d05e49c5a06de3e664
52,813
def order_queryset_by_z_coord_desc(queryset, geometry_field="location"): """Order an queryset based on point geometry's z coordinate""" return queryset.annotate( z_coord=models.ExpressionWrapper( models.Func(geometry_field, function="ST_Z"), output_field=models.FloatField(), ...
bd9e4d9b09b2676727dc2f83452e93b50eda3716
52,814
def err_number(error) : """ Return a error number """ result = errOk if isinstance(error, int) : result = error elif isinstance(error, Error) : result = error.error_code if result < 0 : result = (result - ErrorBaseNumber) * -1 return result
8c6912a8c8466ecf4ce486a43001748d4237a217
52,815
def value_iteration(env): """ Performs Value Iteration to find the most optimal policy for the Tax-v3 environment Args: env: Taxiv3 Gym environment Returns: policy: the most optimum policy """ V = dict() gamma = 0.9 state_size = env.observation_space.n action_si...
461b65bf8de4cf30f018aad24f8452ed6b7ec247
52,816
def keypoint_3d_pck(pred, gt, mask, alignment='none', threshold=150.): """Calculate the Percentage of Correct Keypoints (3DPCK) w. or w/o rigid alignment. Paper ref: `Monocular 3D Human Pose Estimation In The Wild Using Improved CNN Supervision' 3DV'2017. <https://arxiv.org/pdf/1611.09813>`__ . Note...
704cf2cc4b00ad232689d76e65d2a7241eda8fec
52,817
from bioservices import biomart from io import StringIO def mitochondrial_genes(host, org): """Mitochondrial gene symbols for specific organism through BioMart. Parameters ---------- host : {{'www.ensembl.org', ...}} A valid BioMart host URL. org : {{'hsapiens', 'mmusculus'}} Orga...
affd7ff1d9014f36238b535732a1cbaac43b1308
52,818
def Bold(string): """Returns string wrapped in escape codes representing bold typeface.""" return '\x02%s\x0F' % string
4dd1a0d3aecc93873f9763723a3dad76b45e2725
52,819
import os import subprocess def compile_src(commit_id, language): """将程序编译成可执行文件""" commit = Commit.query.get(commit_id) language = language.lower() dir_work = os.path.join(work_dir, str(commit_id)) build_cmd = { "c": "gcc main.c -o main", "c++": "g++ main.cpp -o main", ...
26aa12aa2dceb485d10bbb383a7e967e4619bee8
52,820
from typing import List import decimal import json def from_bbox_array(bbox_array: List[decimal.Decimal]): """returns a geojson geometry object from a bounding box array. Keeping default number of decimal places to 6 for now, can change depending on data precision requirements.""" if bbox_array: ...
3bbaf66d6d5d31f45b93e944474cac5f454df313
52,821
import os import json def Open(filename): """ You can open/read a Zype File with Open() function. Usage: Open(filename) Filename is the Zype File's Name. """ if os.path.isfile(filename): with open(filename) as Zype: content = Zype.read() content = conten...
20a48af9c7e7a0f74e72fa02c7241915b5c5b78c
52,822
def taiwanLightCompensation(im, theta=0.5, thresh=0.2, B=[10, 30]): """ Perform light compensation http://www.csie.ntu.edu.tw/~fuh/personal/LightCompensation.pdf :param theta: weight of corrected image in final output :return: light compensated image """ def getOptimalB(im, thresh, B): ...
ac7c1fa06bb7cc2f0904b8da1ad360a027d6778f
52,823
def _is_sweep_sequential(radar, sweep_number): """ Test if a specific sweep is sequentially ordered. """ start = radar.sweep_start_ray_index['data'][sweep_number] end = radar.sweep_end_ray_index['data'][sweep_number] if radar.scan_type == 'ppi': angles = radar.azimuth['data'][start:end+1] el...
3bc493b80d245a51295c5e3461f9442baecd15cb
52,824
import random def random_expand(image, boxes): """ Perform a zooming out operation by placing the image. Helps to learn to detect smaller objects. Args: image(numpy.array): image, a array of dimensions (original_h, original_w, 3) boxes(numpy.array): bounding boxes in boundary coordin...
79e958a8acdc622e3e2e9270a2a29ededcc110b3
52,825
import re import sys def google_maps(query: str) -> bool: """Uses google's places api to get places near by or any particular destination. This function is triggered when the words in user's statement doesn't match with any predefined functions. Args: query: Takes the voice recognized statement ...
f0a8e25e54a93b0296c537cbc035cded8c9b9675
52,826
def matMULTI(first,second): """ Take in two matrix multiply each element against the other at the same index return a new matrix """ newMAT = [] newCOL = [] for i in range(len(first)): for j in range(len(first[i])): newMAT.append(first[i][j]*second[i][j]) #new...
28b3b5954a483311bca6245c7472a99e8a12395c
52,827
def put_html(html, sanitize=False, scope=Scope.Current, position=OutputPosition.BOTTOM) -> Output: """ Output HTML content :param html: html string :param bool sanitize: Whether to use `DOMPurify <https://github.com/cure53/DOMPurify>`_ to filter the content to prevent XSS attacks. :param int scope,...
60a10c44df3b4ba66f8ac428bfbfeaa60b069ac9
52,828
import sys import os def check_enableusersite(): """Check if user site directory is safe for inclusion The function tests for the command line flag (including environment var), process uid/gid equal to effective uid/gid. None: Disabled for security reasons False: Disabled by user (command line o...
466ce7da62b6578db0f99ca31c7271ef3bc2d832
52,829
def convert_list2dict(word_list): """ 把列表写成字典 """ word_dict = defaultdict(int) for w in word_list: word_dict[w] = 1 return word_dict
72bf12e52f8ebd8d9b9ce3626b995d0ababc2ab5
52,830
def GetAuthorizationCodeViaCommandLine(config): """Gets authorization code via command line. This way is useful anywhere without a browser. Args: config: a dictionary of config. Returns: authorization code. """ body = urlencode({ 'scope': config['scope'], 'redirect_uri': config['redir...
67f7603825fcf30a4fbb957414e90525a88ceae5
52,831
def pedestal_ids_file(base_test_dir): """Mock pedestal ids file for testing.""" pedestal_ids_dir = base_test_dir / "auxiliary/PedestalFinder/20200117" pedestal_ids_dir.mkdir(parents=True, exist_ok=True) file = pedestal_ids_dir / "pedestal_ids_Run01808.0000.h5" file.touch() return file
edda4c192e577774e0cc4a38aaa7d838127e7dcd
52,832
def get_fa_icon_class(app_config): """Return Font Awesome icon class to use for app.""" if hasattr(app_config, "fa_icon_class"): return app_config.fa_icon_class else: return 'fa-circle'
3766abb1f80b7ccea9e09a5edf011f1586e9b49e
52,833
def linear_activation_forward(a_prev, w, b, activation): """ activation step for forward propagation with multiple choices of activation function. @param a_prev: previous A from last step of forward propagation, numpy arrays @param w: parameter W in current layer, numpy arrays @param b: parameter b...
58a12f753c42201400747e52213b95d372ae6e89
52,834
from pathlib import Path import subprocess def git_checkout(repo: Repo, git_ref: str) -> str: """ git_ref is of the form refs/heads/main or refs/tags/0.0.3 """ git_dir = repo.directory is_branch = git_ref.startswith('refs/heads/') target = git_ref if is_branch: # We need the branc...
1bf14117a38ea8c4eebff5d54956da003f4d8277
52,835
import time def create_token(args): """ POST /api/v1/create_token HTTP/1.1 Host: 127.0.0.1:5000 Content-Type: application/json Content-Length: 74 { "name":"1234", "password" :"1234", "email" : "1234", "duration":123 } {"access_token":"ad236cdb-f645-456...
74012f112c5d22a088e1e58032d35de5b1436028
52,836
def getDictionary(id_or_identifier): """ 指定した id または identifier を持つ辞書のメタデータを返します。 id, identifier に一致する辞書が存在しない場合は None を返します。 Parameters ---------- id_or_identifier : str or int str の場合は辞書 identifier で指定。 int の場合は内部辞書 id で指定。 Returns ------- Metadata Metadat...
7d3f19ee4a9952afb336eb00cbc28a07191d02b2
52,837
from typing import Optional import os def load_import_config(project: Project) -> Optional[ImportConfig]: """ Loads the import config for the project (if it exists, otherwise None is returned): """ import_path = os.path.join(project.folder(), IMPORT_PROJECT_FILENAME) if not os.path.exists(import_p...
a8911c0810658ce59a04fecb6eeee200a50de2a3
52,838
def is_phone_in_call(log, ad): """Return True if phone in call. Args: log: log object. ad: android device. """ return ad.droid.telecomIsInCall()
bf279c1892077de53f13976179ecf762f45f54b6
52,839
def omicron_model( xs: np.ndarray, ts: np.ndarray, params: dict ) -> np.ndarray: """ SL_2I_4R model with dual immunity :param np.ndarray xs: actual array of states :param np.ndarray ts: time values :param dict params: dictionary of parameters :return np.ndarray ""...
52ce91a0be8f8f5054c12c08993ed8303ffd87f3
52,840
def identity(n): """ Return n """ return n
cc3249a1164e18f47f962e4db56a425876a87b17
52,841
def look_for_general( m_str: str, ref_dict: defaultdict, base_num: t.Pattern[str], full_num: t.Pattern[str], doc_type: str, ) -> defaultdict: """ Reference Extraction by Regular Expression: For general use Args: m_str: text string to search ref_dict: dictionary of refere...
1563e85f9228f9ffb14f14869ecf1f73441ae2e6
52,842
def losses_and_metrics(num_classes): """ Define loss and metrics Loss: Categorical Crossentropy Metrics: (Train, Validation) Accuracy, Precision, Recall, F1 Returns: loss, train loss, train acc, valid loss, valid acc, precision, recall, auc, f1 """ loss_fn = CategoricalCrossentropy...
d8f571c4e2948007d8b6f880afbbd0e2fcfab00d
52,843
import copy def get_skill_from_model(skill_model): """Returns a skill domain object given a skill model loaded from the datastore. Args: skill_model: SkillModel. The skill model loaded from the datastore. Returns: skill. A Skill domain object corresponding to the given ...
c75ea6c7705d316a5d279da36468dd9278ceae44
52,844
import os def get_loaders(dataset_path, batch_size=32, num_workers=12, mean=None, std=None): """ Function to load the train/test loaders. Parameters ---------- dataset_path: str, dataset path. batch_size: int, batch size. num_workers: int, number of workers. mean:None or torch.Tensor...
b950f7bb79aa6d6891e58bc256ee7cad30e31f69
52,845
def delete_tags_for_manifest(manifest): """ Deletes all tags pointing to the given manifest. Returns the list of tags deleted. """ query = Tag.select().where(Tag.manifest == manifest) query = filter_to_alive_tags(query) query = filter_to_visible_tags(query) tags = list(query) now_ms = get_epoch_ti...
a78b77ea96a3870b736301443005e45d58f76c42
52,846
def eeg_epochs_dataset(subject, trial, config, preload=True): """Get the epoched eeg data excluding unnessary channels from fif file and also filter the signal. Parameter ---------- subject : string of subject ID e.g. 7707 trial : HighFine, HighGross, LowFine, LowGross Returns ------...
58e6a1d63d2cc01416761b48a32a5bc9ebeacef9
52,847
def differences(lis, n=1): """ Returns the `n` successive differences of the elements in `lis`. EXAMPLES:: sage: differences(prime_range(50)) [1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4] sage: differences([i^2 for i in range(1,11)]) [3, 5, 7, 9, 11, 13, 15, 17, 19] ...
067ee6e5744211f2b41f55f8cd7383431df1e486
52,848
def get_bounded_progress(): """ returns progress as a tensor between 0 and 1 """ assert get_default_counter().expected_count is not None return get_default_counter()._bounded_progress
3279ead5729521280bc0fd9295de861944f02b9a
52,849
from matplotlib import path, transforms def polygon_clip(rp, cp, r0, c0, r1, c1): """Clip a polygon to the given bounding box. Parameters ---------- rp, cp : (N,) ndarray of double Row and column coordinates of the polygon. (r0, c0), (r1, c1) : double Top-left and bottom-right coo...
4fd565084417c04e1ad45c713704e9ff41d74eaa
52,850
import six def _is_start_piece_sp(piece): """Check if the current word piece is the starting piece (sentence piece).""" special_pieces = set(list('!"#$%&\"()*+,-./:;?@[\\]^_`{|}~')) special_pieces.add(u"€".encode("utf-8")) special_pieces.add(u"£".encode("utf-8")) # Note(mingdachen): # For foreign characte...
591373699c5e4c41248c81dac2bae5520123b2e7
52,851
import math def atrpips(data, length): """Average True Range indicator in pips Arguments: data {list} -- List of ohlc data [open, high, low, close] length {int} -- Lookback period for atr indicator Returns: list -- ATR (in pips) of given ohlc data """ atr_pips = [] av...
b73ab18cd0e1f338cc8136c0ccd82fd056d668a9
52,852
def start_day(start): """Return TMIN, TAVG, TMAX.""" start_day = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start).group_by(Measurement.date).all() start_day_list = list(start_day) return jsonify(start_da...
3c24c3c22dc1444e4bc46baeaa3e527a1e2af75b
52,853
def R123(a,b,c, degrees=False): """Returns a rotation matrix based on: Z*Y*X""" if degrees: a *= deg2rad b *= deg2rad c *= deg2rad s3 = np.sin(c); c3 = np.cos(c) s2 = np.sin(b); c2 = np.cos(b) s1 = np.sin(a); c1 = np.cos(a) return np.array( [ [c1*c2,...
8097514d390d73d1121c9462cada98060681619e
52,854
from datetime import datetime from typing import Optional import time from typing import Union import calendar def get_next( base: datetime, interval: Interval, frequency: int, at_time: Optional[time] = None, days: Optional[list[int]] = None, ) -> Union[datetime, date]: """Get the next due dat...
678b5c85615e388e2ae221df7ffba7ee38f97584
52,855
from typing import Union def guess_font_size( size: tuple[int, int], font_name: str ) -> tuple[Union[ImageFont, FreeTypeFont], int]: """Try and figure out the correct font size for a given height and font. Args: ``size``: The dimensions of the image in pixels. ``font_name``: The name of t...
01733050378885184ea5e0dbaba053263cf139bd
52,856
def create_model( time_set=None, time_units=pyo.units.s, nfe=5, tee=False, calc_integ=True, ): """Create a test model and solver Args: time_set (list): The beginning and end point of the time domain time_units (Pyomo Unit object): Units of time domain nfe (int): Numb...
9330c87db97d42de665c8198eaa113045ef92897
52,857
from pathlib import Path def read_table(h5file, path, start=None, stop=None, step=None, condition=None) -> Table: """Read a table from an HDF5 file This reads a table written in the ctapipe format table as an `astropy.table.Table` object, inversing the column transformations units. This uses the sam...
f3ef6b3ff7afc81e1afd9cca594727b8117471bc
52,858
from typing import Any def get_valid_ref(ref: Any) -> str: """Checks flow reference input for validity :param ref: Flow reference to be checked :return: Valid flow reference, either 't' or 's' """ if ref is None: ref = 't' else: if not isinstance(ref, str): raise ...
16c66dc9e0568bcd33e1cc9956ed31b5ae47595e
52,859
def k_argmin(l, k, func): """ Gets the indices and values of the k-smallest function results from func. """ l_map = map(func, l) return k_min(l_map, k)
750f408723ad9e024d45796bcc3250a9fcab296a
52,860
from typing import List import os from pathlib import Path def create_zip_task( result: dict = None, task_uid: str = None, data_provider_task_record_uid: List[str] = None, data_provider_task_record_uids: List[str] = None, run_zip_file_uid=None, *args, **kwargs, ): """ :param result...
8b04b99cb07b69d263a39863f120e5356f342f1a
52,861
from typing import Optional from typing import Tuple def add_ports_from_markers_square( component: Component, pin_layer: LayerSpec = "DEVREC", port_layer: Optional[LayerSpec] = None, orientation: Optional[int] = 90, min_pin_area_um2: float = 0, max_pin_area_um2: float = 150 * 150, pin_extr...
349893ef57c43dfc634af54086c98720207d2d6c
52,862
def calc_periodicity(peak_info, period_min=5, period_max=15): """ calculate the period :param peak_info: :param period_min: :param period_max: :return: """ num_peaks = peak_info.shape[0] # calculate periodicity peak_info[:num_peaks-1, 2] = np.diff(peak_info[:, 0]) peak_info =...
ac7ca44153019773741e6e6ca15fd9961bb16089
52,863
from typing import Type def create_global_resource(group: str, version: str, kind: str, plural: str, verbs=None) \ -> Type[GenericGlobalResource]: """Create a new class representing a global resource with the provided specifications. **Parameters** * **group** `str` - API group of the resource. ...
c6cb2e05a048456ed7103c6e1b4c81692b34987a
52,864
from typing import Dict from typing import Hashable from typing import Any def outline_to_implementation( name: str, design: str, outline: fiat.Outline) -> Dict[Hashable, Any]: """[summary] Args: name (str): [description] design (str): [description] outline (fiat.Outline)...
871c7fd4f950c291832cbd0fc3dce823831c4257
52,865
import re def match(pattern, name): """Test whether a name matches a wildcard pattern. Arguments: pattern (str): A wildcard pattern, e.g. ``"*.py"``. name (bool): A filename. Returns: bool: `True` if the filename matches the pattern. """ try: re_pat = _PATTERN_CA...
145023b54449f85bed0421dcf446352c32328bae
52,866
def _OldEnough(try_bot_cache, bot_id): """Checks if the build in the given bot's cache is older than threshold.""" built_cp = try_bot_cache.full_build_commit_positions[bot_id] tot_cp = git.GetCommitPositionFromRevision('HEAD') return built_cp < tot_cp - STALE_CACHE_AGE
0b6ff7a3e1f08ecf602239d127ac879539975bcc
52,867
def the_joke(): """ Combining both joke and emojis into one function. """ return yomama() + laugh()
f7a6baa9cba166f8ddd6d8993f4d8d7225c8d467
52,868
def return_dict(): """ "interfaces": { "Tunnel0": { "state": "UP" }, "Tunnel1": { "state": "DOWN" } } } """ return {"interfaces": {"Tunnel0": {"state": "UP"}, "Tunnel1": {"state": "DOWN"}}}
2c3e71341c425166d11aba9175e3a98027c3d53e
52,869
from typing import List import itertools def allocation_with_lowest_gain(agents: List[Agent], allocations: List[CakeAllocation]) -> CakeAllocation: """ Finds an allocation such that for all agents, gain(agent) (as defined by `get_agent_gain`) in that allocation scope is less than the sum of gain(agent) fo...
3de69a8f735329fb110e7323c851b3a13c58522e
52,870
import torch def replace_magnitude(x, mag): """ Extract the phase from x and apply it on mag x [B,2,F,T] : A tensor, where [:,0,:,:] is real and [:,1,:,:] is imaginary mag [B,1,F,T] : A tensor containing the absolute magnitude. """ phase = torch.atan2(x[:, 1:], x[:, :1]) # imag, real ret...
b535e4271c6fc4fe508af358fbe3eee59a95cc6b
52,871
def is_ip_address(host: str) -> bool: """Determine if host is an IP Address.""" try: ip_address(host) except ValueError: return False return True
90b66e8b8b43ee20796ba2e3a408d217978741aa
52,872
def cut_rod2(p, n, r={}): """Cut rod. Same functionality as the original but implemented as a top-down with memoization. """ q = r.get(n, None) if q: return q else: if n == 0: return 0 else: q = 0 for i in range(n): ...
2fa1433dffb9099709e466025645c4981f289692
52,873
import logging def RunLoad(redis_vm, load_vm, threads, port, test_id): """Spawn a memteir_benchmark on the load_vm against the redis_vm:port. Args: redis_vm: The target of the memtier_benchmark load_vm: The vm that will run the memtier_benchmark. threads: The number of threads to run in this memtier_...
9935a619a6c267023fdcf751b24b9a339d28551a
52,874
import os def choose_vnc_display(): """Try to choose a free vnc display. """ def netstat_local_ports(): """Run netstat to get a list of the local ports in use. """ l = os.popen("netstat -nat").readlines() r = [] # Skip 2 lines of header. for x in l[2:]: ...
66f65fbbbf51323975af0050a7225aaf71ab1a8c
52,875
import os def change_last_activation_to_linear(model: Model, dependencies=None) -> Model: """ Changes last activation function to linear, if it already is linear - returns same model :param dependencies: necessary objects for custom functions in keras :param model: Keras model :return: Keras model...
41b206de30179c67dce9aa56af04831574c4ef67
52,876
from re import T def import_data(): """ Export data via CRUD controller. Old - being replaced by Sync. """ title = T("Import Data") return dict(title=title)
5547236231e524e3d36fde1249f0eb0eaa9427df
52,877
def _set_karma(bot, trigger, change, reset=False): """Helper function for increasing/decreasing/resetting user karma.""" channel = trigger.sender user = trigger.group(2).split()[0] if reset: bot.db.set_nick_value(user, 'karma', 0) return karma = bot.db.get_nick_value(user, ...
72531c032625c365e057057edb84672b86a4faac
52,878
def read_kazr(filename, field_names=None, additional_metadata=None, file_field_names=False, exclude_fields=None): """ Read K-band ARM Zenith Radar (KAZR) NetCDF ingest data. Parameters ---------- filename : str Name of NetCDF file to read data from. field_names : dict, opt...
7b8d87c27b4a69ddbe40ed4e8c5b68b981b06ef9
52,879
def addScriptOptions(parser, pos_args, kw_args): """ add script-specific script options """ script_options_group = parser.add_argument_group('Options') hlpstr = "Prefix string for output filenames. Can optionally include a " \ "full path. Defaults to the input filename." ...
fbf44211bd23eb46e564dee9e6f8b5262f613176
52,880
def get_dag(node): """ :param str node: :return: Maya dag path node :rtype: OpenMaya.MDagPath """ sel = OpenMaya.MSelectionList() sel.add(node) return sel.getDagPath(0)
c28ce48a801ebde3c55e34235546eafa9f67b612
52,881
def aistats2022(): """Font size for AISTATS 2022.""" return _from_base(base=10)
984c4e7e697fea6a8c7643d2e8ac80b20f1fdfc5
52,882
def format_filt( something ): """ Example of a filter that can be used within the Jinja2 code """ return "Not what you asked for"
3878f805f21f2be3a4b96173f04257308f72bd45
52,883
def conv_upample(conv, x, occupy, real_num, out_coords, out_occupy, out_stride=1, mul_occupy_after=True): """ Add occupancy value for sparse convolution that decreases the stride for input data """ if occupy.ndim < 2: occupy = occupy.unsqueeze(1) if conv.kernel.ndim < 3: conv.kerne...
84b21d16fe3105dd6b1c8cc191b1a1a9303fc1f7
52,884
def get_field_node(field_config: dict, config: dict, source=None) -> object: """ get field node. """ required = field_config.get(FIELD_REQUIRED, False) field_type, field_attrs = tuple(field_config[FIELD_TYPE].items())[0][0], tuple( field_config[FIELD_TYPE].items())[0][1] if field_type ==...
431b43032fa77823860aa697df776d4539628615
52,885
from typing import Optional def subcycles() -> Parser: """Return a parser to parse the <subcycles> tag. :return: A parser that consumes the <subcycles> tag and produces an :class:`rads.config.ast.Assignment` AST node which assigns to "subcycles" a :class:`rads.config.tree.SubCycles` d...
50d79b8424b1ec082f12cf8af4f295f057294aeb
52,886
from gtmcore.container.local_container import LocalProjectContainer from gtmcore.container.hub_container import HubProjectContainer from typing import Optional def container_for_context(username: str, labbook: Optional[LabBook] = None, path: Optional[str] = None, override_image_name: Optiona...
792b2111de209e7a11900eae513e839677ad8f82
52,887
import re def suggest(term): """ Find most appropriate EFO term for arbitrary string Arg: * string Returntype: string (EFO ID) """ server = 'http://www.ebi.ac.uk/spot/zooma/v2/api' url_term = re.sub(" ", "%20", re.sub("[%&]", "", term)) ext = "/services/annotate?propertyValue=%s&filter=required:[none],...
4673c1fc715cc77bfb0db8b877174c5be6e6af51
52,888
import numpy def plot_matplotlib_dgt(func, **kwargs): """ Plot scalar discontinuous Galerkin Trace functions in 2D """ # Get information about the underlying function space function_space = func.function_space() family = func.ufl_element().family() mesh = function_space.mesh() ndim = m...
e581b761614ba99424d0933a1f4b4d124921e44d
52,889
from typing import Callable from typing import Awaitable def mapi_async(mapper: Callable[[TSource, int], Awaitable[TResult]]) -> Projection[TSource, TResult]: """Map with index async. Returns an observable sequence whose elements are the result of invoking the async mapper function by incorporating the e...
86c2f1ea0a20b04dab24246a92dda87e29ed4ead
52,890
def descriptors_to_file(config_filepath: str, descriptors: kapture.Descriptors) -> None: """ Writes descriptors to CSV file. :param config_filepath: :param descriptors: """ return image_feature_to_file(config_filepath, descriptors)
cfbfa147893681672666cd09a1b94574893a9798
52,891
def parseEdmSize(lines): """ Returns a list of dictionaries Example of data: >>> parseEdmSize(lines = ( 'File MINBIAS__RAW2DIGI,RECO.root Events 8000', 'TrackingRecHitsOwned_generalTracks__RECO. 407639 18448.4', 'recoPreshowerClusterShapes_multi5x5PreshowerClusterShape_multi5x5PreshowerXClustersShape_RECO. 289.787...
432f697d2c4baf795b3e41f574ba9d3d7ea6a802
52,892
def get_activation_function(label: str) -> ActivationFunction: """Get activation function by label :param label: string denoting function :return: callable function """ if label == 'lin': return Linear() if label == 'sigmoid': return Sigmoid() if label == 'tanh': ret...
d143734f0e2713fbc6e660467d1256afd876a681
52,893
def Detector_List(scanIOC): """ Define the detector used for: keithley_live_strseq() Detector_Triggers_StrSeq() BeforeScan_StrSeq() => puts everybody in passive CA_Average() WARNING: can't have more than 5 otherwise keithley_live_strseq gets angry. """ BL_mode=BL_Mod...
c2303314fb556e504540ccd2f2f0af0c9c2590b2
52,894
import torch def _instance_accuracy(label, raw_pred, compare_func, return_float=True, feed_dict=None, args=None): """get instance-wise accuracy for structured prediction task instead of pointwise task""" # disctretize output predictions if not args.task_is_sudoku: pred = as_tensor(raw_pred) ...
51831f2160a0eec6fbec4e7d8992009b3fff7811
52,895
import html def get_stressors(lat,lon): """ Example for looking up stressors at a particular location. """ # Note df is a flattened list of lat/lon values that only includes those over land df = pvcz.get_pvcz_data() # Point of interest specified by lat/lon coordinates. lat_poi = float(l...
34718b197d265c98d2d3e0a30d041af6e8b1e44e
52,896
def load_and_prepare_image(filename, img_shape=224, rescale=True): """ Preparing an image for image prediction task. Reads and reshapes the tensor into needed shape (img_shape, img_shape, 3). Image tensor is rescaled. :param filename (str): full-path filename of the image :param img_shape (int):...
e666dc909dbc0411c009ca791d1ee2aacf9d32c1
52,897
def jacobi_recr_coeffs(n, alpha, beta): """calculate the coefficients used in recursion relationship Args: n: the targeting order alpha: the alpha coefficient of Jacobi polynomial beta: the veta coefficient of Jacobi polynomial Returns: a1, a2, a3, a4: the coefficients used...
f9beb604af7b82fad8e0a81beed6852ea007cd30
52,898
def get_key(window, key): """ Returns the last reported state of a keyboard key for the specified window. Wrapper for: int glfwGetKey(GLFWwindow* window, int key); """ return _glfw.glfwGetKey(window, key)
b3b1b699d766ae9054278bcc85654c35cd9b3241
52,899