content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def serialize(value): """If the value is an BSON ObjectId, cast it to a string.""" if isinstance(value, bson.objectid.ObjectId): return str(value) else: return value
1fd0e01ebb46e4501b3a82744fcd3b2cdeaaf35b
37,239
def stash_node_versions(node_id): """Gets all version of a node. stash currently only keeps upto 10 versions. """ return stash_invoke('node-versions', node_id)
5b0c32c6f3d45e18233d65255267652eca416d59
37,240
from datetime import datetime def predict_one_epoch(sess, ops, train_writer): """ ops: dict mapping from string to tf ops """ is_training = True # Shuffle train samples # train_idxs = np.arange(0, len(TRAIN_DATASET)) # 预测不需要打乱 # np.random.shuffle(train_idxs) # num_batches = len(TRAIN_DATA...
a48c7a309702f2e9db5a59d6ba50d3d1579d33f9
37,244
from typing import Tuple import re import typing def hex_to_rgb(hex: str, hsl: bool = False) -> Tuple[int, int, int]: """Converts a HEX code into RGB or HSL. Taken from https://stackoverflow.com/a/62083599/7853533 Args: hex (str): Takes both short as well as long HEX codes. hsl (bool): C...
2c912dacfcf6c52c21c94c5d7bb9b9763279245d
37,245
def load_burn_data(url) -> xr.Dataset: """Open a GeoTIFF into an in memory DataArray with DataArray labelled as given name""" geotiff_burn = xr.open_rasterio(url) burn_dataset = geotiff_burn.to_dataset('band') return burn_dataset
195ba329ba5e3d07a737a93e73403d76caa8ca61
37,247
def strip_org(name): """ Returns the name with ORG_PREFIX stripped from it. """ if name.startswith(ORG_PREFIX): return name[len(ORG_PREFIX):] else: return name
855e1bf886c3a3335901e03eab4bb8d1e0e86ebc
37,248
import json def _ios_format_data(cmd_outputs: json) -> json: """ This function will retrieve data from differents commands outputs and gegroup them in a structured data format. Three command are executed on devices -> show ip ospf neighbor detail -> show ip ospf interface -> sh...
cf8cd150b0cdb19f80a962d7c13956347d32f665
37,249
def get_mode_C_array(mode_C): """冷房の運転モードを取得する Args: mode_C(str): 冷房方式 Returns: tuple: 冷房の運転モード """ # 運転モード(冷房) if mode_C == '住戸全体を連続的に冷房する方式': return tuple(["全館連続"] * 12) else: return ('居室間歇', '居室間歇', '居室間歇', '居室間歇', '居室間歇', None, None, None, None, None, None,...
6b9bce2eccab7698ec78ef3b843b17f3c3c9200d
37,250
def launch_and_move(prog_array, workspace, get_wid=get_wid_by_pid, new_name=None): """Launch application and move the created window to `workspace`. Returns the window id as used by wmcrtl. `prog_array` : list forwarded to subprocess.Popen. This should include the co...
db55e33bc6d9f6c9118e04ed0b1c153f5f66e525
37,251
def construct_label_array(video_labels): """Construction label array.""" label_arr = np.zeros((cfg.MODEL.NUM_CLASSES, )) # AVA label index starts from 1. for lbl in video_labels: if lbl == -1: continue assert lbl >= 1 and lbl <= 80 label_arr[lbl - 1] = 1 return l...
0a49f915324311d24888bfa03be186a16f61cdcf
37,252
from typing import Optional def any(x: _cpp.Variable, dim: Optional[str] = None, *, out: Optional[_cpp.Variable] = None) -> _cpp.Variable: """Element-wise OR over the specified dimension or all dimensions if not provided. :param x: Input data. :param dim: Optional dimension al...
fbe911d588adabe9d1f2dbe885a830dedf73e86d
37,253
from datetime import datetime def get_date(): """ gets current date """ return datetime.now()
dccf420bc6eb216bf76ee153504696ec1c390b5d
37,254
def singular(plural): """ Take a plural English word and turn it into singular Obviously, this doesn't work in general. It know just enough words to generate XML tag names for list items. For example, if we have an element called 'tracks' in the response, it will be serialized as a list without ...
92ab7e074387d943d5593d759a10b3fafa67deca
37,255
def create_simple_keras_model(learning_rate=0.1): """Returns an instance of `tf.Keras.Model` with just one dense layer. Args: learning_rate: The learning rate to use with the SGD optimizer. Returns: An instance of `tf.Keras.Model`. """ model = tf.keras.models.Sequential([ tf.keras.layers.Flatt...
a1c777004fe253da5b9f1689284ab99cd6d98cd9
37,256
def elli(x, rot=0, xoffset=0, cond=1e6, actuator_noise=0.0, both=False): """Ellipsoid test objective function""" x = np.asarray(x) if not isscalar(x[0]): # parallel evaluation return [elli(xi, rot) for xi in x] # could save 20% overall if rot: x = rotate(x) N = len(x) if actuat...
8768114827746e1b45ec98aa373201d0e4f8c5bc
37,257
def plot_coauthor_network(docs: DocumentSet, *, max_authors=None, **kwargs): """Plot a co-author network. This is a shorthand for `plot_network(build_coauthor_network(docs))`.""" b, p = split_kwargs(**kwargs) return plot_network( build_coauthor_network(docs, max_authors=max_authors, **b), *...
b98e7ec214b92dd413fac7f27ace9423af9e0921
37,258
def read_gene_list(fname, id_type): """Return references for genes from a file with the given ID type. Parameters ---------- fname : str The name of the file containing the list of genes. Each line of the file corresponds to a single gene. id_type : str The type of identifie...
612e5254c47f3ec189a18c989abd89b8a414d3da
37,259
from datetime import datetime from typing import Dict def backtest( start_date: datetime = None, end_date: datetime = None, interval=1, yield_interval=100, start_balances: Dict[str, float] = None, starting_coin: str = None, config: Config = None, ): """ :param config: Configuratio...
9aa527f6fa11a00ccdbc2c39e3cd0f79fb322e8e
37,260
def define_vgg_pre_processing(tf_input): """ This function defines the vgg_pre_processing network using the tensorflow nn api. Parameters ---------- tf_input: tensorflow.Tensor The input tensor to the network. The image is expected to be in RGB format. Returns ------- ...
e74f686da3f6ec068c4ee69a0a20f63015bec569
37,261
import torch def subreservoir(weight: Tensor, k=3): """ size of weight must devide by k """ subres_size = weight.size(0) // k mask = np.zeros_like(weight) for i in range(k): mask[i * subres_size: (i + 1) * subres_size, i * subres_size: (i + 1) * subres_size] = torch.ones(subres_size, ...
ede0db464956bbf825b57650ae9198c656b850bc
37,262
def buy_tickets(request): """ Provides the event form data and passes it to the frontend as json """ form_html = "" message_html = "" success = True # Ensure all required data has been sent if 'event' not in request.GET or not request.GET['event']: messages.error(request, 'No event infor...
aa5a2791688c9696d462b5efc33ab7f79a83dc93
37,263
def crop_and_revenue_to_df(financial_annual_overview, waste_adjusted_yields, total_sales, vadded_sales, education_rev, tourism_rev, hospitality_rev, grants_rev): """Adding yields and sales information to financial overview Notes: Adds waste-adjusted yields for crops 1, 2, 3 and 4 with t...
6be32e6f4ff3ae0ed6434313b8bcc2f44192231b
37,264
def download_blob(bucket_name, source_blob_name): """Downloads a blob from the bucket.""" client = storage.Client() storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(source_blob_name) return blob.download_as_string()
1251b9f1675237306e5f0057fecd136da6d4cad7
37,266
def val_epoch(state: train_state.TrainState): """ perform a validation epoch :param state: :return: """ val_config = deepcopy(config) val_config['data']['val_fns'] = "path_to_tvqa/val{:03d}of008.tfrecord" val_config['data']['num_val_files'] = 8 val_config['data']['do_random_scale'] =...
023a2b9ec1da79cb7d3b604dcf9ff2b23cb99a2d
37,267
import torch def getBERTFeatures(model, text, attn_head_idx=-1): # attn_head_idx - index o[] """ Get BERT features for the `text` Args: model: BERT model of type `BertForPreTrainingCustom` text: required, get features for this text attn_head_idx: optional, defaults to last layer ...
63a05f9457bbe8e7178c931321d48dc60243bfab
37,268
def filter_rows_via_column_matching(data, column, index=0): """ Filter data, by keeping rows whose particular field index matches the column criteria It takes parameters: data (data in the form of a list of lists) column (used as the match criteria for a particular field of the data) and op...
fcd5548677290a34d94c2eb8d5fefcb2bb50f0b4
37,269
def get_td_at_index(tr, index): """ When calculating the rowspan for a given cell it is required to find all table cells 'below' the initial cell with a v_merge. This function will return the td element at the passed in index, taking into account colspans. """ current = 0 for td in tr.xpath(...
f9b72d5597714273c527187738b99a69580c0576
37,270
import re def _normalize_name(name: str) -> str: """ Normalizes the given name. """ return re.sub(r"[^a-zA-Z0-9.\-_]", "_", name)
b38a90c05b0a6ec5a26db6d0da85bed2ae802cea
37,271
def time_step(las, historic_las, max_t, transport, data_df, transport_threshold, transport_time, transport_severity, transport_release, beta_threshold, beta_time, beta_severity, lockdown_release, nat=False): """ Enacts all actions of the day such as the morning commute,...
4a95d47304616288dbf8e5ea6f1a9abf63700bec
37,272
def filter_claims_by_date(claims_data, from_date, to_date): """Return claims falling in the specified date range.""" return [ claim for claim in claims_data if (from_date <= claim.clm_from_dt <= to_date) ]
d1568d0fd52382bdb3f1f02414f591d5f4da3596
37,274
import json def get_policies_in_category(jamf_url, object_type, object_name, enc_creds, verbosity): """return all policies in a category""" url = "{}/JSSResource/{}/{}".format( jamf_url, object_types(object_type), object_name ) r = curl.request("GET", url, enc_creds, verbosity) if r.stat...
c0621a10c922d6a6cbcaad4d3a1ba68bb70a79b4
37,275
from userbot.modules.sql_helper.notes_sql import add_note async def add_note(fltr): """ .save """ try: except AttributeError: await fltr.edit("`Bot Non-SQL modunda işləyir!!`") return keyword = fltr.pattern_match.group(1) string = fltr.text.partition(keyword)[2] msg = await fl...
276290fc376671adc8694c6f0e9869e344c12309
37,276
import tqdm def get_sorted_nodelist(nodelist, timeout): """ check all nodes and poll for latency, eliminate nodes with no response, then sort nodes by increasing latency and return as a list """ pool_size = mp.cpu_count()*2 n = len(nodelist) with mp.Pool(processes=pool_size...
c903f8b5bae1aaf5557b4ed60b32aebdf34fc0d7
37,277
def featurise_mols(smiles_list, representation, bond_radius=3, nBits=2048): """ Featurise molecules according to representation :param smiles_list: list of molecule SMILES :param representation: str giving the representation. Can be 'fingerprints' or 'fragments'. :param bond_radius: int giving the b...
bb2a3f1eb50b52beabd2da013ee50cf668f02354
37,278
def clear_inactive_structural_variant_sets(_self): """Task to cleanup variant sets and their variants that are stuck in a non-active status for a long time.""" return models.cleanup_variant_sets()
cbcefe13b6cbadc9cf6636ba6dbe17b6db944a80
37,279
def unicode2str(content): """Convert the unicode element of the content to str recursively.""" if isinstance(content, dict): result = {} for key in content.keys(): result[unicode2str(key)] = unicode2str(content[key]) return result elif isinstance(content, list): r...
30618f0305d28646af36bcff488af971643fd142
37,280
def cell_test(U,count,max_kpd_=None): """Tests the ability of the niggli basis to preserve the symmetry of the parent cell under action of the HNF. Args: U (numpy array): The parent lattice as columns of vector. count (dict): A dictionary to count how many times each niggli cel...
e9e488470f19275a42101f1e3224f59acc0f841c
37,281
def get_engine(path: str) -> create_engine: """ Function for connecting to the database-file :param path: path to the file :return: sqlmodel's engine """ return create_engine(path, echo=False)
0a7eb924934ed9b0ea276daa46943ae626ed3073
37,282
def mri_signal_inversion_recovery_function(input_data: dict) -> np.ndarray: """ Function that calculates the inversion recovery signal """ t1: np.ndarray = input_data["t1"].image t2: np.ndarray = input_data["t2"].image m0: np.ndarray = input_data["m0"].image mag_enc: np.ndarray = input_data["mag_en...
ef0819be79a1d575caf4defdedcf2e1d6bb32d49
37,283
def clip_grads(grad_tree, max_norm): """Clip gradients stored as a pytree of arrays to maximum norm `max_norm`.""" norm = l2_norm(grad_tree) normalize = lambda g: np.where(norm < max_norm, g, g * (max_norm / norm)) return layers.nested_map(grad_tree, normalize)
0f6790f92716939263c61a732121e67579916162
37,284
def get_all_facility_users(admin: Client, facility_id: int) -> dict: # noqa: unused client """Query for users related to the given facility.""" disallow_parameters(request) return { 'user': [ user.to_json() for user in Facility.from_id(facility_id).users() ] }
1d72d1e506d052ca67c204035d3d32078833cded
37,285
def rpkm(count, length, nb_read): """ Return the rpkm value """ length /= 10**3 return rpm(count, length, nb_read) / length
8e0c8a557b8bd6a10eead706e5176811d7706dec
37,286
import copy def usm_make(sequence, A=None, seed='centroid'): """ Calculates USM coordinates of a categorical sequence of arbitrary alphabet size. Parameters ---------- sequence : LIST OR ARRAY TYPE; CATEGORICAL SEQUENCE OF DATA d : LIST, optional; LIST CONTAINING ALL POSSIBLE ...
c689a3fba96b0bc995103b9d2c16ef6ab98030aa
37,287
def single_dataset_variableselect(c=cmdc.Client()): """ This example loads a subset of the demographic data by selecting a few variables and a few fips codes """ c.demographics( variable=[ "Total population", "Fraction of population over 65", "Median age",...
4a64844a434e06d188a142f2a5658112104f4caa
37,288
from operator import gt def _get_total_sizes(graph_tensor: gt.GraphTensor) -> SizeConstraints: """Returns the total number of items in the `graph_tensor`.""" return SizeConstraints( total_num_components=graph_tensor.total_num_components, total_num_nodes={ name: node_set.total_size ...
a9c802f5d2b1280132f0016c2b30cfede2692e5e
37,290
def _lookup_credentials_data_workspace_access(access_key_id): """ Raises HawkFail if the access key ID is not of Data workspace """ if access_key_id != settings.HAWK_LITE_DATA_WORKSPACE_CREDENTIALS: raise HawkFail(f"Incorrect Hawk ID ({access_key_id}) for Data workspace") return _lookup_cre...
7f2adcd5576d03a5d41ab7af2aa273fb8a2e13e7
37,291
def generate_2d_data(func, size=100, data_range=(-2., 2.), validation=False, visualize=False, seed=100): """Generates 2d data according to function. Args: func: (function) function that takes (x, y) and return a scalar size: (int) size of training sample to generate ...
a78116489d151624a997fb1b464b86b068cd1df6
37,293
def sphere_line_intercept(l, o, r): """Calculate intercept point between line y = l.x + o and a sphere around the center of origin of the coordinate system: c=0 Parameters: ------------ l ... vector of line of sight o ... observer position r ... vector of dis...
83f3d22a0af6f2a7b9042622525dde7d1984842d
37,294
from typing import List def compress_pulses(schedules: List[Schedule]) -> List[Schedule]: """Optimization pass to replace identical pulses. Args: schedules: Schedules to compress. Returns: Compressed schedules. """ existing_pulses = [] new_schedules = [] for schedule in...
5782b725fa08b26125722a9b695ca4ff92e229d3
37,295
def get_localhost_info() -> dict: """Get information about the specifications of localhost. Returns: dict: Current dict keys: 'os', 'cpu_cores', 'memory', 'python_version', 'workspace_version', 'gpus'. """ info = { "os": _get_os_on_localhost(), "cpu_cores": _get_cpu_count_on_loc...
ce6959f9a5cc95d643c99c0180da53e661226c4f
37,296
def predictions(logits): """Class prediction from logits.""" inner_dim = logits.get_shape().as_list()[-1] with tf.name_scope('predictions'): # For binary classification if inner_dim == 1: pred = tf.cast(tf.greater(tf.squeeze(logits, -1), 0.), tf.int64) # For multi-class classification else: ...
11b08eca2c8f7a65bb778651374bdee605968a30
37,299
def clean_string_dots(str_to_clean=None): """ this function try to clean a string like "Media. . . . . . . . . . . " it will eliminate all the dots and blanck spaces :param str_to_clean: <string> :return: <string> """ if str_to_clean is None: raise("Error, We need a string") ...
6d64bc10a26af5cbd11ccfcbfb3cbd7b2775f6be
37,300
def delete_multiple( request ): """ Delete multiple posts. Variables required in the POST request: - api_key : User identifier. - id[] : A list with the posts identifiers. """ posts = _get_post_list( request ) if isinstance( posts, HttpResponse ): ret...
d7fe7f973b3809285382f6489b64933cc264b889
37,301
def plot_round(logs): """ Plot round growth """ dfs = {k : v.round for k,v in logs.items() if not v.round.empty} # fig,ax = figure_with_legend() plt.title("Round vs T") plt.grid() plt.xlabel("Time") plt.ylabel("Round") for k,v in dfs.items(): plt.plot(v['at'], v['R'],...
df1aa45cf7e208dbc0ad07f04f4a9b93b1c915c4
37,304
def r_example(y0=None, ymax=None, xi=0.01): """https://rdrr.io/rforge/bvpSolve/f/inst/doc/bvpTests.pdf""" L = np.eye(1, 2) R = np.eye(1, 2) y0 = np.array([1.0]) if y0 is None else y0 ymax = np.array([1.5]) if ymax is None else ymax t0 = 0.0 tmax = 1.0 return BoundaryValueProblem( ...
b725f2a76b2291ed7a6f3fd1ec87a98253434bcf
37,305
def get_languages() -> dict[str, str]: """ This method is used to get all the languages available for translation with googletrans :return: dict of languages """ return LANGUAGES
3a1ff4c00edaaac350dd2a8317ad3460df788a24
37,306
import pickle def train(sound_dir, noise_dir=None, neural_network=None, n_files=None, val_split=0.15, ext='mp4', **train_kwargs): """ Train model using a simpler pipeline that is mostly automated for the user. The user simply has to point to the directory with pure sound videos and directory ...
bf4cc7db313f3f75f4cf461d30dcddc79ccdbd70
37,307
from typing import List from typing import Tuple def get_random(building_list: List[str]) -> Tuple[str, str]: """ Get 2 random element from the given list. Parameters ---------- building_list: List[str] A list containing all the remaining building that haven't been pla...
b91b6560f68e33a6d59abd0ed8af7514f36128d6
37,308
import collections def average_over_transforms(func, geometric_transforms, state): """Average a function over transformations to achive rotation invariance.""" result_list = collections.defaultdict(list) for transform in geometric_transforms: output = transform.inverse(func(transform.forward(state))) f...
4f1a6ec9f660bcc6470ac7afe41bf45f1b7b6a8f
37,312
import json def encode_json(struct): """Encode a structure as JSON bytes.""" return bytes(json.dumps(struct), "utf-8")
6724c0a687a98230a32fef81b3a4447c12d164fc
37,314
def categories_to_errors_dict(): """Categories to error dictionary function maps common error substrings to categories. The categories are keys in the dictionary and the values are arrays of strings or arrays of list. Some error categories, such as User Errors, has many subcategories. Thus, ...
4b59fc9775d3d5d808ecedee7756dad5d302848a
37,315
def extract_comments(filename, mime=None): """Extracts and returns the comments from the given source file. Args: filename: String name of the file to extract comments from. mime: Optional MIME type for file (str). Note some MIME types accepted don't comply with RFC2045. If not give...
d0f2de5b4935b5fad6b525d5e6bd83efe453d073
37,316
def cov(arr : np.ndarray): """Compute the sample covariance matrix for a matrix arr, assumed to be given in (samples x features) form for data fitting applications. Parameters ---------- arr : np.ndarray matrix in (samples x features) form """ n, _ = arr.shape return...
9727922a984d4e27b4de0f92d9ec94328231a34b
37,317
def is_rdn_equal(rdn1, rdn2): """Returns True if and only if the RDNs are equal. * RDNs must have the same number of AVAs. * Each AVA of the RDNs must be the equal for the same attribute type. The order isn't significant. Note that an attribute type will only be in one AVA in an RDN, otherwise ...
8f2710aa33f251020841b0f86b2f2f61cbf64cc6
37,318
def EMetaclass(cls): """Class decorator for creating PyEcore metaclass.""" superclass = cls.__bases__ if not issubclass(cls, EObject): sclasslist = list(superclass) if object in superclass: index = sclasslist.index(object) sclasslist.insert(index, EObject) ...
7e84de2daa4b8bc08843e63295aa540de0a907d6
37,321
def _first_defined(*args): """Return the first non-null argument (PRIVATE).""" for arg in args: if arg is not None: return arg return None
0e0fc10e5ef14d9b445dae5b5dbb5ce467e1cb1b
37,322
import re def rhyme_analyser(str, rhyme_db): """ Rhyme Analyzer - Print out the rhyme scheme of a poem. Given: A string - like If you want to smell a rose You must put it to your nose. If you want to eat some bread You must not eat it in bed Or I will eat your toes. Output: Rhyme s...
0fb166c92b2e60d1739638b23a3de5dae18ce26b
37,324
def show_log() -> list: """ Отоброжает содержимое log_tab. :return: список кортежей со всеми данными из таблицы. """ try: with DatabaseConnection(app.config['log_db_config']) as cursor: _SQL = """SELECT * FROM log_tab ORDER BY ts DESC LIMIT 1000;""" cursor.execute(...
1d47b4adf178656a7c63ff23a91337a6eb6ed171
37,325
def gate_neighbours(current, grid, path): """ Generate a heatmap for gates so that A star can avoid gates. This consists of all direct neighbours, diagonal neighbours, and every coordinate straight above the gate in question """ neighbours = list() # Generate all other coordinates around the ...
a3055ee81756c147a44335b219da194471b4fe4c
37,326
def is_chosen(bbox, area_threshold=None) -> bool: """ Calculate area of bounding boxes and return True if area >= threshold Args: bbox: (x1, y1, width, heigh) area_threshold: Returns: True/False """ are = bbox[2] * bbox[3] if area_threshold is not None: if ...
091fda7a389a74e92703c6eeca05aec413bc65a5
37,329
import pymess def pymess_dae2_cnt_riccati(mmat=None, amat=None, jmat=None, bmat=None, wmat=None, z0=None, mtxoldb=None, transposed=False, aditol=5e-10, nwtn_res2_tol=5e-8, maxit=20, verbose=False, linesearch=False, **kw): """ solv...
7de34ce6106ba5c0cb1f13e2ad9c2f79327ce829
37,330
def is_unary_operator(oper): """returns True, if operator is unary operator, otherwise False""" # definition: # memeber in class # ret-type operator symbol() # ret-type operator [++ --](int) # globally # ret-type operator symbol( arg ) # ret-type operator [++ --](X&, int) symbols = [...
fa563cb7bc24462779ddcb0a61dbf6f93903a1d8
37,331
def map_advanced_param(param, value): """ Maps an advanced parameter value to the value expected on the krdict website. """ return _get_advanced_param(_ADVANCED_PARAM_MAP[param], str(value), True)
39d174e897ecde71d6185db815caa2c272e292ea
37,332
def basin_to_gridcell_dict(df_reference): """Generate a dictionary of gridcell id to basin id {grid_id: basin_id} :param df_reference: Input data reference dataframe containing grid to basin info :type df_reference: dataframe :return: dict. {grid_id: basin...
730823f7c2f1da2bbf5a114c5b270ab741dfdb24
37,333
def fitness_coeff_constant(N_site,N_state,h_0,J_0): """ creating the mutational fitness coefficients for the simulated sequences in the case of constant fields and constant couplings Parameters: N_site: int sequence length N_state: int number of states per site ...
811c248de631d91c8bafd0617f05f7b02a07289c
37,334
def add_to_user_path(new_path: str, ): """ Add **one** path into PATH of current user """ assert ';' not in new_path old_fixed_paths = get_user_path() for p in old_fixed_paths: if is_same_file(p, new_path): return old_paths = get_user_path() return set_user_path([new_...
51dec120301296847dbfbc4da17f20581dfa6c2b
37,335
def generate_1d_scatter(data, variables, class_data=None, class_names=None, nrows=None, ncols=None, sharex=False, sharey=False, show_legend=True, outliers=False, cmap_class=None, **kwargs): """Generate 1D scatter plots from the given data and v...
9b09b2fbc92bd888b060cd7d3b751783030bc8f7
37,336
def create_translator_instance(): """Create IBM Translator Instance.""" authenticator = IAMAuthenticator(apikey) language_translator = LanguageTranslatorV3( version='2018-05-01', authenticator=authenticator ) language_translator.set_service_url(url) return language_translator
0e6124be33d8a783937a09980b25bcdfe09e3c2b
37,338
def shot(**kwargs): """ Adds a shot entity under the shots table in the `wgid` database. Args: kwargs(dict): Reference alfred configs Returns: True if successful """ key = "shot" cmd = _create_from_config(key) cmd += _create_entity(key, **kwargs) # Submit SQL ...
747cb2623a3ea197ea1f6b1a96d5104d26cfbe23
37,339
def symmAndRefl(t, ipt=False): """ Return the transducer t | t.inverse, if ipt is True; return the transducer t | t.inverse | id, otherwise :type t: SFT :type ipt: bool :rtype: SFT""" t1 = t | t.inverse() if ipt is True: return t1 t2 = SFT() s0 = t2.addState() ...
81f088bd27aa25a6d8104912ace56306873aa8ac
37,340
import logging def show( document: vp.Document, classic: bool, force: bool, show_pen_up: bool, show_points: bool, outline: bool, colorful: bool, show_axes: bool, show_grid: bool, hide_legend: bool, unit: str, ): """Display the geometry in an graphical user interface. ...
a0e1e1819c5ed3e1d73bdaa427afefe1ca8e4300
37,341
def _float(value): """Return env var cast as float.""" return float(value)
254b1e3a542c5a74153cd58d3f43e86dab964028
37,342
import copy import warnings from datetime import datetime def correctMSdataset(data, window=11, method='LOWESS', align='median', parallelise=True, excludeFailures=True): """ Conduct run-order correction and batch alignment on the :py:class:`~nPYc.objects.MSDataset` instance *data*, returning a new instance with cor...
b7f7cd1ffc8c01520b8a0231f83db5cbdf7f35b6
37,343
def create_assignment_registry(): """Create the registry for course properties.""" reg = FieldRegistry( base.OfflineAssignmentBase.NAME, description=base.OfflineAssignmentBase.DESCRIPTION) # Course level settings. reg.add_property(SchemaField( 'key', 'ID', 'string', editable=Fa...
f26fd224133c059e734029cfd8add042ac16b718
37,344
def do_s3_media_url(parser, token, static=False): """ This is for use with ``CloudFrontURLs`` and will return the appropriate url if a match is found. Usage:: {% s3_media_url path %} For ``HTTPS``, the ``cuddlybuddly.storage.s3.middleware.ThreadLocals`` middleware must also be used. ...
db8d740a7c3b8406694a53494c9835c3986d2536
37,345
def wavlm(refresh=False, *args, **kwargs): """ The default model - Base-Plus refresh (bool): whether to download ckpt/config again if existed """ return wavlm_base_plus(refresh=refresh, *args, **kwargs)
371ccdf7f955142b2f8343d59998323fbe4f02e9
37,346
def add_area_from_serialized_data( annotation_model, area_id, serialized_area_data, lv0_height ): """Add point annotation data to annotation model from serialized_data""" serialized_area_data = AreaAnnotationSerializedData( *serialized_area_data ) flag, area_record = create_area_annotati...
2d03640a7674e0a7e5af5cf6a05ea77424c05f97
37,347
def select_largest_3prime_footprint(transcripts): """Select transcript(s) with largest 3' footprint""" ret = [transcripts[0]] furthest = transcripts[0].utr3_end for i in range(1, len(transcripts)): t = transcripts[i] utr3footprint = t.utr3_end if utr3footprint == furthest: ...
35a437351a886c00c431b2adf61fad42118e94f8
37,348
def read_mutation_matrix(file_in): """Create a table from a mutation matrix provided by SNPad Returns ------- tbl : Pandas.table A table containing the mutation probability for base at each position of a read. sn : list of dict The list contains the highest probability for which we ...
28a397d25ce6afb2d9b06534c2e8780a44253508
37,349
def ctc_cost(acts, labels, input_lengths = None): """ Given sequences of output layer activations and labels, compute the softmax output at each timestep, and then compute the CTC cost of each sequence with respect to its corresponding label sequence. :param acts: Tensor of pre-softmax activations, with shape=...
e12183a91ab146e123be58e82ad54c9284db67d5
37,350
import torch def center_size(boxes): """ Convert prior_boxes to (cx, cy, w, h) representation for comparison to center-size form ground truth data. Args: boxes: (tensor) point_form boxes Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. """ wh = boxes[:, 2...
8e2cc32aa59aeae2e8ef7ffd9489420b94a105a2
37,351
def train_network(data, supervisor): """ This function abstracts out the learning process for the Fuzzy ARTMAP algorithm. :param data: The data of the training set :param supervisor: The supervisor data, to train against :return: new_network, the trained ARTMAP network utilised in classification and...
29d71e51590c8407c994db067cd25f8ee16422a4
37,352
def add(user_obj): """Add a User""" user_obj.set_password() return crud.add(user_obj)
433e8fe8ecc44e66008a403ba26a666de6870b60
37,353
def perspective_transform(img): """ This class takes in the Gradient and Color Space thresholded binary image, and perspective transforms the Binary image to halp make view the lanes to be viewed from the top (as like in Bird's eye view). We take 4 source points that are assumed to form a Quadrilat...
b6c18fff72d403b13ec8dd392237b88102ebf0d7
37,354
def numericise(value, empty_value=''): """Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty2zero flag is set - The same input string, empty or not, ...
4faff17b9434cfa9c57556c335b8fbf2463842ea
37,355
def test_likelihood_value(): """Just a sanity check to show we get the right likelihood values""" config = test_conf_reparam(events_per_day=1) conv_config = deepcopy(BASE_CONV_CONFIG) # initialize the old likelihood first # this is an input for the reparameterized likelihood lf_old = UnbinnedLog...
b6f2d369846a5eb36760e9bffbe660d4747be590
37,356
def show_booking_page(): """Show booking page.""" return render_template('booking.html') # will need another route to process the booking form
930726776fb226e9d066e89e21e96d32bd1aeb43
37,358
def axis(*v, **kwargs): """ Convenience method to get or set axis properties. Calling with no arguments:: >>> axis() returns the current axes limits ``[xmin, xmax, ymin, ymax]``.:: >>> axis(v) sets the min and max of the x and y axes, with ``v = [xmin, xmax, ymin, ymax]``.:: ...
7b28f933be0d60a708ae9fe7fc817dcbe92a86d0
37,359
def split_data(data, num_folds, fold): """ Partitions and returns selected partition :param data: data :param num_folds: num folds to make :param fold: selected fold :return: data_fold, data_rest """ X = data['X'] t = data['t'] xJoinT = np.c_[X, t] rows = np.size(xJoinT, 0) ...
f79094ca5065c79e11514fbb912c8ce30df685d8
37,360
import typing import requests def buy( symbol: str, quantity: int, duration: str = "gtc", order_type: str = "market", price: typing.Any = None, stop: typing.Any = None, brokerage: typing.Any = USER_BROKERAGE, access_token: str = USER_ACCESS_TOKEN, ...
e04fe21778634af8c24a83a1e694a976c2ac96cf
37,361