content
stringlengths
22
815k
id
int64
0
4.91M
def _system_message(message_contents): """ Create SYSTEM_MESSAGES_FILE file w/contents as specified. This file is displayed in the UI, and can be embedded in nginx 502 (/opt/galaxy/pkg/nginx/html/errdoc/gc2_502.html) """ # First write contents to file. if os.path.exists(SYSTEM_MESSAGES_FILE): ...
31,500
def detected(numbers, mode): """ Returns a Boolean result indicating whether the last member in a numeric array is the max or min, depending on the setting. Arguments - numbers: an array of numbers - mode: 'max' or 'min' """ call_dict = {'min': min, 'max': max} if mode not in ca...
31,501
def test_delete_multiple_status(mock_event: dict) -> None: """ Test that status effects get correctly removed when there are multiple status effects with a duration of 1 in the status effects list :param mock_event: Mock AWS lambda event dict """ # Arrange mock_event["body"]["Player1"]["act...
31,502
def generator_v0( samples, cfg ) : """Taken from section 18. Generators""" num_samples = len(samples) batch_size = cfg["batch_size"] step_size = batch_size // 2 while True : samples = sklearn.utils.shuffle(samples) for offset in range( 0, num_samples, step_s...
31,503
def calculate_compass_bearing(point_a, point_b): """ Calculates the bearing between two points. The formulae used is the following: θ = atan2(sin(Δlong).cos(lat2), cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong)) :Parameters: - `pointA: The tuple representing the lat...
31,504
def parse_instructions(instruction_list): """ Parses the instruction strings into a dictionary """ instruction_dict = [] for instruction in instruction_list: regex_match = re.match(r"(?P<direction>\w)(?P<value>\d*)",instruction) if regex_match: instruction_dict.append(reg...
31,505
def calc_elapsed_sleep(in_num, hyp_file, fpath, savedir, export=True): """ Calculate minutes of elapsed sleep from a hypnogram file & concatenate stage 2 sleep files Parameters ---------- in_num: str patient identifier hyp_file: str (format: *.txt) file with hypnogram at 30-sec...
31,506
def delete_file(path): """ 删除一个目录下的所有文件 :param path: str, dir path :return: None """ for i in os.listdir(path): # 取文件或者目录的绝对路径 path_children = os.path.join(path, i) if os.path.isfile(path_children): if path_children.endswith(".h5") or path_children.endswit...
31,507
def label(ctx, name): """Manipulate labels.""" ctx.obj['name'] = name
31,508
def valid_pairs(pairs, chain): """ Determine if the chain contains any invalid pairs (e.g. ETH_XMR) """ for primary, secondary in zip(chain[:-1], chain[1:]): if not (primary, secondary) in pairs and \ not (secondary, primary) in pairs: return False return True
31,509
def setup(sub_args, ifiles, repo_path, output_path): """Setup the pipeline for execution and creates config file from templates @param sub_args <parser.parse_args() object>: Parsed arguments for run sub-command @param repo_path <str>: Path to installation or source code and its templates ...
31,510
def fqname_for(obj: Any) -> str: """ Returns the fully qualified name of ``obj``. Parameters ---------- obj The class we are interested in. Returns ------- str The fully qualified name of ``obj``. """ if "<locals>" in obj.__qualname__: raise RuntimeErro...
31,511
def analyzer_zipfile(platform, monitor): """Creates the Zip file that is sent to the Guest.""" t = time.time() zip_data = io.BytesIO() zip_file = zipfile.ZipFile(zip_data, "w", zipfile.ZIP_STORED) # Select the proper analyzer's folder according to the operating # system associated with the cur...
31,512
def symbol_size(values): """ Rescale given values to reasonable symbol sizes in the plot. """ max_size = 50.0 min_size = 5.0 # Rescale max. slope = (max_size - min_size)/(values.max() - values.min()) return slope*(values - values.max()) + max_size
31,513
def test_distance_function(cosine_kmeans): """ Checks that cosine kmeans uses distance_cosine as the distance calculator. """ assert isinstance(cosine_kmeans.distance_func, type(distance_cosine))
31,514
def AddServiceAccountArg(parser): """Adds argument for specifying service account used by the workflow.""" parser.add_argument( '--service-account', help='The service account that should be used as ' 'the workflow identity. "projects/PROJECT_ID/serviceAccounts/" prefix ' 'may be skipped from...
31,515
def delete(id): """Soft delete a patient.""" check_patient_permission(id) patient = Patient.query.get(id) patient.deleted = datetime.datetime.now() patient.deleted_by = current_user db.session.commit() return redirect(url_for('screener.index'))
31,516
def system_temp_dir(): """ Return the global temp directory for the current user. """ temp_dir = os.getenv('SCANCODE_TMP') if not temp_dir: sc = text.python_safe_name('scancode_' + system.username) temp_dir = os.path.join(tempfile.gettempdir(), sc) create_dir(temp_dir) return...
31,517
def _pipeline_network_multiple_database(database: List[str], kernel_method: Callable, filter_network_omic: Union[List, str]) -> Union[Matrix, str]: """Process network for a multiple database.""" network = None db_norm = frozenset([db.lower().replace(' ', '_') for db ...
31,518
def _to_tensor(args, data): """Change data to tensor.""" if vega.is_torch_backend(): import torch data = torch.tensor(data) if args.device == "GPU": return data.cuda() else: return data elif vega.is_tf_backend(): import tensorflow as tf ...
31,519
def materialize_jupyter_deployment( config: ClusterConfig, uuid: str, definition: DeploymentDefinition) -> JupyterDeploymentImpl: # noqa """Materializes the Jupyter deployment definition. :param config: Cluster to materialize the Jupyter deployment with. :param uuid: Unique...
31,520
async def test_filter_matching_past_event(mock_now, hass, calendar): """Test that the matching past event is not returned.""" config = dict(CALDAV_CONFIG) config["custom_calendars"] = [ {"name": "Private", "calendar": "Private", "search": "This is a normal event"} ] assert await async_setup...
31,521
def show_M(N): """ N: int """ n = np.arange(N) k = n.reshape((N,1)) M = k*n print("M:", M)
31,522
def update_weekly_downloads(): """Update the weekly "downloads" from the users_install table.""" raise_if_reindex_in_progress() interval = datetime.datetime.today() - datetime.timedelta(days=7) counts = (Installed.objects.values('addon') .filter(created__gte=interval, ...
31,523
def _CreateLSTMPruneVariables(lstm_obj, input_depth, h_depth): """Function to create additional variables for pruning.""" mask = lstm_obj.add_variable( name="mask", shape=[input_depth + h_depth, 4 * h_depth], initializer=tf.ones_initializer(), trainable=False, dtype=lstm_obj.dtype) ...
31,524
def get_index_fredkin_gate(N, padding = 0): """Get paramaters for log2(N) Fredkin gates Args: - N (int): dimensional of states - padding (int, optional): Defaults to 0. Returns: - list of int: params for the second and third Frekin gates """ indices = [] for i in range(...
31,525
def import_by_name(name): """ 动态导入 """ tmp = name.split(".") module_name = ".".join(tmp[0:-1]) obj_name = tmp[-1] module = __import__(module_name, globals(), locals(), [obj_name]) return getattr(module, obj_name)
31,526
def fyolo_vgg_voc(backbone="vgg16", num_layers=13, pretrained_base=True, pretrained=False, num_sync_bn_devices=-1, **kwargs): """FYOLO of VGG on VOC dataset Parameters ---------- backbone : str Use the imagenet pretrained backbone ("vgg11", "vgg13" or "vgg16") for initializati...
31,527
def f1_score(y_true, y_pred): """F-measure.""" p = precision(y_true, y_pred) r = true_positive_rate(y_true, y_pred) return 2 * (p * r) / (p + r)
31,528
def hexColorToInt(rgb): """Convert rgb color string to STK integer color code.""" r = int(rgb[0:2],16) g = int(rgb[2:4],16) b = int(rgb[4:6],16) color = format(b, '02X') + format(g, '02X') + format(r, '02X') return int(color,16)
31,529
def reset_speed(): """ reset vertical speed as score achieves certain level :return: float, new vertical speed """ global y_speed # when score achieves 50 if score == 50: # ball moves faster y_speed = y_speed * 1.2 graphics.reset_vertical_velocity(dy) # when score...
31,530
def test(model, X, model_type, test_type, counter=False): """Test functions.""" if model_type == 'notear-mlp': X = np.vstack(X) y = model(torch.from_numpy(X)) y = y.cpu().detach().numpy() mse = mean_squared_loss(y.shape[0], y[:, 0], X[:, 0]) elif model_type == 'notear-castle': X = np.vstack(X...
31,531
def scale(): """ Returns class instance of `Scale`. For more details, please have a look at the implementations inside `Scale`. Returns ------- Scale : Class instance implementing all 'scale' processes. """ return Scale()
31,532
def imread_rgb(filename): """Read image file from filename and return rgb numpy array""" bgr = cv2.imread(filename) rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) return rgb
31,533
def insert_at_index(rootllist, newllist, index): """ Insert newllist in the llist following rootllist such that newllist is at the provided index in the resulting llist""" # At start if index == 0: newllist.child = rootllist return newllist # Walk through the list curllist = rootllist for i in ran...
31,534
def _save_observables( file_name: str, file_override: bool, observable_names: List[str], observable_defs: List[Union[str, Callable]], ) -> None: """ Save observable properties into a HDF5 data file Parameters ---------- file_name: str HDF5 file name to save observables prope...
31,535
def kpi_value(request, body): """kpi值接口 根据 indicator 传入参数不同请求不同的 handler""" params = { "indicator": body.indicator } handler = KpiFactory().create_handler(params["indicator"]) result = handler(params=params) return DashboardResult(content=result)
31,536
def safeReplaceOrder( references ): """ When inlining a variable, if multiple instances occur on the line, then the last reference must be replaced first. Otherwise the remaining intra-line references will be incorrect. """ def safeReplaceOrderCmp(self, other): return -cmp(self.colno, o...
31,537
def broken_link_finder(urls: Union[str, list, tuple, set], print_to_console: bool = False, file_out = None, viewer = DEFAULT_CSV_VIEWER, open_results_when_done = True, exclude_prefixes: Iterable = EXC...
31,538
def test_compute_reproject_roi_issue1047(): """ `compute_reproject_roi(geobox, geobox[roi])` sometimes returns `src_roi != roi`, when `geobox` has (1) tiny pixels and (2) oddly sized `alignment`. Test this issue is resolved. """ geobox = GeoBox(3000, 3000, Affine(0.00027778,...
31,539
def clean_value(value: str) -> t.Union[int, float, str]: """Return the given value as an int or float if possible, otherwise as the original string.""" try: return int(value) except ValueError: pass try: return float(value) except ValueError: pass return value
31,540
def check_matching_unit_dimension( ureg: UnitRegistry, base_units: str, units_to_check: List[str] ) -> None: """ Check if all units_to_check have the same Dimension like the base_units If not :raise DimensionalityError """ base_unit = getattr(ureg, base_units) for unit_string in units_...
31,541
def sumstat(*L): """ Sums a list or a tuple L Modified from pg 80 of Web Programming in Python """ if len(L) == 1 and \ ( isinstance(L[0],types.ListType) or \ isinstance (L[0], types.TupleType) ) : L = L[0] s = 0.0 for k in L: s = s + k r...
31,542
def test_cases_by_pinned_gene_query(app, case_obj, institute_obj): """Test cases filtering by providing the gene of one of its pinned variants""" # GIVEN a test variant hitting POT1 gene (hgnc_id:17284) suspects = [] test_variant = store.variant_collection.find_one({"genes.hgnc_id": {"$in": [17284]}}) ...
31,543
def halref_to_data_url(halref: str) -> str: """ Given a HAL or HAL-data document URIRef, returns the corresponding HAL-data URL halref: str HAL document URL (Most important!) https://hal.archives-ouvertes.fr/hal-02371715v2 -> https://data.archives-ouvertes.fr/document/hal-02371715v...
31,544
def find_best_rate(): """ Input: Annual salary, semi-annual raise, cost of home Assumes: a time frame of three years (36 months), a down payment of 25% of the total cost, current savings starting from 0 and annual return of 4% Returns the best savings rate within (plus/minus) $100 of the down...
31,545
def export_secret_key(ctx, account_name): """print secret key of own account.""" account = get_account(ctx, account_name) data = account.export_secret_key() click.echo(data)
31,546
def q_inv(a): """Return the inverse of a quaternion.""" return [a[0], -a[1], -a[2], -a[3]]
31,547
def divide_hex_grid_flower(points, hex_radius=None): """Partitions a hexagonal grid into a flower pattern (this is what I used for the final product. Returns a list of partition indices for each point.""" if hex_radius is None: # copied from build_mirror_array() mini_hex_radius = (10 * 2.5 / 2) + 1 ...
31,548
def fis_gauss2mf(x:float, s1:float, c1:float, s2:float, c2:float): """Split Gaussian Member Function""" t1 = 1.0 t2 = 1.0 if x < c1: t1 = fis_gaussmf(x, s1, c1) if x > c2: t2 = fis_gaussmf(x, s2, c2) return (t1 * t2)
31,549
def _is_trigonal_prism(vectors, dev_cutoff=15): """ Triangular prisms are defined by 3 vertices in a triangular pattern on two aligned planes. Unfortunately, the angles are dependent on the length and width of the prism. Need more examples to come up with a better way of detecting this shape. For now, this...
31,550
def get_sza(times, rad, mask=None): """ Fetch sza at all range cell in radar FoV rad: Radar code mask: mask metrix """ fname = "data/sim/{rad}.geolocate.data.nc.gz".format(rad=rad) os.system("gzip -d " + fname) fname = fname.replace(".gz","") data = Dataset(fname) lat, lon = data...
31,551
def load_results(path): """ return a dictionary of columns can't use genfromtex because of weird format for arrays that I used :param path: :return: """ data = defaultdict(list) column_casts = { "epoch": float, "env_name": str, "game_counter": int, "game...
31,552
def save_tf(model, folder, filename): """Save model in Tensorflow format Args: model {graph_def} -- classification model folder {string} -- folder name filename {string} -- model filename """ filepath = os.path.join(folder, filename) sess = K.get_session(...
31,553
def priority(n=0): """ Sets the priority of the plugin. Higher values indicate a higher priority. This should be used as a decorator. Returns a decorator function. :param n: priority (higher values = higher priority) :type n: int :rtype: function """ def wrapper(cls): cls...
31,554
def vecangle(u,v): """ Calculate as accurately as possible the angle between two 3-component vectors u and v. This formula comes from W. Kahan's advice in his paper "How Futile are Mindless Assessments of Roundoff in Floating-Point Computation?" (https://www.cs.berkeley.edu/~wkahan/Mindless.pdf), ...
31,555
def _setup_sensor(hass, humidity): """Set up the test sensor.""" hass.states.async_set(ENT_SENSOR, humidity)
31,556
def rm_empty_dir(path, rmed_empty_dirs): """Recursively remove empty directories under and including path.""" if not os.path.isdir(path): return fnames = os.listdir(path) if len(fnames) > 0: for fn in fnames: fpath = os.path.join(path, fn) if os.path.isdir(fpath)...
31,557
def sanitize_option(option): """ Format the given string by stripping the trailing parentheses eg. Auckland City (123) -> Auckland City :param option: String to be formatted :return: Substring without the trailing parentheses """ return ' '.join(option.split(' ')[:-1]).strip()
31,558
def node_values_for_tests(): """Creates a list of possible node values for parameters Returns: List[Any]: possible node values """ return [1, 3, 5, 7, "hello"]
31,559
def computeGramMatrix(A, B): """ Constructs a linear kernel matrix between A and B. We assume that each row in A and B represents a d-dimensional feature vector. Parameters: A: a (n_batch, n, d) Tensor. B: a (n_batch, m, d) Tensor. Returns: a (n_batch, n, m) Tensor. """ ...
31,560
def parse_config(config): """Backwards compatible parsing. :param config: ConfigParser object initilized with nvp.ini. :returns: A tuple consisting of a control cluster object and a plugin_config variable. raises: In general, system exceptions are not caught but are propagated up to the...
31,561
def example(tracker,img_path,dest,scr,disp,log,kb_obj,kb_chc): """ Describe Demonstration Example """ txt_task = ("Scientist at work in a laboratory.") img_name = "scientist.jpg" exp1(tracker,dest,img_path,img_name,txt_task,scr,disp,log,kb_obj,kb_chc) scr.clear() scr.draw_text(text= "Great wor...
31,562
def test_private_median(example_private_table: PrivateTable): """check private median implementation using Age in adult dataset.""" noisy_median = example_private_table.median('Age', PrivacyBudget(10000.)) check_absolute_error(noisy_median, 37., 1.) del noisy_median
31,563
def _generate_output_data_files_threaded( short_topic, output_template, plaintext_key, output_folder, encryption_json_text_output, output_iv_full, job_id, ): """Generates required historic data files from the files in the given folder using multiple threads. Keyword arguments: s...
31,564
def deletable_proxy_user(request, onefs_client): """Get the name of an existing proxy user that it is ok to delete.""" return _deletable_proxy_user(request, onefs_client)
31,565
def get_from_module(identifier, module_params, module_name, instantiate=False, kwargs=None): """The function is stolen from keras.utils.generic_utils. """ if isinstance(identifier, six.string_types): res = module_params.get(identifier) if not res: raise Except...
31,566
def test_mnist_model_register_and_scale_using_non_existent_handler(): """ Bug - Following code block will result in "Buggy" behaviour. If a non-existent handler is used, then ideally we should not be able to scale up workers anytime, but currently Torchserve scales up background workers. Uncomment it after ...
31,567
def color_lerp(c1, c2, a): """Return the linear interpolation between two colors. ``a`` is the interpolation value, with 0 returing ``c1``, 1 returning ``c2``, and 0.5 returing a color halfway between both. Args: c1 (Union[Tuple[int, int, int], Sequence[int]]): The first color. At...
31,568
def get_equations(points): """ Calculate affine equations of inputted points Input : 1 points : list of list ex : [[[x1, y1], [x2, y2]], [[xx1, yy1], [xx2, yy2]]] for 2 identified elements Contains coordinates of separation lines i.e. [[[st...
31,569
def Temple_Loc(player, num): """temple location function""" player.coins -= num player.score += num player.donation += num # player = temple_bonus_check(player) for acheivements return (player)
31,570
def save_crowdin(data): """ Save crowdin `data`. """ fpath = os.path.join(REPO_ROOT, CROWDIN_FILE) with open(fpath, "w") as fh: fh.write(yaml.safe_dump(data))
31,571
def indexGenomeFile(input, output): """Index STAR genome index file `input`: Input probes fasta file `output`: SAindex file to check the completion of STAR genome index """ #print input #print output base = splitext(input)[0] base = base + ".gtf" #print base gtfFile = base o...
31,572
def assert_allclose( actual: numpy.ndarray, desired: Tuple[float, float, float], rtol: numpy.float64, atol: numpy.float64, err_msg: Literal["driver: None"], ): """ usage.scipy: 2 """ ...
31,573
def test_list_id_max_length_1_nistxml_sv_iv_list_id_max_length_2_1(mode, save_output, output_format): """ Type list/ID is restricted by facet maxLength with value 6. """ assert_bindings( schema="nistData/list/ID/Schema+Instance/NISTSchema-SV-IV-list-ID-maxLength-2.xsd", instance="nistDat...
31,574
def performance(origin_labels, predict_labels, deci_value, bi_or_multi=False, res=False): """evaluations used to evaluate the performance of the model. :param deci_value: decision values used for ROC and AUC. :param bi_or_multi: binary or multiple classification :param origin_labels: true values of the ...
31,575
def group_emoves(emoves, props): """Elementary moves with the same scale ratio can be combined. All emoves are from the same group, so they share the same transformation distance. We can combine all emoves that also share the same scale ratio.""" # group the emoves by ratio emoves.sort(key=lambda x: x.n...
31,576
def rotkehlchen_instance( uninitialized_rotkehlchen, database, blockchain, accountant, start_with_logged_in_user, start_with_valid_premium, function_scope_messages_aggregator, db_password, rotki_premium_credentials, accounting_data_dir, ...
31,577
def enable_dashboard(cls, config): """Method to enable the dashboard module. if user bootstrap with skip-dashboard option then enabling the dashboard module. Args: cls (CephAdmin object) : cephadm instance object. config (Dict): Key/value pairs passed from the test suite. Exam...
31,578
def store_inspection_outputs_df(backend, annotation_iterators, code_reference, return_value, operator_context): """ Stores the inspection annotations for the rows in the dataframe and the inspection annotations for the DAG operators in a map """ dag_node_identifier = DagNodeIdentifier(operator_conte...
31,579
def picard_bedtointervallist(bed, refdict, out_path, no_header_out_path): """Starts a Picard BedToIntervalList process that writes to out_path""" cmd = f'{GATK_PATH} BedToIntervalList -SD "{refdict}" --INPUT "{bed}" --OUTPUT "{out_path}"' run_ext_process(cmd, shell=True) # Some GATK-Picard modules do n...
31,580
def breadth_first_search(g, s): """ Breadth First Search. Based on CLR book. For each node, it calculates a distance (from starting vertex s), and the parent node. @param g: input graph, assume all unvisited @type g: Graph @param s: starting vertex name """ # g.reset() node_s ...
31,581
def draw_overlay(image, overlay, alpha): """Draws an overlay over an image at a specified alpha. :param image: The base image. :param overlay: The overlay image. :param alpha: The opacity, from 0 to 1. :type image: ndarray :type overlay: ndarray :type alpha: float """ cv2.addWeighte...
31,582
def switched (decorator): """decorator transform for switched decorations. adds start_fun and stop_fun methods to class to control fun""" @simple_decorator def new_decorator (fun): event = new_event() def inner_fun (self, *args): if args: event.wait() if threads_alive(): retu...
31,583
def logistic_embedding0(k=1, dataset='epinions'): """using random embedding to train logistic Keyword Arguments: k {int} -- [folder] (default: {1}) dataset {str} -- [dataset] (default: {'epinions'}) Returns: [type] -- [pos_ratio, accuracy, f1_score0, f1_score1, f1_score2, auc_score...
31,584
def process_plus_glosses(word): """ Find all glosses with a plus inside. They correspond to one-phoneme affix sequences that are expressed by the same letter due to orthographic requirements. Replace the glosses and the morphemes. """ return rxPartsGloss.sub(process_plus_glosses_ana, word)
31,585
def replication(): """ 1) Connect to the PostgreSQL database server 2) Create and start logical replication with Postgres Server. 3) Call the Pub/sub function to push to Pub/Sub """ conn = None try: # read connection parameters dsn = config() # connect to t...
31,586
def check_in_the_past(value: datetime) -> datetime: """ Validate that a timestamp is in the past. """ assert value.tzinfo == timezone.utc, "date must be an explicit UTC timestamp" assert value < datetime.now(timezone.utc), "date must be in the past" return value
31,587
def fixture(filename): """ Get the handle / path to the test data folder. """ return os.path.join(fixtures_dir, filename)
31,588
def character_count_helper(results: Dict) -> int: """ Helper Function that computes character count for ocr results on a single image Parameters ---------- results: Dict (OCR results from a clapperboard instance) Returns ------- Int Number of words computed from ...
31,589
def from_pickle(input_path): """Read from pickle file.""" with open(input_path, 'rb') as f: unpickler = pickle.Unpickler(f) return unpickler.load()
31,590
def PromptForRegion(available_regions=constants.SUPPORTED_REGION): """Prompt for region from list of available regions. This method is referenced by the declaritive iam commands as a fallthrough for getting the region. Args: available_regions: list of the available regions to choose from Returns: T...
31,591
def update(x, new_x): """Update the value of `x` to `new_x`. # Arguments x: A `Variable`. new_x: A tensor of same shape as `x`. # Returns The variable `x` updated. """ return tf.assign(x, new_x)
31,592
def r1r2_to_bp(r1,r2,pl=0.01, pu=0.25): """ Convert uniform samling of r1 and r2 to impact parameter b and and radius ratio p following Espinoza 2018, https://iopscience.iop.org/article/10.3847/2515-5172/aaef38/meta Paramters: ----------- r1, r2: float; uniform parameters in from u(...
31,593
def is_utc_today(utc): """ Returns true if the UTC is today :param utc: :return: """ current_time = datetime.datetime.utcnow() day_start = current_time - datetime.timedelta(hours=current_time.hour, minutes=current_time.minute, seconds=curre...
31,594
def test_run_completed(mock_job, mock_queue, mock_driver): """Test run function for a successful run.""" # Setup def mock_render(*args, **kwargs): return class MockStorage: def __init__(self): pass def load(self, *args, **kwargs): return 'blah' ...
31,595
async def get_telegram_id(phone_number, user_mode=False): """ Tries to get a telegram ID for the passed in phone number. """ async with start_bot_client() as bot: if user_mode: # just leaving this code here in case it proves useful. # It only works if you use a user, not ...
31,596
def QuadRemesh(thisMesh, parameters, multiple=False): """ Quad remesh this mesh. """ url = "rhino/geometry/mesh/quadremesh-mesh_quadremeshparameters" if multiple: url += "?multiple=true" args = [thisMesh, parameters] if multiple: args = list(zip(thisMesh, parameters)) response = Util.Com...
31,597
def part_2_helper(): """PART TWO This simply runs the script multiple times and multiplies the results together """ slope_1 = sled_down_hill(1, 1) slope_2 = sled_down_hill(1, 3) slope_3 = sled_down_hill(1, 5) slope_4 = sled_down_hill(1, 7) slope_5 = sled_down_hill(2, 1) return slope...
31,598
def test_shuffle_each_shard(): """Test that shuffle_each_shard works.""" n_samples = 100 n_tasks = 10 n_features = 10 X = np.random.rand(n_samples, n_features) y = np.random.randint(2, size=(n_samples, n_tasks)) w = np.random.randint(2, size=(n_samples, n_tasks)) ids = np.arange(n_samples) dataset = ...
31,599