content
stringlengths
22
815k
id
int64
0
4.91M
def most_frequent_code(features, common_table, config): """ Set feature to true if code is the most common one for language name :param features: mapping from (lgname, lgcode) pair to features to values :param common_table: language table mapping name to most common code :return: none """ fo...
26,200
def scrape_data_post(userName, id, scan_list, section, elements_path, save_status, file_names, workEducation): """Given some parameters, this function can scrap friends/photos/videos/about/posts(statuses) of a profile""" page = [] folder = os.path.join(os.getcwd(), "Data") data = [] if save_status =...
26,201
def broadcast_dynamic_shape(shape_x, shape_y): """Computes the shape of a broadcast given symbolic shapes. When shape_x and shape_y are Tensors representing shapes (i.e. the result of calling tf.shape on another Tensor) this computes a Tensor which is the shape of the result of a broadcasting op applied in ten...
26,202
def extract_args_for_httpie_main(context, method=None): """Transform a Context object to a list of arguments that can be passed to HTTPie main function. """ args = _extract_httpie_options(context) if method: args.append(method.upper()) args.append(context.url) args += _extract_http...
26,203
def apply_configuration(dist: "Distribution", filepath: _Path) -> "Distribution": """Apply the configuration from a ``setup.cfg`` file into an existing distribution object. """ _apply(dist, filepath) dist._finalize_requires() return dist
26,204
def test_double_prepare_slash(db): """ This tests that the chain does not change head unless there are more commits on the alternative fork """ test_string = 'B J0 B B S0 B P0 B1 C0 B1 R0 B P0 B1 C0 B1 X0 B J1 J2 B B P1 P2 B1 C1 C2 B P1 P2 B1 C1 C2 B1' test = TestLangHybrid(test_string, 15, 100, 0.02, 0.002...
26,205
def bitbucketBaseIssue(): """ BitbucketIssueのベースとなるデータを生成して返します。 """ return { 'assignee': None, 'component': None, 'content': 'issue_summary', 'content_updated_on': '4000-01-01T00:00:00Z', 'created_on': '3000-01-01T00:00:00Z', 'edited_on': '4000-01-01T00:0...
26,206
def FindChromeCandidates(overlay_dir): """Return a tuple of chrome's unstable ebuild and stable ebuilds. Args: overlay_dir: The path to chrome's portage overlay dir. Returns: Tuple [unstable_ebuild, stable_ebuilds]. Raises: Exception: if no unstable ebuild exists for Chrome. """ stable_ebuild...
26,207
def is_hour_staffed(coverage_events_for_hour, level_mappings): """ Logic for determining if a shift is correctly staffed. The required subcalendar id determines which logic to apply coverage_events_for_hour is a list of coverage events for the hour (a list of CoverageOffered JSON objects) """ retur...
26,208
def sqliteAdminBlueprint( dbPath, bpName='sqliteAdmin', tables=[], title='标题', h1='页标题', baseLayout='flask_sqlite_admin/sqlite_base.html', extraRules=[], decorator=defaultDecorator): """ create routes for admin """ sqlite = Blueprint(bpName, __name__,template_folder='templates',static_folde...
26,209
def AccountsUrl(command): """Generates the Google Accounts URL. Args: command: The command to execute. Returns: A URL for the given command. """ return '%s/%s' % (GOOGLE_ACCOUNTS_BASE_URL, command)
26,210
def iter_input_annotation_output_df_df(inspection_index, input_df, annotation_df, output_df): """ Create an efficient iterator for the inspection input """ # pylint: disable=too-many-locals # Performance tips: # https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe...
26,211
def measure_curvatures(left_fit, right_fit, ym_per_pix=1., xm_per_pix=1., y_eval=0): """ Calculate left and right lane line curvature Args: left_fit: `numpy.ndarray` second order linear regression of left lane line right_fit: `numpy.ndarray` second order linear regression of right lane li...
26,212
def ensure_present(params, check_mode): """ Ensure that the specified Hipersockets adapter exists and has the specified properties set. Raises: ParameterError: An issue with the module parameters. Error: Other errors during processing. zhmcclient.Error: Any zhmcclient exception can ha...
26,213
def getRelation (pid, rid, out) : """ pid: parent relation id for this relation rid: crawl relation """ full_url = 'https://api.openstreetmap.org/api/0.6/relation/'+rid+'/full' xml = requests.get(full_url) # save this XML to local file. file = codecs.open('boundary/'+rid + '.xml'...
26,214
def make_viz(): """Produce visualization.""" # Set plot settings ylim = [-5, 5] gpv.update_rc_params() # Define model params gp1_hypers = {'ls': 1., 'alpha': 1.5, 'sigma': 1e-1} gp2_hypers = {'ls': 3., 'alpha': 1., 'sigma': 1e-1} # Define domain x_min = -10. x_max = 10. do...
26,215
def execute_parallel_get(og_obj_id, tar_par_loc, remove_after): """ Copy file from mounted files system to mounted system """ # TODO: download file from PARALLEL subprocess.check_output(['mpiexec', '-n', '1', '-usize', '17', 'python', 'getParallel.py', og_obj_id]) pass
26,216
def test_to_time_string_wih_datetime(berlin_datetime): """ gets the time string representation of input datetime. example: `23:40:15+00:00` :rtype: str """ time_berlin = datetime_services.to_time_string(berlin_datetime, to_server=True) assert time_berlin == '16:00:00+00:00'
26,217
def get_processed_image(username): """Gets the b64 strings of the processed images from the server and converts them to image files Args: username (tkinter.StringVar): user-specified username to identify each unique user Returns: JpegImageFile: the image file of the processed i...
26,218
def make_cse_path(raw_ticker: str, raw_industry: str) -> str: """makes slug for ticker for the cse Parameters: raw_ticker - cse ticker from xlsx sheet raw_industry - verbatim industry from ticker, not slugified Returns: description - url for cse files for download """ if pd.isna(r...
26,219
def readTMY(filepath=os.path.join("TMY", "Germany DEU Koln (INTL).csv")): """ Reads a typical meteorological year file and gets the GHI, DHI and DNI from it. """ # get data data = pd.read_csv( os.path.join(PATH, "weatherdata", filepath), skiprows=([0, 1]), sep=",", ) ...
26,220
def interface(inp, xdata, ydata): """ splits the c function output to two variables, the RMSE and the derivative of RMSE with respect to the parameters""" p = _gauss.gaussjac(xdata,ydata,inp) return p[0],p[1:]
26,221
def generateCoverText_BERT(mod, tok, startOfText, ranks, completeMessage): """ Function to get the cover text that is sent from Alice to Bob based on the ranks of the secret text """ inputs = tok.encode(startOfText, return_tensors="pt", add_special_tokens=False) for s in ranks: tab = inputs.numpy() pr...
26,222
async def _(event: GroupMessageEvent): """ “来点色图” """ msg = MessageSegment.reply(event.message_id) + '您点的一份色图~' + MessageSegment.image( f"file:///{Path(SETU_PATH + choice(os.listdir(SETU_PATH))).absolute()}") await setu.finish(msg)
26,223
def infer_from_did_elasticnet(did, debug=False): """Returns `inferred` tuple (interaction_coefficients, growth_rates) Will return info as well if debug=True""" df_geom, df_dlogydt, df_nzmask, n_species = prepare_data_for_inference(did) ####### BEGIN THE INFERENCE!!!!! ####### regs = [] interc...
26,224
def Fanstatic(app, publisher_signature=fanstatic.DEFAULT_SIGNATURE, injector=None, **config): """Fanstatic WSGI framework component. :param app: The WSGI app to wrap with Fanstatic. :param publisher_signature: Optional argument to define the signature of the...
26,225
def predicate_id(namespace, predicate, cursor=None): """ Get a RDF predicate ID, creating it if necessary. """ data = {'namespace': namespace, 'predicate': predicate} cursor = relations_reader.predicate_id(data, cursor=cursor) if not cursor.rowcount: relations_writer.upsert_predicate(da...
26,226
def _create_filter_list(user_list, request=None): """ [メソッド概要] フィルタのリストを作成する [引数] user_list :_getUserData(filters)により作成されるuser_list request :logger.logic_logでuserId sessionIDを表示するために使用する [戻り値] filter_list """ logger.logic_log('LOSI00001', 'user_list: %s' % len(user_li...
26,227
def run_script(cli_string, die=True, verbose=True): """Run the cli_string UNIX CLI command and record output. Args: cli_string: String of command to run die: Exit with error if True Returns: (returncode, stdoutdata, stderrdata): Execution code, STDOUT output and STDERR ...
26,228
def get_events() -> List[Dict]: """Represents set of sales events""" return [{ "Txid": 1, "productname": "Product 2", "qty": 2, "sales": 489.5 }, { "Txid": 2, "productname": "Product 3 XL", "qty": 2, "sales": 411.8 }, { "Txid": 3, ...
26,229
def jump_handler(s): """Handling single and double jumps""" jump = 1 if s.poG or s.ljump and not s.poG and s.fz > 0 else 0 if jump and s.ljump != s.lljump or not s.ljump: s.pitch = s.yaw = s.roll = 0 if min(0.18, s.dT + 0.05) < s.airtime and s.fz > 100: jump = not s.ljump return ...
26,230
def init(): """ Initialize the connections. Let's get it started...in here! Developer note: the advantage of putting it here is that me.py doesn't need to import anything. """ global neighborStrategy me.init(nodes.CurrentNode()) debug("Init called. Node is " + me.getUid(), info=True...
26,231
def sec2hms(sec): """ Convert seconds to hours, minutes and seconds. """ hours = int(sec/3600) minutes = int((sec -3600*hours)/60) seconds = int(sec -3600*hours -60*minutes) return hours,minutes,seconds
26,232
def EnableProfiler(enable): # real signature unknown; restored from __doc__ """ EnableProfiler(enable: bool) Enable or disable profiling for the current ScriptEngine. This will only affect code that is compiled after the setting is changed; previously-compiled code wil...
26,233
def to_english_like_sentence(sentence: str, tokenizer = tokenizers.JiebaTokenizer()): """ :param sentence: :return: """ return ' '.join(tokenizer(sentence))
26,234
def get_month_range(start_date): """ Get the start and end datetimes for the month :param start_date: period start_date :type start_date: datetime.datetime() :return: tuple start_datetime, end_datetime """ start_date = datetime(start_date.year, start_date.month, 1) end_date = utils.date...
26,235
def generate_rendition(in_path: str, out_dir: str, size: int) -> str: """ Given an image path and a size, save a rendition to disk :param str in_path: Path to the file :param str out_dir: Directory to store the file in :param int size: Rendition size: :returns: a file path """ image = gen...
26,236
def dump(curse_manifest, filelike): """ Dump a curse manifest as bytes into a file-like object (supporting write()). The encoding is utf-8 Arguments curse_manifest -- curse manifest to dump filelike -- filelike object that has a write() method """ filelike.write(json.dumps(curse...
26,237
def convert_to_rotation_fdot( gwfrequency=None, rotationfrequency=None, rotationperiod=None, gwfdot=None, rotationpdot=None, **kwargs, ): """ Convert the GW frequency (assumed to be twice the rotation frequency) or the rotation period and GW rotation frequency derivative or rotation ...
26,238
def send_block( cmd=None, section=None, item=None, identifier=None, zone=None, owner=None, ttl=None, rtype=None, data=None, flags=None, filter_=None, ): """Send block command to Libknot server control.""" ctl = connect_knot() resp = None try: ctl.sen...
26,239
def _poisson_covariance(dist, lambda0): """ Poisson covariance model on the sphere. Parameters ---------- dist: float Great circle distance. lambda0: float Lengthscale parameter. """ cov = (1 - lambda0**2) / (1 - 2*lambda0*np.cos(dist) + lambda0**2)**(3/2) return cov
26,240
def ch_mkdir(directory): """ ch_mkdir : This function creates a directory if it does not exist. Arguments: directory (string): Path to the directory. -------- Returns: null. """ if not os.path.exists(directory): try: os.makedirs(directory) exce...
26,241
def snot(N=None, target=None): """Quantum object representing the SNOT (2-qubit Hadamard) gate. Returns ------- snot_gate : qobj Quantum object representation of SNOT gate. Examples -------- >>> snot() Quantum object: dims = [[2], [2]], \ shape = [2, 2], type = oper, isHerm = T...
26,242
def _do_wrapper( func: Callable, *, responses: Dict[str, Type[BaseModel]] = None, header: Type[BaseModel] = None, cookie: Type[BaseModel] = None, path: Type[BaseModel] = None, query: Type[BaseModel] = None, form: Type[BaseModel] = None, body: Type[...
26,243
def make_divisible(v, divisor, min_val=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py """ ...
26,244
def mock_query_object(LCClient): """ Creating a Query Response object and prefilling it with some information """ # Creating a Query Response Object start = '2016/1/1' end = '2016/1/2' obj = { 'TimeRange': TimeRange(parse_time(start), parse_time(end)), 'Time_start': parse_tim...
26,245
def edit(photo_id): """ Edit uploaded photo information. :param photo_id: target photo id :return: HTML template for edit form or Json data """ if request.method == 'GET': photo = Photo.get(current_user.id, photo_id) return render_template('upload.html', photo=photo, gmaps_key=c...
26,246
def crop_only(net1, net2): """ the size(net1) <= size(net2) """ net1_shape = net1.get_shape().as_list() net2_shape = net2.get_shape().as_list() # print(net1_shape) # print(net2_shape) # if net2_shape[1] >= net1_shape[1] and net2_shape[2] >= net1_shape[2]: offsets = [0, (net2_shape[1]...
26,247
def test_load_missing_key(engine): """Trying to load objects with missing hash and range keys raises""" user = User(age=2) with pytest.raises(MissingKey): engine.load(user) complex_models = [ ComplexModel(), ComplexModel(name=uuid.uuid4()), ComplexModel(date="no hash") ...
26,248
def normalize(image): """ Normalize to 0-255, dtype: np.uint8 """ if np.min(image) < 0: image = image - np.min(image) if np.max(image) != 0: image = image / np.max(image) image = image * 255 image = np.uint8(image) return image
26,249
def temp_file(contents, suffix=''): """Create a self-deleting temp file with the given content""" tmpdir = get_test_tmpdir() t = tempfile.NamedTemporaryFile(suffix=suffix, dir=tmpdir) t.write(contents) t.flush() return t
26,250
def string_to_charlist(string): """Return a list of characters with extra empty strings after wide chars""" if not set(string) - ASCIIONLY: return list(string) result = [] if PY3: for c in string: result.append(c) if east_asian_width(c) in WIDE_SYMBOLS: ...
26,251
def test_bad_pipeline_param_error(): """ Should return error if pipeline parameter is not valid. """ runner = CliRunner() result = runner.invoke(maggport.maggport, [ '--host', 'test_host', '--collection', 'test_collection', '--db', 'test_db', '--port', '8080', ...
26,252
def urlparams(url_, hash=None, **query): """Add a fragment and/or query paramaters to a URL. New query params will be appended to exising parameters, except duplicate names, which will be replaced. """ url = urlparse.urlparse(url_) fragment = hash if hash is not None else url.fragment # Us...
26,253
def get(word, cache=True): """ Load the word 'word' and return the DudenWord instance """ html_content = request_word(word, cache=cache) # pylint: disable=unexpected-keyword-arg if html_content is None: return None soup = bs4.BeautifulSoup(html_content, 'html.parser') return DudenW...
26,254
def cubespace(start, stop=False, num=10, include_start=True): """ Return sequence of *num* floats between *start* and *stop*. Analogously to numpy's linspace, values in returned list are chosen so that their cubes (hence name) are spread evenly in equal distance. If the parameter *stop* is not give...
26,255
def to_ndarray(arr): """ Convert a list of lists to a multidimensional numpy array @param arr: @return: """ return np.array([np.array(x) for x in arr])
26,256
def spectre_avatar(avatar, size="sm", **kwargs): """ render avatar :param avatar: :param size: :param kwargs: :return: HTML """ avatar_kwargs = kwargs.copy() avatar_kwargs['avatar_url'] = avatar avatar_kwargs['size'] = size if "background" not in avatar_kwargs.keys(): ...
26,257
def update_models(scouseobject, key, models, selection): """ Here we update the model selection based on the users instructions """ spectrum = scouseobject.indiv_dict[key] if np.size(selection) == 0.0: # If no selection is made - refit manually # Make pyspeckit be quiet with...
26,258
def get_modules_by_appid(app_id): """ 查询业务下的所有模块信息 注意:企业版使用get_modules_by_property代替 """ cc_data = bk.cc.get_modules_by_property(app_id=app_id) return cc_data
26,259
def length(time_array, voltage_array): """This function checks if the time and voltage arrays are of equal lengths. The first two lines in the function determine the length of the time and voltage arrays, respectively. The if statement checks to see if they are unequal, if so, it raises and excepti...
26,260
def get_bed_from_nx_graph( graph, bed_file, interval_key="active", merge=True, return_key="region"): """get BED file from nx examples """ if isinstance(graph.graph["examples"], basestring): graph.graph["examples"] = graph.graph["examples"].split(",") examp...
26,261
def do_json_counts(df, target_name): """ count of records where name=target_name in a dataframe with column 'name' """ return df.filter(df.name == target_name).count()
26,262
def is_a(file_name): """ Tests whether a given file_name corresponds to a ICEYE file. Returns a reader instance, if so. Parameters ---------- file_name : str|BinaryIO the file_name to check Returns ------- CSKReader|None `CSKReader` instance if Cosmo Skymed file, `None`...
26,263
def exclusiveFields(obj, fields=[]): """ Validates that obj has fields only from specified list """ for k in obj.keys(): assert k in fields, k+':invalid'
26,264
def split_graph(infile, outdir, k_outdirs=None, num_outputs=None, seedfile=None, dagfile=None): """ Load the dependency graph from infile and split it into num_outputs. """ if infile.endswith('.tgz'): # there is only one file in the tarball archive tmp_graph = tarfile.open(infile, "r:gz"...
26,265
def fetch_optimizer(args, model): """ Create the optimizer and learning rate scheduler """ optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wdecay, eps=args.epsilon) scheduler = optim.lr_scheduler.OneCycleLR(optimizer=optimizer, max_lr=args.lr, total_steps=args.num_steps+100, ...
26,266
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings, freeze_bert, finetune_module, num_train_examples): """Returns `model_fn` closure for TPUEstimator.""" ...
26,267
def var_dump(*obs): """ shows structured information of a object, list, tuple etc """ i = 0 for x in obs: dump(x, 0, i, '', object, True) i += 1
26,268
def logout(odj: ODI) -> None: """Logout from ODI and remove the local cache.""" from odi.cli.command import implement_logout implement_logout()
26,269
def load_series_spectrum_df(series_dict_channels): """ Takes a series of dictionaries generated by pd.Series.apply(load_channels) and returns a dataframe with the frequencies expanded as columns. If the frequencies are not identically overlapping across rows, the resulting set of columns will the t...
26,270
def compare_balloon_states(b1: balloon.BalloonState, b2: balloon.BalloonState, check_not_equal: Sequence[str] = ()): """Function for comparing balloon states. Args: b1: First BalloonState. b2: Second BalloonState. check_not_equal: A sequence of stri...
26,271
def get_mujoco_features_dict( builder_config: BuilderConfig, ds_config: DatasetConfig) -> Dict[str, tfds.features.FeatureConnector]: """Builds the features dict of a Mujoco dataset. Args: builder_config: builder config of the Mujoco dataset. ds_config: config of the Mujoco dataset containing the sp...
26,272
def copy_and_extract_documents(agency_directory, d): """ Extract text from documents, and return a tuple contain documentation details and the extracted text. """ date_dir = os.path.join(agency_directory, d) manifest_path = os.path.join(date_dir, 'manifest.yml') manifest = yaml.load(open(manifest_p...
26,273
def weighted_cross_entropy(y_true, y_pred): """ Weighted cross entropy loss :param y_true: Ground truth :param y_pred: Prediction :return: Loss value between y_true and y_pred """ try: [seg, weight] = tf.unstack(y_true, 2, axis=3) seg = tf.expand_dims(seg, -1) weigh...
26,274
def get_config(custom_path=None): """ Get config file and load it with yaml :returns: loaded config in yaml, as a dict object """ if custom_path: config_path = custom_path else: for d in CONFIG_DIRS: config_path = os.path.join(d, CONFIG_FILENAME) if os.pa...
26,275
def union(a, b): """Find union of two lists, sequences, etc. Returns a list that includes repetitions if they occur in the input lists. """ return list(a) + list(b)
26,276
def update_intervals(M, s, B): """ After found the s value, compute the new list of intervals """ M_new = [] for a, b in M: r_lower = ceil(a * s - 3 * B + 1, n) r_upper = ceil(b * s - 2 * B, n) for r in range(r_lower, r_upper): lower_bound = max(a, ...
26,277
def mixer_l16_224_in21k(pretrained=False, **kwargs): """ Mixer-L/16 224x224. ImageNet-21k pretrained weights. Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601 """ model_args = dict(patch_size=16, num_blocks=24, embed_dim=1024, **kwargs) model = _create_...
26,278
def compileInterpolatableTTFs(ufos, preProcessorClass=TTFInterpolatablePreProcessor, outlineCompilerClass=OutlineTTFCompiler, featureCompilerClass=FeatureCompiler, featureWriters=None, ...
26,279
def autofill(blf_dict: dict, user_dict: dict): """Accepts a dictonary of BLFs and a dictionary of users. Where there is partial information (empty extension numbers or empty names) in the BLF dictionary, this function will look in the user dictionary for matching info it can use to fill in. """ ...
26,280
def isoslice(var, iso_values, grid=None, iso_array=None, axis="Z"): """Interpolate var to iso_values. This wraps `xgcm` `transform` function for slice interpolation, though `transform` has additional functionality. Inputs ------ var: DataArray Variable to operate on. iso_values: li...
26,281
def game_stats(history): """ displays statistics for current session of the game :param history: """ lost_games = history["loss"] won_games = history["won"] total_games = won_games + lost_games print("total no of games played are:", total_games) # displays total number of games played ...
26,282
def user_prompt(msg: str, sound: bool = False, timeout: int = -1): """Open user prompt.""" return f'B;UserPrompt("{msg}",{sound:d},{timeout});'.encode()
26,283
def ComputeWk(X, labels, classes): """ X - (d x n) data matrix, where n is samples and d is dimentionality lables - n dimentional vector which are class labels """ Wk = 0 for i in range(classes): mask = (labels == i) Wk = Wk + np.sum(np.sum((X[:, mask] - np.mean(X[:, mas...
26,284
def vad_split(audio, rate, frame_duration, aggressiveness=1): """Splits the audio into audio segments on non-speech frames. params: audio: A numpy ndarray, which has 1 dimension and values within -1.0 to 1.0 (inclusive) rate: An integer, which is the rate at which samples are take...
26,285
def is_extant_string(string): """Check if the string exists in the database""" return HyperlinkModel.objects.filter(internal=string).exists()
26,286
def time_to_convergence(T,P0,final_beliefs=False,tolerance=0,max_iter=10000): """ This function calculates the number of periods that it takes for opinions to stop changing in the DeGroot Model. Optionally, one can also get the final belief profile. """ T = np.asarray(T) P0 = np.transpose(np.asa...
26,287
def sound_settings_function(): """Function called when the player enter the sound settings. It allows the player to navigate trough the music and the sounds to mute them or play them. We have to repeat this instructions in diferent parts of the game.""" if event.key == K_LEFT: if soundSettings.s...
26,288
def count_subset_sum_recur(arr, total, n): """Count subsets given sum by recusrion. Time complexity: O(2^n), where n is length of array. Space complexity: O(1). """ if total < 0: return 0 if total == 0: return 1 if n < 0: return 0 if total < arr[n]: ret...
26,289
def monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week whi...
26,290
def Contap_HCurve2dTool_Bezier(*args): """ :param C: :type C: Handle_Adaptor2d_HCurve2d & :rtype: Handle_Geom2d_BezierCurve """ return _Contap.Contap_HCurve2dTool_Bezier(*args)
26,291
def api_view_issue(repo, issueid, username=None, namespace=None): """ Issue information ----------------- Retrieve information of a specific issue. :: GET /api/0/<repo>/issue/<issue id> GET /api/0/<namespace>/<repo>/issue/<issue id> :: GET /api/0/fork/<username>/<repo...
26,292
def mktest(): """Create testsuite. """ if changed('tests'): os.chdir('tests') run("python ../dktest/mktest.py")
26,293
def mcc_class_loss( predictions: torch.tensor, targets: torch.tensor, data_weights: torch.tensor, mask: torch.tensor, ) -> torch.tensor: """ A classification loss using a soft version of the Matthews Correlation Coefficient. :param predictions: Model predictions with shape(batch_size, tasks...
26,294
def inverse(fun, value): """Calculate argument of f given its value""" epsilon = 1e-09 start = middle = 1e-09 end = 1e9 while abs(end - start) > epsilon: middle = (start + end) / 2 if isclose(fun(middle) - value, 0.0): break elif fun(middle) - value > 0 and fun(st...
26,295
def run_architecture_validator_test( mocker, config, constrained_param_section, constrained_param_name, param_name, param_val, validator, expected_warnings, expected_errors, ): """Run a test for a validator that's concerned with the architecture param.""" mocked_pcluster_conf...
26,296
def get_test_files(dirname): """ Gets a list of files in directory specified by name. """ if not os.path.isdir(dirname): return [] path = dirname + "/{}" return list(map(path.format, sorted(os.listdir(dirname))))
26,297
def test_index_references_are_valid(repo): """ demonstrate that all keys in the index reference valid TOC entries in data pages. this means: - all pages exist - all IDs exist - the reported size equals the allocated size Args: repo (cim.CIM): the deleted-instance repo ...
26,298
def setup(verbose, cpu, memory, update): """ Uses Terraform to create a full Numerai Compute cluster in AWS. Prompts for your AWS and Numerai API keys on first run, caches them in $HOME/.numerai. Will output two important URLs at the end of running: - submission_url: The webhook url you will ...
26,299