content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import html def update_table1(is_open, signup, user_edit, user_remove): """update_table """ df = lookup_data() # Add icons df[_('Active')] = df[_('Active')].apply(lambda x: html.I(className="fa fa-check") if x else None ) df[_('Edit')] = df[_('UID')].apply(lambda x: dbc.B...
c93ce73bfb1d4d74cf2d05e98e2689db908d3b2d
32,598
def create_app(*args, **kwargs): """ Create flask app with predefined values. :return: Flask application """ """Create flask app with all configuration set""" app = flask.Flask(__name__) app.register_blueprint(pps_blueprint) app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO...
84e283f7e7d5299e0a6f4f77c590e53eb5890df1
32,600
from typing import Optional def _rebase_node(curr: Optional[SQLNode], pre: SQLNode) -> SQLNode: """shorthand for a common pattern""" return pre if curr is None else curr.rebase(pre)
84e7fbb901009619d8183dc779a94f08404833d1
32,601
def proposal_list(request): """Retrieve and return a list of proposals, optionally filtered by the given acceptance status. Requires API Key. URL: /<YEAR>/pycon_api/proposals/ To filter by proposal type, add a GET query param "type" with a value of "talk", "tutorial", "lightning", or "poster"...
dadb694c162c385dc6aba1ac8d9dfdfced117a5e
32,602
def apply_mask(image, mask, color, alpha=0.5): """Apply the given mask to the image. """ for c in range(3): image[:, :, c] = np.where(mask == 1, image[:, :, c] * (1 - alpha) + alpha * color[c] * 255, ...
b57c6606eb125ece0f00825a41c99702affd0a9e
32,603
import re def clean_str(string): """ Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py """ string = unidecode(string) string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r...
56c55ef100aa2c612e5a84f061b82ac225be2bd0
32,604
def dkm_ms_em_remote_check_stopping(w, wo, epsilon): """ Stopping condition is distance below some epsilon """ delta = np.sum([abs(w[i] - wo[i]) for i in range(len(w))]) # print("Delta", delta) result = delta > epsilon return result
c226ed6f6b7e3a383e6f59492ed1b30d1f8eec31
32,605
def parse_from_string(root_processor, xml_string): """ Parses the XML string using the processor starting from the root of the document. :param xml_string: XML string to parse. See also :func:`declxml.parse_from_file` """ if not _is_valid_root_processor(root_processor): raise InvalidRo...
015f89cb407bef4564cd2aa4de0f807c69cd2a15
32,606
def validate(args, limit_to=None): """Validate an input dictionary for Coastal Blue Carbon. Args: args (dict): The args dictionary. limit_to=None (str or None): If a string key, only this args parameter will be validated. If ``None``, all args parameters will be validat...
57dd66464dca7d28974366e63755e84905c9c90d
32,607
def findBestK(x_train, y_train, params, R): """ Función que calcula los valores de accuracy media obtenidos con validación cruzada para los valores del parámetro K que se indican como parámetro, y visualiza dichos valores en un gráfico Args: x_train: conjunto de entrena...
d9b07ccbca0551928a6966ab0dd6b29965668373
32,608
import base64 def pdf_to_img(pdf: str) -> [str]: """ Takes a base64 encoded string representing a PDF and turns it into a list of base64 encoded strings representing pages in the PDF :param pdf: :return: list of strings """ imgs = list() decoded = b64string_to_bytes(pdf) images = c...
cf04b206b24786116cc5a92550333ac256db391d
32,609
def is_ready(): """Checks if IoT Inspector is ready to interface with the AR app.""" return OK_JSON
c6b860179e4a969e1069b405bfcbd76c1b95c1d4
32,610
from typing import List from typing import Dict from typing import Any def get_indicators_command(client: Client, insight_category: list, insight_data_type: list, args: dict) -> List[Dict]: """Create indicators. Arguments: client {Client} -- Client derives from BaseClient. ...
63a678da0abd76e56fceaad2a075e7d209eced00
32,611
def engineer_features(df,training=True): """ for any given day the target becomes the sum of the next days revenue for that day we engineer several features that help predict the summed revenue the 'training' flag will trim data that should not be used for training when set to false all data wi...
b10b973e5ef7cbe9aa2d7c436747673d83c0d5f6
32,613
def inconsistent_target_program(): """Returns a benchmark.Benchmark with an inconsistent target program.""" examples = [ benchmark.Example( inputs=[ [10], [20], ], output=[40], # Should be 30. ), ] constants = [0] description = 'add elemen...
c7cc9e6fa380e2a1e111e5dabd6e9412582bb825
32,614
def _slice_slice(outer, outer_len, inner, inner_len): """ slice a slice - we take advantage of Python 3 range's support for indexing. """ assert(outer_len >= inner_len) outer_rng = range(*outer.indices(outer_len)) rng = outer_rng[inner] start, stop, step = rng.start, rng.stop, rng.step ...
4430ae752fbc9d7db6414418b18a0b8186f3d328
32,615
def tp(a): """Tranpose 1d vector""" return a[np.newaxis].T
86f357de5d1f080194867e826db5ff78c3926b92
32,616
def _parse_interval(value): """ Do some nasty try/except voodoo to get some sort of datetime object(s) out of the string. """ try: return sorted(aniso8601.parse_interval(value)) except ValueError: try: return aniso8601.parse_datetime(value), None except ValueE...
d99151734cd6ba81919857482e56c627a4b3aa9b
32,617
def is_masquerading_as_non_audit_enrollment(user, course_key, course_masquerade=None): """ Return if the user is a staff member masquerading as a user in _any_ enrollment track _except_ audit """ group_id = _get_masquerade_group_id(ENROLLMENT_TRACK_PARTITION_ID, user, course_key, course_masquerade) ...
cd337e3f44a9c618609d103c5c0c6617fc62d70b
32,618
def holding_value_grouped_nb(holding_value, group_lens): """Get holding value series per group.""" check_group_lens(group_lens, holding_value.shape[1]) out = np.empty((holding_value.shape[0], len(group_lens)), dtype=np.float_) from_col = 0 for group in range(len(group_lens)): to_col = from_...
c0b0e2f538e9849671c5388c82f822d755d24b61
32,619
def read_upload(up_file, data_model=None): """ take a file that should be ready for upload using the data model, check that all required columns are full, and that all numeric data is in fact numeric. print out warnings for any validation problems return True if there were no problems, otherwise...
b62339cc17aadd51f1a97cab3fe5158b5eaacf0b
32,620
import torch def predict(network, X, batch_size, device, move_network=True): """ predict batchwise """ # Build DataLoader if move_network: network = network.to(device) y = torch.Tensor(X.size()[0]) data = DataLoader(TensorDataset(X, y), batch_size, False) # Batch prediction network...
e9f2c12e812950d73a4aec57c966f76f5c006785
32,621
def read_glossary_df(plugins): """Returns the glossary as a DataFrame, created from the schemas.yml file. NOTE: This is used by the GUI.""" global __glossary_df if __glossary_df is None: schemas = cea.schemas.schemas(plugins) glossary_df = pd.DataFrame(columns=["SCRIPT", "LOCATOR_METHOD", "W...
246f27927cc70eb03be8e9b84423442ef5b884e2
32,623
from pathlib import Path def extract_all(session_path, save=False, data=False): """ Extract all behaviour data from Bpod whithin the specified folder. The timing information from FPGA is extracted in :func:`~ibllib.io.extractors.ephys_fpga` :param session_path: folder containing sessions :ty...
5ace8847251d3c4a971e5717495613179ead49c4
32,624
def tokenize(data): """ Tokenization. Tokenize and lemmatize the sentences; extract labels of tokens. Parameters ---------- data : list of dict each dict should have the following form: {"sentence": str, "sentence_id": str, "annotations": [ {"ann_id": str "text": str, "sta...
91a0db8ff0054f249f08ecb02f4fddeb17af40fe
32,625
def rotate_thread(thymio: Thymio, angle: float, verbose: bool = False, function=stop, args=None, kwargs=None): """ Rotates of the desired angle by using a timer on a parallel thread. :param function: function to execute at the end of rotation, default stop :param args: array of non-keyworded ...
d19ea0f601ff991a20e889b62481f46a0475573d
32,626
import bigflow.transform_impls.first def first(pcollection, **options): """ 取出PCollection中的第一个元素 Args: pcollection (PCollection): 输入PCollection **options: 可配置选项 Returns: PObject: 取出的单个元素,以PObject给出 >>> from bigflow import transforms >>> _p = _pipeline.parallelize([3, 7,...
993c6603c182bd67ee0c22418243c0ce9933ef37
32,627
def select_values_over_last_axis(values, indices): """ Auxiliary function to select logits corresponding to chosen tokens. :param values: logits for all actions: float32[batch,tick,action] :param indices: action ids int32[batch,tick] :returns: values selected for the given actions: float[batch,tick]...
a116e9fb009a53f3da2e177a9cefd5382ba44906
32,628
def dump_adcs(adcs, drvname='ina219', interface=2): """Dump xml formatted INA219 adcs for servod. Args: adcs: array of adc elements. Each array element is a tuple consisting of: slv: int representing the i2c slave address plus optional channel if ADC (INA3221 only) has multiple channels. ...
b9c0aec3e6098a5de28a467910f4861e8860d723
32,629
def list_launch_agents(): """ Return an array of the files that are present in ~/Library/LaunchAgents, /System/Library/LaunchAgents/ and /Library/LaunchAgents/ """ files = list_system_launch_agents() files += list_library_launch_agents() files += list_homedir_launch_agents() return files
f8a890064f9140b6f67c9be489b5b4a991255ebe
32,630
def get_projection_point_dst(coords_src, M): """ Gets the coordinate equivalent in surface projection space from original view space Args: coords_src: `numpy.darray` coordinate in the original image space M: `numpy.darray` rotation matrix Returns: coords_src: `numpy.da...
b93f52727d4ca378c54094a89ce346e049bdf818
32,631
import torch def torchify(a): """Converts an array or a dict of numpy arrays to CPU tensors. If you'd like CUDA tensors, follow the tensor-ification ``.cuda()`` ; the attribute delegation built into :class:`~rebar.dotdict.dotdict` s will do the rest. Floats get mapped to 32-bit PyTorch floats; i...
d91577b1e4e9c1d0f2a1703995400e51623f9abe
32,632
def rel_angle(vec_set1, vec_set2): """ Calculate the relative angle between two vector sets Args: vec_set1(array[array]): an array of two vectors vec_set2(array[array]): second array of two vectors """ return vec_angle(vec_set2[0], vec_set2[1]) / vec_angle( vec_set1[0], vec_...
bc18b1e8c2225eac8fcded45c07e8d0fcaaba5bb
32,633
def equalization(data, equilibrium_points): """ Эквализация данных. Параметры: data - таблица данных, которые нужно выровнять. Тип - pandas.DataFrame. equilibrium_points - точки сдвига равновесия. Для каждого столбца нужно использовать свою точку равновесия, т.к. у каждой кривой должна ...
c3c5dd9dafe6dd8655216ef53033968700d80e93
32,634
import json def from_config(config_file="./config.json"): """Run training from a config file :param config_file: JSON file with arguments as per "training" CLI. :return: """ with open(config_file, "r") as f: config_string = f.read() config = json.loads(config_string) return ma...
31eb83d0c364a31fcf515d164ca306c6756c70c9
32,635
def load_anomalies_text(input_path): """Loads the Anomalies proto stored in text format in the input path. Args: input_path: File path from which to load the Anomalies proto. Returns: An Anomalies protocol buffer. """ anomalies = anomalies_pb2.Anomalies() anomalies_text = file_io.read_file_to_stri...
c723faff2a5b622162f3d23041a3c13dd44d35bb
32,636
def is_isbn_or_key(q): """ 判断搜索关键字是isbn还是key :param q: :return: """ # isbn13 13位0-9数字;isbn10 10位0-9数字,中间含有 '-' isbn_or_key = 'key' if len(q) == 13 and q.isdigit(): isbn_or_key = 'isbn' if '-' in q: short_q = q.replace('-', '') if len(short_q) == 10 and short_q...
cf35f13e8188741bd37715a1ed91cf40667cff40
32,638
def find_scripts(entry_points=False, suffix=''): """Find IPython's scripts. if entry_points is True: return setuptools entry_point-style definitions else: return file paths of plain scripts [default] suffix is appended to script names if entry_points is True, so that the Python 3 s...
3103915d245f753f04ccf0eab682cccd57629613
32,639
def get_upright_box(waymo_box): """Convert waymo box to upright box format and return the convered box.""" xmin = waymo_box.center_x - waymo_box.length / 2 # xmax = waymo_box.center_x+waymo_box.length/2 ymin = waymo_box.center_y - waymo_box.width / 2 # ymax = waymo_box.center_y+waymo_box.width/2 ...
2c301e3d60078ba416446dfe133fb9802c96f09c
32,640
def update_two_contribution_score(click_time_one, click_time_two): """ user cf user contribution score update v2 :param click_time_one: different user action time to the same item :param click_time_two: time two :return: contribution score """ delta_time = abs(click_time_two - click_time_one...
df959e4581f84be5e0dffd5c35ebe70b97a78383
32,642
def series_dropna(series, axis=0, inplace=False, how=None): """ Return a new Series with missing values removed. See the :ref:`User Guide <missing_data>` for more on which values are considered missing, and how to work with missing data. Parameters ---------- axis : {0 or 'index'}, default...
994b9b8a6552f49a8533744a58091daa14557641
32,643
def partial_escape(xpath): """ Copied from http://stackoverflow.com/questions/275174/how-do-i-perform-html-decoding-encoding-using-python-django but without replacing the single quote """ return mark_safe(force_unicode(xpath).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('...
5588b97ec57d2df2ed22ded28d9d8b98b8ed3851
32,644
def identify_regions(lat_lon, coordinates=False): """ Returns the region associated with the given lat/lon point. Args: lat_lon (:obj:`list` of :obj:`float`): latitude/longitude point to access coordinates (bool): optionally include a list of all registered coordinates f...
4a32bb0afd8d5768325769e8b89b3cd2cf593b4f
32,645
def fix_text_note(text): """Wrap CHS document text.""" if not text: return "" else: return """* CHS "Chicago Streets" Document:\n> «{}»""".format(text)
56cbcbad7e8b3eee6bb527a240ad96701c4eea2f
32,646
def GetCBSPLogFile(): """ Generate the CBSP base file name used for many things, including accessing *jason* files. """ return Config.GetCBSPInstanceName()
10d0f141e3ee7f605fce22c9f971eb9f2eabebd2
32,647
from typing import Optional def pretty_xml(document: 'Document', declaration: Optional[str] = None, encoding: Optional[str] = UTF8, indent: int = 2) -> str: """Render the given :class:`~xml.dom.minidom.Document` `document` into a prettified string.""" kwargs = { ...
0f342831ccb69cf1b1b7a4f379364d8b8c046f41
32,648
def cluster(image, R): """Split the image points up into a number of clusters At first there are 10 clusters 1. The centre of each cluster are set to be equally spaced out in angle, at a radius of 1 2. Each point is looped through and assigned to the ...
063c513e771874b78725726a84383c1dff06552c
32,649
import torch def bbox_xyxy_to_cxcywh(bbox): """Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, w, h). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes. """ x1, y1, x2, y2 = bbox.split((1, 1, 1, 1), dim=-1) bbox_new = [(x1 + x2) / 2, (...
4d8a7c4147a8c604004215d6240de33e72608abd
32,651
def get_isolated_page(request: HttpRequest) -> bool: """Accept a GET param `?nav=no` to render an isolated, navless page.""" return request.GET.get("nav") == "no"
bdfde1929308915cd797b25e2003e1b78fc2e75a
32,652
import multiprocessing def _fetch_cpu_count(): """ Returns the number of available CPUs on machine in use. Parameters: ----------- None Returns: -------- multiprocessing.cpu_count() Notes: ------ None """ return multiprocessing.cpu_count()
6c35446b706aa27b49bd678520b2378b1c7f8b90
32,655
def MakeAxesActor(): """ Make an axis actor. :return: The axis actor. """ axes = vtkAxesActor() axes.SetShaftTypeToCylinder() axes.SetXAxisLabelText('X') axes.SetYAxisLabelText('Y') axes.SetZAxisLabelText('Z') axes.SetTotalLength(1.0, 1.0, 1.0) axes.SetCylinderRadius(1.0 * a...
295dfc3ed64c5b7d307ebc5e710007055954c15c
32,657
def bmi_stats(merged_df, out=None, include_min=True, include_mean=True, include_max=True, include_std=True, include_mean_diff=True, include_count=True, age_range=[2, 20], include_missing=False): """ Computes summary statistics for BMI. Clean values are for BMIs computed when both the hei...
2665fd7a4156451c55437a63626572cab32d9cda
32,659
async def system_health_info(hass): """Get info for the info page.""" remaining_requests = list(hass.data[DOMAIN].values())[0][ COORDINATOR ].accuweather.requests_remaining return { "can_reach_server": system_health.async_check_can_reach_url(hass, ENDPOINT), "remaining_requests"...
8b63a669180af16839e2dc36af30c3c45e39dfdf
32,660
def predict_ankle_model(data): """Generate ankle model predictions for data. Args: data (dict): all data matrices/lists for a single subject. Returns: labels (dict): columns include 'probas' (from model) and 'true' (ground truth). One row for each fold. """ RESULT_DIR ...
e2ebea56855f6717f01d7962b00d6b8ee0df16ea
32,661
def cholesky_decomp(A): """ Function: int gsl_linalg_cholesky_decomp (gsl_matrix * A) This function factorizes the positive-definite square matrix A into the Cholesky decomposition A = L L^T. On output the diagonal and lower triangular part of the input matrix A contain the matrix L. The upper ...
004669d55eb58df99e1724beab8453ce4140697f
32,662
def is_block_comment(line): """ Entering/exiting a block comment """ line = line.strip() if line == '"""' or (line.startswith('"""') and not line.endswith('"""')): return True if line == "'''" or (line.startswith("'''") and not line.endswith("'''")): return True return False
ea38c248964eeaec1eab928182022de6ecccad69
32,663
import tensorflow as tf import functools def generate_keras_segmentation_dual_transform(*layers): """Generates a `dual_transform` pipeline from Keras preprocessing layers. This method takes in Keras preprocessing layers and generates a transformation pipeline for the `dual_transform` argument in *sem...
6f10b4cf1ce8fc34aa71588682db99cbe6a01537
32,664
def get_before_deploy_steps(): """Get pre-deploy steps and their associated model aliases. Get a map of configuration steps to model aliases. If there are configuration steps which are not mapped to a model alias then these are associated with the the DEFAULT_MODEL_ALIAS. eg if test.yaml contained...
3277f8827f204f358501afeb781d6e2934727327
32,665
def pre_ml_preprocessing(df, initial_to_drop, num_cols, target_var = None, num_cols_threshold = 0.9, low_var_threshold = 0.9): """Process data for machine learning preprocessing. Low variance categorical features are high correlated numerical features are dropped from DataFrame. This process helps in dimension...
20325bc6d650cf9bccd06bf2547f36bc29e5d446
32,666
import json def pool_status(): """Fetch overall pool status.""" d = make_request('getpoolstatus') return json.loads(d)
0793dd3c5bb07f670b84b905fb030e278d4a9cba
32,667
from typing import List from typing import Dict import requests def get_airtable_data(url: str, token: str) -> List[Dict[str, str]]: """ Fetch all data from airtable. Returns a list of records where record is an array like {'my-key': 'George W. Bush', 'my-value': 'Male'} """ response = re...
f91326938a663ddedd8b4a10f796c7c36981da4e
32,668
def displayname(user): """Returns the best display name for the user""" return user.first_name or user.email
aecebc897803a195b08cdfb46dbeb4c9df9ede09
32,669
def format_satoshis_plain(x, decimal_point = 8): """Display a satoshi amount scaled. Always uses a '.' as a decimal point and has no thousands separator""" scale_factor = pow(10, decimal_point) return "{:.8f}".format(Decimal(x) / scale_factor).rstrip('0').rstrip('.')
2afa53e820d080bef762ab78fd02f09b60fe355f
32,670
def get_aps(dispatcher, apic, tenant): """Display Application Profiles configured in Cisco ACI.""" if not apic: dispatcher.prompt_from_menu("aci get-aps", "Select APIC Cluster", apic_choices) return False try: aci_obj = NautobotPluginChatopsAci(**aci_creds[apic]) except KeyError...
de7ab1a4680edb735c7cf2e46098b52d88ecb865
32,671
def delete_dnt(id): """ Function deleting specific department by its id :param id: id of the specific department an admin wants to delete :return: redirects user to the departments page """ if session.get('user') and session.get('user')[0] == ADMIN: data = f'?login={session["user"][0]}&p...
12f87af2a657eb631aabfac7acb88ce2e5abf07d
32,672
def price(listing): """Score based on number of bedrooms.""" if listing.price is None: return -4000 score = 0.0 bedrooms = 1.0 if listing.bedrooms is None else listing.bedrooms if (bedrooms * 1000.0) > listing.price: score += -1000 - ((bedrooms * 750.0) / listing.price - 1.0) * 1000 ...
7087da4e4f9dedf03fdaed5661029f1be0703f0e
32,673
def entropy_to_mnemonic(entropy: bytes) -> str: """Convert entropy bytes to a BIP39 english mnemonic Entropy can be 16, 20, 24, 28, 32, 36 or 40 bytes""" try: return wally.bip39_mnemonic_from_bytes(None, entropy) except ValueError: raise InvalidEntropy
1e4de2dfdde71a8ab241fae05385a6ce8c8a10f5
32,675
async def read_run(catalog_name: str, run_uid: str): """Summarize the run for the given uid.""" summary = databroker.run_summary(catalog_name, run_uid) if summary is None: raise HTTPException(status_code=404, detail="Not found") return summary
cf36b8bffa034392c8943ea179e67f28d12102e3
32,676
import shlex def shell_quote(*args: str) -> str: """ Takes command line arguments as positional args, and properly quotes each argument to make it safe to pass on the command line. Outputs a string containing all passed arguments properly quoted. Uses :func:`shlex.join` on Python 3.8+, and a for ...
b2d0ecde5a2569e46676fed81ed3ae034fb8d36c
32,677
def is_resources_sufficient(order): """Returns True when order can be made, False if ingredients are insufficient.""" check = [ True if MENU[order][key] <= resources[key] else False for key, value in MENU[order].items() ] return not False in check[:-1]
5454fca8ac7574e74c795d205a9355839f5320f2
32,678
def mode(arr): """Return the mode, i.e. most common value, of NumPy array <arr>""" uniques, counts = np.unique(arr, return_counts=True) return uniques[np.argmax(counts)]
abb8a79ff8ac4f28fe5e6e4491146c90ee680cd4
32,679
import torch def normalized_state_to_tensor(state, building): """ Transforms a state dict to a pytorch tensor. The function ensures the correct ordering of the elements according to the list building.global_state_variables. It expects a **normalized** state as input. """ ten = [[ state[sval] ...
4aea246f388f941290d2e4aeb6da16f91e210caa
32,680
def get_num_of_lines_in_file(filename): """Open the file and get the number of lines to use with tqdm as a progress bar.""" file_to_read = open(filename, "rb") buffer_generator = takewhile( lambda x: x, (file_to_read.raw.read(1024 * 1024) for _ in repeat(None)) ) return sum(buf.count(b"\n") ...
00d4a042a904140645d7f1e9fe6d85b86031fc3b
32,681
def translate_lat_to_geos5_native(latitude): """ The source for this formula is in the MERRA2 Variable Details - File specifications for GEOS pdf file. The Grid in the documentation has points from 1 to 361 and 1 to 576. The MERRA-2 Portal uses 0 to 360 and 0 to 575. latitude: float Needs +/- i...
b1fb1824bfefce3fd58ca7a26f9603b910779a61
32,682
def disabled_payments_notice(context, addon=None): """ If payments are disabled, we show a friendly message urging the developer to make his/her app free. """ addon = context.get('addon', addon) return {'request': context.get('request'), 'addon': addon}
b77dc41cf8ac656b2891f82328a04c1fe7aae49c
32,683
import time def upload_fastq_collection_single(gi,history_id,fastq_single): """ Uploads given fastq files to the Galaxy history and builds a dataset collection. :param gi: Galaxy instance. :param history_Id: History id to upload into. :param fastq_single: Single-end files to upload. :retu...
ecf3c3be06e0f012609214dc810ebefe67968ab1
32,684
import torch def get_world_size() -> int: """ Simple wrapper for correctly getting worldsize in both distributed / non-distributed settings """ return ( torch.distributed.get_world_size() if torch.distributed.is_available() and torch.distributed.is_initialized() else 1 ...
0017278b422aa39ea0a8074c70a7df84885c7929
32,685
def filtraColunas(df: pd.DataFrame, colunas_interesse: list) -> pd.DataFrame: """ Seleciona apenas as colunas de interesse de uma DataFrame Parameters ---------- DataFrame : pd.DataFrame DataFrame para filtragem colunas_interesse : list lista com os cabeçalhos das colunas de in...
bb2c2a0e5718e663750a420a6b70a7b9af182e4b
32,686
def PatSub(s, op, pat, replace_str): """Helper for ${x/pat/replace}.""" #log('PAT %r REPLACE %r', pat, replace_str) regex, err = glob_.GlobToExtendedRegex(pat) if err: e_die("Can't convert glob to regex: %r", pat) if regex is None: # Simple/fast path for fixed strings if op.do_all: return s.r...
d5272d9b16517ce4244573bad992031f78e40556
32,687
async def check_for_role(self, name): """ A function to check for the existence of a role. """ name = name.lower() role = ( await GuildRoles .query .where(database.func.lower(GuildRoles.name) == name) .gino .scalar() ) return role
c78b66660bcacf930a2945ccf90860b89799dfcc
32,688
def construct_futures_symbols( symbol, start_year=2010, end_year=2014 ): """ Constructs a list of futures contract codes for a particular symbol and timeframe. """ futures = [] # March, June, September and # December delivery codes months = 'HMUZ' for y in range(start_...
2917a9eb008f5ab141576243bddf4769decfd1f3
32,689
def UpdateDescription(unused_ref, args, request): """Update description. Args: unused_ref: unused. args: The argparse namespace. request: The request to modify. Returns: The updated request. """ if args.IsSpecified('clear_description'): request.group.description = '' elif args.IsSpecif...
2c70200915cef809f91d2f0f303b622b41301cfa
32,690
def getAllChannels(): """ a func to see all valid channels :return: a list channels """ return ["Hoechst", 'ERSyto', 'ERSytoBleed', 'Ph_golgi', 'Mito']
d4fee111bad73f8476877a96645490aef37c07c9
32,691
def get_virtual_func_address(name, tinfo=None, offset=None): """ :param name: method name :param tinfo: class tinfo :param offset: virtual table offset :return: address of the method """ address = idc.LocByName(name) if address != idaapi.BADADDR: return address address = C...
b7466609b0119d1a110a72fdb2d012f3f40a43dc
32,692
from typing import Callable from typing import Tuple from typing import List from typing import Dict def coupler_netlist( wg_width: float = 0.5, gap: float = 0.236, length: float = 20.007, coupler_symmetric_factory: Callable = coupler_symmetric, coupler_straight: Callable = coupler_straight, l...
d855b0ccfe435470f109b3c212083313ebe06ce1
32,693
def accuracy(output, target, mask, inc_fix=False): """ Calculate accuracy from output, target, and mask for the networks """ output = output.astype(cp.float32) target = target.astype(cp.float32) mask = mask.astype(cp.float32) arg_output = cp.argmax(output, -1) arg_target = cp.argmax(target, -...
c78be00f4c229f440987b1004878d6e944626dfd
32,694
def get_filterset_class(filterset_class, **meta): """Get the class to be used as the FilterSet""" if filterset_class: # If were given a FilterSet class, then set it up and # return it return setup_filterset(filterset_class) return custom_filterset_factory(**meta)
5b6f87fd6b299e89272fcc3f15499369cc2e3f0e
32,695
def first_lower(string): """ Return a string with the first character uncapitalized. Empty strings are supported. The original string is not changed. """ return string[:1].lower() + string[1:]
f3503902d18ffd5b5689c3738eb8c40e749d3e3e
32,696
def read_db() -> list: """Читает все данные из базы""" conn = psycopg2.connect(dbname=DB_NAME, user=DB_USERNAME, password=DB_PASS, host=DB_HOST) cursor = conn.cursor(cursor_factory=DictCursor) cursor.execute('SELECT * FROM posts') res = cursor.fetchall() conn.close() return res
481fadc0ba86cdb36d007a924424ff073e0c844c
32,697
def logit(p): """Logit function""" p = np.atleast_1d(np.asfarray(p)) logit_p = np.zeros_like(p) valid = (p > 0) & (p < 1) if np.any(valid): logit_p[valid] = np.log(p[valid] / (1 - p[valid])) logit_p[p==0] = np.NINF logit_p[p==1] = np.PINF return logit_p
a8d4ee374284721eeb04d2fd4409e28036a75f12
32,698
async def logout(request): """ Finish the session with auth, clear the cookie and stop the session being used again. """ session_id = request['session'].session_id await finish_session(request, session_id, 'logout') session = await get_session(request) session.pop(str(session_id)) await...
0ff00ddeb34c39ef7611d8896298aeca7070df5d
32,699
def create_multiple_new_predictions(monkeypatch): """ Mock prediction model method to ensure no duplicate prediction in predictions table. """ @classmethod async def mockfunc_get_one_by_username(cls, username): """Return a user record from the users table.""" hashed_pwd = bcrypt...
27608239ba1d1d5da0cf464d9ab1f752ec7057b6
32,700
def tidy_split(df, column, sep, keep=False): """ Split the values of a column and expand so the new DataFrame has one split value per row. Filters rows where the column is missing. Params ------ df : pandas.DataFrame dataframe with the column to split and expand column : str ...
4e4138cf4f5fab924d4e9e792db5e1c954ee8032
32,701
def greedyClustering(v_space, initial_pt_index, k, style): """ Generate `k` centers, starting with the `initial_pt_index`. Parameters: ---------- v_space: 2D array. The coordinate matrix of the initial geometry. The column number is the vertex's index. initia...
ac90d1d6c461a969a2bcb71f3df3a822496b3a65
32,702
def s2_matrix(beta, gamma, device=None): """ Returns a new tensor corresponding to matrix formulation of the given input tensors representing SO(3) group elements. Args: beta (`torch.FloatTensor`): beta attributes of group elements. gamma (`torch.FloatTensor`): gamma attributes of group...
20d08d1b75f22bddfaf5295751f05d43ea7fe6bb
32,703
import threading def cache(func): """Thread-safe caching.""" lock = threading.Lock() results = {} def wrapper(*args, **kwargs): identifier = checksum(args, kwargs) if identifier in results: return results[identifier] with lock: if identifier in results:...
c17a6550ec91edcfcad6d898a1f81fa4b878757a
32,704
import platform def hide_console(): """Startup-info for subprocess.Popen which hides the console on Windows. """ if platform.system() != 'Windows': return None si = sp.STARTUPINFO() si.dwFlags |= sp.STARTF_USESHOWWINDOW si.wShowWindow = sp.SW_HIDE return si
faf25cdf48ffddd2ae7185c457d1abe60a0ec181
32,706
from typing import Dict from typing import Any def merge_dicts(dict1: Dict[str, Any], dict2: Dict[str, Any], *dicts: Dict[str, Any]) -> Dict[str, Any]: """ Merge multiple dictionaries, producing a merged result without modifying the arguments. :param dict1: the firs...
869399774cc07801e5fa95d9903e6a9f2dadfc25
32,707
def decode(model, inputs): """Decode inputs.""" decoder_inputs = encode_onehot(np.array(['='])).squeeze() decoder_inputs = jnp.tile(decoder_inputs, (inputs.shape[0], 1)) return model( inputs, decoder_inputs, train=False, max_output_len=get_max_output_len())
632b57ab86b9dd670d3e7203197575130ded7057
32,708
from typing import Sequence from typing import List def combinations_all(data: Sequence) -> List: """ Return all combinations of all length for given sequence Args: data: sequence to get combinations of Returns: List: all combinations """ comb = [] for r in range(1, len(d...
7e0b31189a5afe3ac027a4c947aca08b3a2075ff
32,709