content
stringlengths
22
815k
id
int64
0
4.91M
def create_user(weixin_id, sno, password): """ :param weixin_id: string :param sno: string for student number :param password: string :return: void """ file_name = 'user/{}.txt'.format(weixin_id) data = '{}#{}'.format(sno, password) with open(file_name, mode='w') as f: f.wri...
5,323,500
def _get_interface_name_index(dbapi, host): """ Builds a dictionary of interfaces indexed by interface name. """ interfaces = {} for iface in dbapi.iinterface_get_by_ihost(host.id): interfaces[iface.ifname] = iface return interfaces
5,323,501
def generate_data(shape, num_seed_layers=3, avg_bkg_tracks=3, noise_prob=0.01, verbose=True, seed=1234): """ Top level function to generate a dataset. Returns arrays (events, sig_tracks, sig_params) """ np.random.seed(seed) num_event, num_det_layers, det_layer_size, _ = shape ...
5,323,502
def create_project( root: xml.etree.ElementTree.Element, include: List[str], exclude: Optional[List[str]] = None ) -> Tuple[List[str], List[str], List[pathlib.Path], List[pathlib.Path], List[pathlib.Path], List[pathlib.Path]]: """Create a project from a list of specified components. Args...
5,323,503
def to_data(x): """Converts variable to numpy""" if torch.cuda.is_available(): x = x.cpu() return x.data.numpy()
5,323,504
def levmar_bc(func, p0, y, bc, args=(), jacf=None, mu=1.0e-03, eps1=1.5e-08, eps2=1.5e-08, eps3=1.5e-08, maxit=1000, cdiff=False): """ Parameters ---------- func: callable Function or method computing the model function, `y = func(p, *args)`. p0: array_like, shape...
5,323,505
def set_name_filter(request): """ Sets product filters given by passed request. """ product_filters = request.session.get("product_filters", {}) if request.POST.get("name", "") != "": product_filters["product_name"] = request.POST.get("name") else: if product_filters.get("produc...
5,323,506
def get_arguments(): """ Wrapper function to get the command line arguments. Inserting this piece of code into its own function for conda compatibility. """ parser = argparse.ArgumentParser( prog='KrakMeOpen', usage='krakmeopen [--input FILE | --input_pickle FILE | --input_file_list...
5,323,507
def select( da, longitude=None, latitude=None, T=None, Z=None, iT=None, iZ=None, extrap=False, extrap_val=None, locstream=False, ): """Extract output from da at location(s). Parameters ---------- da: DataArray Property to take gradients of. longitude,...
5,323,508
def afsluitmiddel_regelbaarheid(damo_gdf=None, obj=None): """" Zet naam van AFSLUITREGELBAARHEID om naar attribuutwaarde """ data = [_afsluitmiddel_regelbaarheid(name) for name in damo_gdf['SOORTREGELBAARHEID']] df = pd.Series(data=data, index=damo_gdf.index) return df
5,323,509
def generate(i): """ Input: { (output_txt_file) - if !='', generate text file for a given conference (conf_id) - record names for this conf } Output: { return - return code = 0, if successful > 0...
5,323,510
def chdir(dest): """Chdir into the given directory within a context.""" cwd = os.getcwd() os.chdir(dest) try: yield finally: os.chdir(cwd)
5,323,511
def calc_solidangle_particle( pts=None, part_traj=None, part_radius=None, config=None, approx=None, aniso=None, block=None, ): """ Compute the solid angle subtended by a particle along a trajectory The particle has radius r, and trajectory (array of points) traj It is observed f...
5,323,512
def fields_view(arr, fieldNameLst=None): """ Return a view of a numpy record array containing only the fields names in the fields argument. 'fields' should be a list of column names. """ # Default to all fields if not fieldNameLst: fieldNameLst = arr.dtype.names dtype2 = np.dtyp...
5,323,513
def aggregate_values(infiles, outfile, col_index, header=None): """ Output one specific column from a list of files as one file. :param infiles: list of CSV files from which to obtain columns :param outfile: path to output file :param col_index: column index to take :param header: optional header to...
5,323,514
def initialize_servers_and_threads(): """ Returns a dictionary object containing an initialized server and thread object for each email """ servers_and_threads = {} for email in os.listdir(".emails"): server = classes.server.Server(email) servers_and_threads[email] = {"Server": server, "Thread": classes.server...
5,323,515
def image_detach_with_id_color_list( color_img: np.ndarray, id_color_list: List[Tuple[int, Tuple[int, int, int]]], bin_num: int, mask_value: float = 1.0, ) -> np.ndarray: """ 컬러 이미지 `color_img`를 색상에 따른 각 인스턴스 객체로 분리합니다. Parameters ---------- color_img : np.ndarray 컬러 이미지 ...
5,323,516
def defaultArgs(options: Dict = None, **kwargs: Any) -> List[str]: # noqa: C901,E501 """Get the default flags the chromium will be launched with. ``options`` or keyword arguments are set of configurable options to set on the browser. Can have the following fields: * ``headless`` (bool): Whether to ru...
5,323,517
def insertionsort(A): """In-place insertion sort.""" for i in range(1, len(A)): j = i while j > 0 and A[j] < A[j - 1]: swap(A, j, j - 1) j -= 1 yield A
5,323,518
def process_v3_fields(fields: List[str], endpoint: str) -> str: """ Filter v3 field list to only include valid fields for a given endpoint. Logs a warning when fields get filtered out. """ valid_fields = [field for field in fields if field in FIELDS_V3] if len(valid_fields) < len(fields): ...
5,323,519
def getManifestFsLayers(manifest): """ returns hashes pointing to layers for manifest""" return manifest["manifest"]["fsLayers"]
5,323,520
def Jones_METIS(c, tau, w, q): """ Returns Jones polynomial evaluated at t(q) via METIS contraction of the tensor network of the knot encoded in edgelist c. w is the writhe of the knot. """ nc = len(c) # number of crossings if nc > 0: nv = cnf_nvar(c) ekpotts = -tpotts(q) ...
5,323,521
def cli(cxn): """ get report of stocks """ click.echo("Done")
5,323,522
def screen_name_filter(tweet_list, stoplist): """ Filter list of tweets by screen_names in stoplist. Pulls original tweets out of retweets. stoplist may be a list of usernames, or a string name of a configured named stoplist. """ tweets = [] id_set = set() if isinstance(stoplist, ba...
5,323,523
def insert_into(table_name, values, column_names, create_if_not_exists=False, inspect=True, engine=None): """ Inserts a list of values into an existing table :param table_name: the name of the table into which to insert records :param values: a list of lists containing literal values to insert into the...
5,323,524
def set_up_bq(): """Set up BQ datasets and tables.""" try: Client("measures").create_dataset() except Conflict: pass client = Client("hscic") client.get_or_create_table("ccgs", schemas.CCG_SCHEMA) client.get_or_create_table("practices", schemas.PRACTICE_SCHEMA) client.get_o...
5,323,525
def delchars(str, chars): """Returns a string for which all occurrences of characters in chars have been removed.""" # Translate demands a mapping string of 256 characters; # whip up a string that will leave all characters unmolested. identity = "".join([chr(x) for x in range(256)]) return str...
5,323,526
def normalize_typed_substitution( value: SomeValueType, data_type: Optional[AllowedTypesType] ) -> NormalizedValueType: """ Normalize a mix of substitution and values. This function becomes handy when you need a substitution whose result will be coerced to a specific type. Example: -------...
5,323,527
def index(request): """ View for the static index page """ return render(request, 'public/home.html', _get_context('Home'))
5,323,528
def merge(arr, left, middle, right): """C/C++ 思维编码""" result = [0] * (right - left + 1) i, j, k = left, middle + 1, 0 while i <= middle and j <= right: if arr[i] <= arr[j]: result[k] = arr[i] i += 1 else: result[k] = arr[j] j += 1 k += 1 while i <= middle: result[k] = arr[i] i += 1 k += 1 ...
5,323,529
def bytes2hex(bytes_array): """ Converts byte array (output of ``pickle.dumps()``) to spaced hexadecimal string representation. Parameters ---------- bytes_array: bytes Array of bytes to be converted. Returns ------- str Hexadecimal representation of the byte array. ...
5,323,530
def test_tracker_binom(): """Test TrackerBinom""" tr = TrackerBinom(callback, 0.05, 0.1, 5) with ExperimentController('test', **std_kwargs) as ec: tr = TrackerBinom(ec, 0.05, 0.1, 5) tr = TrackerBinom(None, 0.05, 0.5, 2, stop_early=False) while not tr.stopped: tr.respond(False) a...
5,323,531
def atan2(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arctan2 <numpy.arctan2>`. See its docstring for more information. """ if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allow...
5,323,532
def multidim_str_putcolslice(row_runs, blc, trc, table_future, column, data): """ Put multidimensional string data into the table """ table = table_future.result() putcol = table.putcol rr = 0 table.lock(write=True) try: for rs, rl in row_runs: # Construct a dict with the s...
5,323,533
def family_directory(fonts): """Get the path of font project directory.""" if fonts: dirname = os.path.dirname(fonts[0]) if dirname == '': dirname = '.' return dirname
5,323,534
def authorizer(*args, **kwargs): """ decorator to register an authorizer. :param object args: authorizer class constructor arguments. :param object kwargs: authorizer class constructor keyword arguments. :keyword bool replace: specifies that if there is another registered ...
5,323,535
def option_getter(config_model): """Returns a get_option() function using the given config_model and data""" def get_option(option, x=None, default=None, ignore_inheritance=False): def _get_option(opt, fail=False): try: result = config_model.get_key('techs.' + opt) ...
5,323,536
def is_core_dump(file_path): """ Determine whether given file is a core file. Works on CentOS and Ubuntu. Args: file_path: full path to a possible core file """ file_std_out = exec_local_command("file %s" % file_path) return "core file" in file_std_out and 'ELF' in file_std_out
5,323,537
def to_posix(d): """Convert the Path objects to string.""" if isinstance(d, dict): for k, v in d.items(): d[k] = to_posix(v) elif isinstance(d, list): return [to_posix(x) for x in d] elif isinstance(d, Path): return d.as_posix() return d
5,323,538
def lc_concatenate_worker(task): """ This is the parallel worker for the function below. task is a tuple: task[0] = base LC file task[1] = new LC file to be concatenated to base task[2] = zero-indexed column number to use to sort resulting LC (if None, then no sorting is done) ...
5,323,539
def use_diff(on=True): """ Reduces size of pickles by only including object which have changed. Decreases pickle size but increases CPU time needed. Also helps avoid some unpicklable objects. MUST be called at start of script, otherwise changes will not be recorded. """ global _use_diff, di...
5,323,540
def generate_barset_forever(): """ This function generates barsets for all symbols provided in the csv file :return: None """ p_auth = "Zay2cQZwZfUTozLiLmyprY4Sr3uK27Vp" from trade_backend.trader import CustomTimeZone while True: # Exit this thread when main thread is not alive ...
5,323,541
def mouseMotion( x, y ): """Callback function (mouse moved while button is pressed). The current and old mouse positions are stored in a global renderParam and a global list respectively. The global translation vector is updated according to the movement of the mouse pointer.""" global rP, oldMousePos deltaX =...
5,323,542
def list_entities(currency, ids=None, page=None, pagesize=None): # noqa: E501 """Get entities # noqa: E501 :param currency: The cryptocurrency (e.g., btc) :type currency: str :param ids: Restrict result to given set of comma separated IDs :type ids: List[str] :param page: Resumption toke...
5,323,543
def sensor(request): """HTTP/GET /sensor コール時の処理 ADC以外のセンサー値を読んで返す Args: request (QueryDict): リクエストパラメータ Returns: dict: クライアントに返すjson形式の値 """ params = request.GET.copy() api_response = ApiResponse() params["ids"] = params.getlist("ids") parse = ParseApiParams(param...
5,323,544
def display_instances(image, boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), ax=None, show_mask=True, show_bbox=True, colors=None, captions=None): """ boxes: [num_instance, (y1, x1, y2, x2, cla...
5,323,545
def stat(lst): """Calculate mean and std deviation from the input list.""" n = float(len(lst)) mean = sum(lst) / n stdev = sqrt((sum(x * x for x in lst) / n) - (mean * mean)) return mean, stdev
5,323,546
def _recursive_generic_validator(typed): """Recursively assembles the validators for nested generic types Walks through the nested type structure and determines whether to recurse all the way to a base type. Once it hits the base type it bubbles up the correct validator that is nested within the upper vali...
5,323,547
def main(): """ main entry point of game """ global FPSCLOCK, DISPLAYSURF pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) mousex = 0 mousey = 0 pygame.display.set_caption("Memory Puzzle") main_board = get_rando...
5,323,548
def add_to_PYTHONPATH(path): """ Add a path to the python path, only if it isn't present in the python path. Args: path (str): The path to add to the python path. """ if not path: return if not path in sys.path: sys.path.append(path)
5,323,549
def getAllFilesOfExtension(rootDir, extension): """Traverse a directory tree and find all the files with a specified extension Args: rootDir: The directory to traverse extension: The extension Returns: A list of files """ fileList = [] for (dirPath, dirNames, fil...
5,323,550
def get_posts(di, po, syn): """ Gets the postings list for each unique token in the query """ words = {} #goes through each token in the query and returns its postings list for i in range(len(syn)): word = syn[i][0] #goes through each synonym for each word ...
5,323,551
def need_food(board, bad_positions, snake): """ Determines if we need food and returns potential food that we can get """ potential_food = [] # food that is not contested (we are the closest) safe_food = [fud for fud in board.food if board.get_cell(fud) != SPOILED] # always go for safe food even i...
5,323,552
def categoriesJSON(): """Return JSON for all the categories""" categorys = session.query(Category).all() return jsonify(categories=[c.serialize for c in categorys])
5,323,553
def rescale_column(img, gt_bboxes, gt_label, gt_num, img_shape): """rescale operation for image""" img_data, scale_factor = rescale_with_tuple(img, (config.img_width, config.img_height)) if img_data.shape[0] > config.img_height: img_data, scale_factor2 = rescale_with_tuple(img_data, (config.img_heig...
5,323,554
def ausc_trapazoidal(mean_df, doses): """Performs numerical integration using the trapazoidal rule to determine the area under the survival curve (AUSC) for the drug respose. The only argument, mean_df, is a data frame made from make_mean_std(). """ y = mean_df.normalized_mean x = doses ...
5,323,555
def _get_file_handler(name): """ Создание файлового хандлера. Ротация 5 файлов по 50 мегабайт. """ file_obj = RotatingFileHandler(os.path.join(_path, name + ".log"), maxBytes = 50000000, backupCount = 5) file_obj.setLevel("TRACE") return file_obj
5,323,556
def create_schemas_for_rebuild(schemas: Sequence[DataWarehouseSchema], use_staging: bool, dry_run=False) -> None: """ Create schemas necessary for a full rebuild of data warehouse. If `use_staging`, only create new staging schemas. Otherwise, move standard position schemas out of the way by renaming th...
5,323,557
def _initialize_optimizer_vars(model, optimizer): """Ensures variables holding the state of `optimizer` are created.""" delta = tf.nest.map_structure(tf.zeros_like, _get_weights(model).trainable) model_weights = _get_weights(model) grads_and_vars = tf.nest.map_structure(lambda x, v: (x, v), delta, ...
5,323,558
def run(command, run_in='host'): """ Runs a command in the shell. Useful for sequences like wget a dataset, then unzip to another directory. You can just put the command in a yml file and call it here. You can run a sequence of commands easily by putting them one after the other in a .yml file and c...
5,323,559
def psu_info_table(psu_name): """ :param: psu_name: psu name :return: psu info entry for this psu """ return "PSU_INFO" + TABLE_NAME_SEPARATOR_VBAR + psu_name
5,323,560
def delete_rds(rds_client, rds_instances) -> list: """Deletes all instances in the instances parameter. Args: rds_client: A RDS boto3 client. rds_instances: A list of instances you want deleted. Returns: A count of deleted instances """ terminated_instances = [] for ins...
5,323,561
def all_preferences(candidates, concentrate=False): """ Generates all possible preferences given a list of candidates """ permutations_tuple = list(itertools.permutations(candidates)) permutations_list = list(map(list, list(permutations_tuple))) if concentrate: return convert_condensed(p...
5,323,562
def div_reg(net, data, ref): """ Regulize the second term of the loss function """ mean_f = net(data).mean() log_mean_ef_ref = torch.logsumexp(net(ref), 0) - np.log(ref.shape[0]) return mean_f - log_mean_ef_ref - log_mean_ef_ref**2
5,323,563
def test_image_resize(): """Test we resize the image into three new images""" # First remove all but the original image images_path = Path(__file__).parent.joinpath("fixtures") test_image = images_path.joinpath("xfer-original.jpg") files = images_path.glob("*") for f in files: if not f....
5,323,564
def action_list(): """ Prints all the available actions present in this file. """ rospy.loginfo(color.BOLD + color.PURPLE + '|-------------------|' + color.END) rospy.loginfo(color.BOLD + color.PURPLE + '| AVAILABLE ACTIONS |' + color.END) rospy.loginfo(color.BOLD + color.PURPLE + '| 1: MOVE TO POINT ...
5,323,565
def firstLetterCipher(ciphertext): """ Returns the first letters of each word in the ciphertext Example: Cipher Text: Horses evertime look positive Decoded text: Help """ return "".join([i[0] for i in ciphertext.split(" ")])
5,323,566
def polar_decode(N, K, P0): """ Decode a (N, K) polar code. P0 must be 1-normalized probabilities """ n = np.log2(N).astype(int) A = polar_hpw(N)[-K:] # We're not using all the elements in the P array, as each layer lamb # only uses 2**(n-lamb) elements. Given the current indexing it's ...
5,323,567
def parse_samtools_flagstat(p: Path) -> Tuple[int, int]: """Parse total and mapped number of reads from Samtools flagstat file""" total = 0 mapped = 0 with open(p) as fh: for line in fh: m = re.match(r'(\d+)', line) if m: if 'in total' in line: ...
5,323,568
def main(train_path, test_path, output_path): """ 读取数据集进行训练和测试 """ filename = train_path # 训练集和测试集的划分比例 splitRatio = 0.67 dataset = loadCsv(filename) trainData, testData = splitDataset(dataset, splitRatio) bayes = Bayes(trainData) model = bayes.tarin_bayesModel() ...
5,323,569
def create_tar_in_memory(files): """ Construct a tar file in-memory. :param files: Sequence of (path, data) tuples. :type files: list :return: Tar file. :rtype: File-like object. """ output = io.BytesIO() with tarfile.open(fileobj=output, mode='w') as tarf: def add_...
5,323,570
def get_country(country_id=None, incomelevel=None, lendingtype=None, cache=True): """ Retrieve information on a country or regional aggregate. Can specify either country_id, or the aggregates, but not both :country_id: a country id or sequence thereof. None returns all countries and aggregates...
5,323,571
def _PmapWalkARMLevel2(tte, vaddr, verbose_level = vSCRIPT): """ Pmap walk the level 2 tte. params: tte - value object vaddr - int returns: str - description of the tte + additional informaiton based on verbose_level """ pte_base = kern.PhysToKernelVirt(tte & 0xFFFFFC00) ...
5,323,572
def set_Coords(self, Coords): """ Set coordinate polygon by given :py:class:`CoordsType` object. Moreover, invalidate self's ``pc:AlternativeImage``s (because they will have been cropped with a bbox of the previous polygon). """ if hasattr(self, 'invalidate_AlternativeImage'): # Regi...
5,323,573
def create_new_track(unassigned_detections): """ Creates new KF instance for every unassigned detection """ for k in range(len(unassigned_detections)): kf_obj = KF(k, _boxes_rot, unassigned_detections) tracks.create_entry_with_kf(kf_obj)
5,323,574
def mel_spectrogram_feature(wav, hparams=None): """ Derives a mel spectrogram ready to be used by the encoder from a preprocessed audio waveform. Note: this not a log-mel spectrogram. """ hparams = hparams or default_hparams frames = librosa.feature.melspectrogram( wav, hparams.s...
5,323,575
def test_read_given_two_disks(): """ Test if given two disks, it creates list of Disks. """ disks = Reader.read(make_buffer('<disks><disk/><disk/></disks>')) assert_true(isinstance(disks, list)) assert_equals(len(disks), 2) assert_true(isinstance(disks[0], types.Disk)) assert_true(isinst...
5,323,576
def config_activated() : """ Tests if config is enabled """ result = CONFIG_TOOLS.list_recorders() is_enabled = False for recorder in result : if recorder['recordingGroup']['allSupported'] and \ recorder['recordingGroup']['includeGlobalResourceTypes'] : is_enabled =...
5,323,577
def file(url, dest): """Download file. Args: url (str): URL where the file is located. dest (str): Where to download the file to on this system. """ agent = "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11" try: request = urllib.request.Request(url, headers=...
5,323,578
def getRdkitAtomXYZbyId(rdkitMol,atomId, confId=0): """Returns an xyz atom position given atom's id.""" conf = rdkitMol.GetConformer(confId) return np.array(list(conf.GetAtomPosition(atomId)))
5,323,579
def test_read_crux_peptide_pairing(mod_target_crux_txt, mod_decoy_crux_txt): """Test that peptide pairing is correctly created when parsing crux files""" expected_peptide_pairing = { "ALLSLR": "ALLLSR", "QTPPAR": "QTAPPR", "GEVPN[0.98]R": "GN[0.98]PEVR", "GGHMDR": "GDMGHR", }...
5,323,580
def wavelength_soln(arc, slit_edges, im_index=1 ,): """ Get wavelength solution from arc file""" with fits.open(arc) as HDUList: img, hdr = HDUList[im_index].data, HDUList[im_index].header for n in hdr: print(n) slit_edge = slit_edges[im_index] print(slit_edge) # Trim off exc...
5,323,581
def update2MNPR(): """ Updates older versions """ if mnpr_system.refreshShaders(): # delete old config node if cmds.objExists("watercolorConfig"): if not cmds.ls(sl=True): cmds.error("Please select all objects you wish to upgrade to work with MNPR") ...
5,323,582
def _mn_minos_ ( self , *args ) : """Get MINOS errors for parameter: >>> m = ... # TMinuit object >>> result = m.minos( 1 , 2 ) """ ipars = [] for i in args : if not i in self : raise IndexError ipars.append ( i ) return _mn_exec_ ( self , 'MINOS' , 200 , *...
5,323,583
def gen_primes(): """Generate an infinite sequence of prime numbers.""" # Maps composites to primes witnessing their compositeness. # This is memory efficient, as the sieve is not "run forward" # indefinitely, but only as long as required by the current # number being tested. # D = {} #...
5,323,584
def test_commit_ctagline(app, test_client, db_posts, user): """test to commit translate result""" cowork_commit(app, test_client, db_posts, user, 'ctagline')
5,323,585
def app_files(proj_name): """Create a list with the project files Args: proj_name (str): the name of the project, where the code will be hosted Returns: files_list (list): list containing the file structure of the app """ files_list = [ "README.md", "setup.py", ...
5,323,586
def periodic_name(userword): """Generate a sequence of periodic elements from a word or sentence.""" # split up into individual words sentence = userword.split() output = [] # match each word with the periodic system for word in sentence: sequencer = ElementalWord(word) basescore...
5,323,587
def presentationRequestApiCallback(): """ This method is called by the VC Request API when the user scans a QR code and presents a Verifiable Credential to the service """ presentationResponse = request.json print(presentationResponse) if request.headers['api-key'] != apiKey: print("api-key wron...
5,323,588
def edit_issue(details): """Edit issue with the id given in details dict""" if "id" in details: issue = get_issue(details["id"]) with issueLock: issue.details["priority"] = details.get("priority", issue.details["priority"]) issue.details["issueName"] = details.get("issue...
5,323,589
def make_permalinks_py_file(): """ This function creates a file in the current working directory which creates a dictionary of available representation types and callable functions. """ file_dir = os.getcwd() file_name = "permalinks.py" file_path = file_dir + "/" + file_name data = creat...
5,323,590
def process_table(data: document.TableNode, caption: str) -> NoEscape: """ Returns a Latex formatted Table Item, wrapped with a NoEscape Command """ rows = [ tuple( " ".join(process(c) for c in table_cell["children"]) for table_cell in table_row["children"] ) ...
5,323,591
def register_span_prediction_head( model, args, name, num_classes=None, inner_dim=None, **kwargs, ): """Register a span prediction head for a RobertaModel.""" if name in model.classification_heads: prev_num_classes = model.classification_heads[ name].out_proj.out_feat...
5,323,592
def getTracksForArtist(artistName, tracks = None): """ Return a Track object for each track found with the specified artistName. """ tracksToSearch = tracks or getTracks() return filter(lambda x:x.artist == artistName, tracksToSearch)
5,323,593
def log_safe(x): """The same as torch.log(x), but clamps the input to prevent NaNs.""" x = torch.as_tensor(x) return torch.log(torch.min(x, torch.tensor(33e37).to(x)))
5,323,594
def join_transaction( session, initial_state=STATUS_ACTIVE, transaction_manager=zope_transaction.manager, keep_session=False, ): """Join a session to a transaction using the appropriate datamanager. It is safe to call this multiple times, if the session is already joined then it just return...
5,323,595
def index(request): """Redirect to the index page.""" context = {'form': LoginForm() } return render(request, 'index.htm', context)
5,323,596
def summarize_chrom_classif_by_sample(psd_list, sample_list): """ Summarize chromosome classification by sample Inputs: psd_list: list of SamplePSD AFTER calc_chrom_props() has been run sample_list: list of samples in same order as psd_list Returns: data frame w...
5,323,597
def fake_quant_with_min_max_vars_per_channel_gradient(input_gradients, input_data, input_min, input_max, num_bits=8, narrow_range=False): """ Computes gradients of Fake-quantize on the 'input_data' tenso...
5,323,598
def top_off_accounts(): """ Sets account balances to the default if they are below default """ db_connection = DbConnection() update_account_query = "UPDATE account SET balance = %s WHERE balance < %s" db_connection.cursor.execute(update_account_query, [INITIAL_ACCOUNT_AMOUNT, INITIAL_ACCOUNT_AM...
5,323,599