content
stringlengths
22
815k
id
int64
0
4.91M
def compare(A: Mv, B: Mv) -> Union[Expr, int]: """ Determine if ``B = c*A`` where c is a scalar. If true return c otherwise return 0. """ if isinstance(A, Mv) and isinstance(B, Mv): Acoefs, Abases = metric.linear_expand(A.obj) Bcoefs, Bbases = metric.linear_expand(B.obj) if ...
5,286,800
def get_enum_size(*args): """get_enum_size(enum_t id) -> size_t""" return _idaapi.get_enum_size(*args)
5,286,801
def assert_gluonts( exception_class: type, condition: bool, message: str, *args, **kwargs ) -> None: """ If the given ``condition`` is ``False``, raises an exception of type ``exception_class`` with a message formatted from the ``message`` pattern using the ``args`` and ``kwargs`` strings. Para...
5,286,802
def process(img_name): """ 处理一张图片 """ bak_path = os.path.join(bak_dir, img_name) img_path = os.path.join(img_dir, img_name) # 备份 with open(img_path, 'rb') as fr, open(bak_path, 'wb') as fw: fw.write(fr.read()) # 读取 img = cv2.imread(img_path) # 缩小 h, w = img.shape[: 2] if...
5,286,803
def _martin_luther_king_holiday(year): """Martin Luther King's birthday (third Monday in January)""" if year < 1983: return None for day in range(15, 22): d = dt.date(year, 1, day) if d.weekday()==0: return d raise Exception('Should never get there')
5,286,804
def test_valid_alternatives(data, fld, value_in, value_out): """When the pydanic model is created, it should transform some fo the fields. Mode should be a two letter code made from uppercase letters or digits. The pydantic model should convert any letters to uppercase automatically. Uppercase letters...
5,286,805
def test_cmp_attrs_extents_flag(): """ Test that the cmp_attr function handles the extents flag correctly. This test specifically tests for a bug described in #57189. """ # If the e attribute is not present and shall not be set, it should be # neither in the added nor in the removed set. wit...
5,286,806
def main(): """ main entry point, report place visits summary to stdout """ parser = argparse.ArgumentParser() parser.add_argument("-p", "--place", help="Type of place visited, TYPE_WORK/HOME/etc", default="TYPE_WORK") args = parser.parse_args() total...
5,286,807
def random_bivariate_anisotropic_Gaussian(kernel_size, sigma_x_range, sigma_y_range, rotation_range, noise_range=None, ...
5,286,808
def clear_sheet() -> None: """This clears the google sheet before adding in new data.""" serviceAccount = gspread.service_account(filename='google-credentials.json') sheet = serviceAccount.open_by_key(config('GOOGLE_SHEET_URL_KEY')) worksheet = sheet.sheet1 worksheet.clear()
5,286,809
def validate_guess(number) -> str or None: """ :param number: the number to guess :return: the valid guessed number or None if user gives up """ number_size = len(number) while True: guess = easygui.enterbox(f"Please guess the {number_size}-digit number: ") if guess is None: ...
5,286,810
def test_consistency_verification_on_startup_case_1(tempdir): """ One more node was added to nodes file """ ledger = create_default_ledger(tempdir) tranzNum = 10 for d in range(tranzNum): ledger.add(random_txn(d)) # Writing one more node without adding of it to leaf and transaction l...
5,286,811
def excel_radiosonde(request, form): """ Reads the radiosonde form and converts the data into a excel file """ start = form.cleaned_data['start_date_radiosonde'] end = form.cleaned_data['end_date_radiosonde'] time = form.cleaned_data['time_radiosonde'] fields = form.cleaned_data['fields...
5,286,812
def compare_metrics(best_eval_result, current_eval_result): """Compares two evaluation results.""" return best_eval_result["exact_match"] < current_eval_result["exact_match"]
5,286,813
def import_module(filename): """Import a module given a full path to the file.""" spec = importlib.util.spec_from_file_location("doc_filter", filename) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
5,286,814
def set_target_bits(targs, sourcemask): """Apply bright source mask to targets, return desi_target array. Parameters ---------- targs : :class:`recarray` A recarray of targets as made by, e.g., :mod:`desitarget.cuts.select_targets`. sourcemask : :class:`recarray` A recarray containi...
5,286,815
def get_checksum_value(checksum): """ Return the checksum value. The given checksum might either be a standard ad32 or md5 string, or a dictionary with the format { checksum_type: value } as defined in the `FileSpec` class. This function extracts the checksum value from this dictionary (or immediate...
5,286,816
def construct_bibfile_data(*paths): """ List of data corresponding to individual bib files :param pathlib.Path *paths: Path to file possibly containing BibTeX data. :rtype: list """ bibs = [reffile_factory(path) for path in paths] return bibs
5,286,817
def check_shell_pipes(cmd): """ Determine whether a command appears to contain shell pipes. :param str cmd: Command to investigate. :return bool: Whether the command appears to contain shell pipes. """ return "|" in strip_braced_txt(cmd)
5,286,818
def scrap_allrecipes_recipe(url: str) -> Dict: """This function scraps a recipe of Allrecipes, given its URL, and prepare a JSON file to index in Elasticsearch. :param url: the URL of the recipe :return: the recipe as a JSON-like dictionary :raise: ConnectionError, if the connection against Allreci...
5,286,819
def waitTargetUpdate(omni_robot, timeout): """ Wait for target updating :param omni_robot: (OmniRobot) :param timeout: (time to wait for updating) """ omni_robot.target_pos_changed = True time = 0.0 # second while time < timeout and not rospy.is_shutdown(): if not omni_robot.tar...
5,286,820
def known_references(request): """ List all known references witht he option of removing the contact date """ user = request.user if 'remove_known_ref' in request.POST and \ request.POST['remove_known_ref'].isdigit(): try: application = CredentialApplication.objects.get( ...
5,286,821
def get_plugin(): """Return the filter.""" return IpynbFilter
5,286,822
def run_gliph(fname: str, cutoff: int = 0) -> Collection[Tuple[str]]: """ Run gliph. Note that we copy the fname into the current directory to make working with GLIPH's outputs a little easier Returns the path to the convergence groups txt file output """ assert os.path.isfile(fname) gliph_...
5,286,823
def main_loop(snake_list, cherry_list): """ Main loop of the game. This function returns only if snake collision occured. """ while True: # capture events for event in pygame.event.get(): if event.type == pygame.QUIT: # happens when user tries to close window...
5,286,824
def add_user(cursor, user_tuple): """ Adds user to the DB.Users :param cursor: cursor of the DB :param user_tuple: raw user data :return: None """ cursor.execute("insert into Users values (?,?,?,?,?,?,?)", user_tuple)
5,286,825
def __ensure_paragraphs(text): """ Checks if paragraph break in text else adds it and returns """ if "\n\n" in text: # Paragraph break detected just return it return text # If not detected add it ourselves new_text = "\n\n".join(__cut_text(text, length=500)) return new_text
5,286,826
def main(input_file: Path, output_file: Path): """Convert yml to json and vice versa""" if input_file.suffix == ".json": options = json.loads(input_file.read_text()) elif input_file.suffix == ".yml": options = yaml.safe_load(input_file.read_text()) else: raise RuntimeError(f"Cann...
5,286,827
def main(path, task, representation): """ :param path: str specifying path to dataset. :param task: str specifying the task. Always e_iso_pi in the case of the human performance comparison :param representation: str specifying the molecular representation. One of ['fingerprints, 'fragments', 'fragprints...
5,286,828
def vectorized_loss_and_aux(task_family: tasks_base.TaskFamily, learned_opt: lopt_base.LearnedOptimizer, theta: lopt_base.MetaParams, inner_opt_state: Any, task_param: Any, key: PRNGKey, data: Any) -> jnp.nda...
5,286,829
def region_of_interest(img, vertices): """ 区域选择 Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. """ # defining a blank mask to start with mask = np.zeros_like(img) # defining a 3 channel or 1 channel color to fill...
5,286,830
def segformer_b5(pretrained=False, progress=True, num_classes=150): """Create a SegFormer-B5 model. Args: pretrained: Download backbone weights pretrained on ImageNet data if true. progress: Display the download progress of pretrained weights if true. num_classes: Number of output class...
5,286,831
def expand_codes(df=None, codes=None, cols=None, sep=None, codebook=None, hyphen=True, star=True, colon=True, regex=None, del_dot=False, case_sensitiv...
5,286,832
def compute_roce(fpr, preds, real): """ Calculate the ROC enrichment (ROCE) score - i.e., the y value divided by the x value on an ROC curve, at a fixed predetermined x value (i.e. a fixed false positive rate). Args: fpr (float): pre-set false positive rate preds (np.array): model pr...
5,286,833
def create_local_path(*relative_path, cache=LOCAL_CACHE) -> str: """ Create path in local OS - if not exist, create make directory to the root :param relative_path: path relative to 'base_path' :param cache: initial part of local path to be be joined with :return: a full path in local OS """ ...
5,286,834
def segmentPlaneIntersection(s0 = "const Dim<3>::Vector&", s1 = "const Dim<3>::Vector&", point = "const Dim<3>::Vector&", normal = "const Dim<3>::Vector&", tol = ("const double", "1.0e-8")): """Inters...
5,286,835
def subplots(nrows=1, ncols=1, figsize=None, xlabel=None, ylabel=None): """ Creates subplots from matplotlib. Args: nrows (int): ncols (int): figsize (tuple[int, int]): xlabel (str): ylabel (str): Returns: fig (matplotlib.figure.Figure): the matplotlib f...
5,286,836
def get_host_data(root): """Traverses the xml tree and build lists of scan information and returns a list of lists. """ host_data = [] hosts = root.findall('host') for host in hosts: addr_info = [] # Ignore hosts that are not 'up' if not host.findall('status')[0].attrib[...
5,286,837
def with_progress_bar(target): """ Adapted from ipywidgets progress bar example :param target: Function to run. Function must take progress bar as argument. :return: None Try it out with:: a = [] def work(progress): total = 3 for i in range(total): ...
5,286,838
def incident_beam(*, source_chopper: sc.Variable, sample_position: sc.Variable) -> sc.Variable: """ Compute the incident beam vector from the source chopper position vector, instead of the source_position vector. """ return sample_position - source_chopper.value['position'].data
5,286,839
def main(args=None): """ Benchmark nevow.json string parsing, maybe with some parameters. """ options = StringTokenizer() options.parseOptions(args) benchmark(options['iterations'], options['scale'])
5,286,840
def arrhenius (A: float, E: float, T: float, R: float = R) -> float: """ Args: A: Pre-exponential (frequency) factor. ValueError raised if not > 0. E: Activation energy. T: Temperature in Kelvins. ValueError raised if not >= 0. R: Universal gas constant. ...
5,286,841
def xoai_contributor(source, *args, **kwargs): """ CZ: EN: """ value = [] for person_role in source: role = person_role["@name"] field = person_role["element"]["field"] if isinstance(field, list): for person in field: value.append( ...
5,286,842
def http_endpoint( flask_entity, flask_rule, method: HttpMethod = HttpMethod.GET, returns_json_response: bool = True, ): """ Decorator factory used to easily register a Transiter HTTP endpoint. :param flask_entity: either the Flask app or a Flask blueprint :param flask_rule: the URL rel...
5,286,843
def all_gather_cuda(data: Any) -> List[bytes]: """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = global_world_size() if world_size == 1: return [data] tensor = to_b...
5,286,844
def from_array(array, copy=True): """Convert a NumPy array to a tensor. Initializes a taco tensor from a NumPy array and copies the array by default. This always creates a dense tensor. Parameters ------------ array: numpy.array A NumPy array to convert to a taco tensor copy: boo...
5,286,845
def download(supported_tags, date_array, tag, sat_id, remote_site='https://cdaweb.gsfc.nasa.gov', data_path=None, user=None, password=None, fake_daily_files_from_monthly=False, multi_file_day=False): """Routine to download NASA CDAWeb CDF data. This routine i...
5,286,846
def test__get_all_hypotheses() -> None: """ Test `hsr4hci.hypotheses.get_all_hypotheses`. """ # Fix random seed np.random.seed(42) # Create fake PSF template x, y = np.meshgrid(np.arange(33), np.arange(33)) model = models.Gaussian2D(x_mean=17, y_mean=17) psf_template = model(x, y) ...
5,286,847
def eject_vmedia(task, device): """Eject the Vmedia. device: Ejects this device """ sdflex_object = get_sdflex_object(task.node) sdflex_object.eject_vmedia(device)
5,286,848
def maybeName(obj): """ Returns an object's __name__ attribute or it's string representation. @param obj any object @return obj name or string representation """ try: return obj.__name__ except (AttributeError, ): return str(obj)
5,286,849
def ped_datasets() -> List[str]: """Returns paths after downloading pedestrian datasets.""" if not os.path.exists("datasets"): subprocess.call( ["wget", "https://www.dropbox.com/s/8n02xqv3l9q18r1/datasets.zip"] ) subprocess.call(["unzip", "-q", "datasets.zip"]) subpro...
5,286,850
def compare(attr_a, attr_b=0, operation=0): """Create math_Compare-node to get boolean of logical comparison between given attrs. Args: attr_a (NcNode or NcAttrs or string): Maya node attribute. attr_b (NcNode or NcAttrs or float): Maya node attribute. operation (NcNode or NcAttrs or in...
5,286,851
def train_eval_input_fn(mode, params, restrict_classes=None, shift_classes=0): """Mode-aware input function. restrict_classes: for use with intra fid shift_classes: for use with restrict_classes """ is_train = mode == tf.estimator.ModeKeys.TRAIN split = 'train' if is_train else flags.FLAGS.dataset_val_sp...
5,286,852
def gc_nc_60_79(mqc): """ Analogous to gc_nc_0_19. """ k = inspect.currentframe().f_code.co_name try: d = next(iter(mqc["multiqc_picard_gcbias"].values())) v = d["GC_NC_60_79"] v = np.round(v, DECIMALS) except KeyError: v = "NA" return k, v
5,286,853
def generate_random_pose(): """ generate a random rod pose in the room with center at (0, 0), width 10 meters and depth 10 meters. The robot has 0.2 meters as radius Returns: random_pose """ def angleRange(x, y, room, L): """ Compute rod angle based on a given robot p...
5,286,854
def version_description(project_arn: str, version_name: str = None): """[Describes a Project on Rekognition in AWS] Args: project_arn (str): [Unique Identifier for a Project on Rekognition in AWS] version_name (str, optional): [Display Name]. Defaults to None. Raises: error: [Error...
5,286,855
def feature_importance(residuals, analysis_type="collective", date_from=None, date_till=None, weigh=True): """Feature importance calculation Parameters ---------- residuals : pandas.DataFrame() analysis_type : str, "single"/"collective", "single" by default date_from : str in format 'yyyy-mm-...
5,286,856
def utest(a, b): """ MannWhitney U statistic scipy.stats.mannwhitneyu tests for a != b Use only when the number of observation in each sample is > 20 and yo have 2 independent samples of ranks. Mann-Whitney U is significant if the u-obtained is LESS THAN or equal to the critical value of U....
5,286,857
async def run_async(func: Callable[..., Any], *args, **kwargs) -> Any: """ Runs a callable on the database thread pool executor using the current thread's I/O loop instance. Usage: def blocking_task(arg1, arg2, arg3): # ... # does some blocking stuff # ... ...
5,286,858
def constant_schedule_with_warmup(epoch, warmup_epochs=0, lr_start=1e-4, lr_max=1e-3): """ Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate increases linearly between {lr_start} and {lr_max}. """ if epoch < warmup_epochs: lr = (lr_max - ...
5,286,859
def cleanup_job(finished_tasks_queue): """ Perform the cleanup process on finished tasks. This function serves as the final stop for any Task that has gone through the pipleine, regardless of whether uploading is in effect or not, or its success state. The function will remo...
5,286,860
def gen_lc(x,p0,struct,pmax=85.): """ From gen_lc.pro """ #p0 = m0i, m0v, m0b, period, phase shift, tbreak1, tbreak2 p = np.array(p0).copy() if len(p) < 11: # use the poly fits to fill in the pca1-pca4 coeffs c_need = 11 - len(p0) poly_fits = struct["POLY_FITS"][0] new_coeffs = [...
5,286,861
def normal_hash(node_count, item_count): """ 普通hash分布算法 取余分布 在分布式系统中存在严重问题,新加入结点时,会造成绝大部分数据需要迁移 :param node_count: 结点总数 :param item_count: 数据总量 :return: """ node_item_count = [0] * node_count new_node_count = node_count + 1 moved_item_count = 0 for item in range(item_co...
5,286,862
def create_embed(author, level, ascendency_name, class_name, main_skill: Skill, is_support): """ Create the basic embed we add information to :param author: of the parsed message - str :param level: of the build :param ascendency_name: to display :param class_name: to display if no ascendency ha...
5,286,863
def _set_default_extent(self: GeoAxesSubplot) -> None: """Helper for a default extent limited to the projection boundaries.""" west, south, east, north = self.projection.boundary.bounds self.set_extent((west, east, south, north), crs=self.projection)
5,286,864
def getVersionFolder(baseVersioningFolder, versionNumber=None): """ If versionNumber is None the newest version is returned if available. If the specified version is not available None is returned. """ if not os.path.exists(baseVersioningFolder): raise Exception(f"The given base versioning fold...
5,286,865
def test_user(session): """Check that users can be created and can set their password""" u = User(u'testuser', u'Test User', status=UserStatus.active) # Check authentication/permissions assert u.is_authenticated() assert u.active assert not u.pk session.add(u) session.commit() assert...
5,286,866
def get_cluster_name(): """ Retrieves the current cluster name from the CLUSTERNAME environment variable This should probably be in conf.py, but it creates dependency issues with ZMQ :return: str cluster name """ return environ.get('CLUSTERNAME')
5,286,867
def extract(): """Disconnect all arrows between selected and unselected nodes, and move selected nodes to the right. This function is maintained only for compatibility. Please use nuke.extractSelected() instead.""" nuke.extractSelected()
5,286,868
def ml_ssl(stft, sv, compression=0, eps=1e-8, norm=False, mask=None): """ Maximum likelihood SSL Arguments: stft: STFT transform result, M x T x F sv: steer vector in each directions, A x M x F norm: normalze STFT or not mask: TF-mask for source, T x F x (N) Return: ...
5,286,869
def test_containing(testInput, collection, expectedOutput, errorState): """utils: Check if collection contains an item""" if errorState is False: assert containing(collection, testInput) == expectedOutput else: with pytest.raises(utilsError) as e: containing(collection, testInpu...
5,286,870
def vonMisesStressUtilization(axial_stress, hoop_stress, shear_stress, gamma, sigma_y): """combine stress for von Mises""" # von mises stress a = ((axial_stress + hoop_stress)/2.0)**2 b = ((axial_stress - hoop_stress)/2.0)**2 c = shear_stress**2 von_mises = np.sqrt(a + 3.0*(b+c)) # stress ...
5,286,871
def fit(X, estimator, beta=0.05, N=None, start=1, step=1, tol=1e-5, max_iter=20, debug=False): """Run the StARS algorithm to select the regularization parameter for the given estimator. Parameters: - X (np.array): Array containing n observations of p variables. Columns are the observations of a...
5,286,872
def bar_chart(data2): """ A bar chart, like the one above but with small custom alterations title and size """ Chart2 = alt.Chart(data2).mark_bar().encode( alt.X ('movies', title="My Favorite Movies"), alt.Y ('num_oscars', title="# of Academy Awards"), color='movies', )....
5,286,873
def nSpecies(): """ Returns the total number of species in the model. """ return 62
5,286,874
def plot_convergence(*args, **kwargs): """Plot one or several convergence traces. Parameters ---------- * `args[i]` [`OptimizeResult`, list of `OptimizeResult`, or tuple]: The result(s) for which to plot the convergence trace. - if `OptimizeResult`, then draw the corresponding ...
5,286,875
def server_player_id(player_id): """Serve player ID endpoint. This endpoint is used to indicate a buzzer has been triggered, or register a buzzer. Args: player_id: Player identifier. """ gameshow = flask.current_app gameshow.state_machine.process( state_machine.Events.TRIGG...
5,286,876
def crt(cong): """Use the Chinese Remainder THeorem to solve the given system of congruences, cong = [(mod1, rem1), (mod2, rem2), ...] where val = rem1 mod mod1 val = rem2 mod mod2 ... The val satisfying the congruences is returned. """ result = 0 nprod = math.prod([v[0] for v in con...
5,286,877
def compose_message(body, subject, contacts): """ composes message using message text, subject, contacts and returns it encoded """ message = MIMEMultipart() message['subject'] = subject message['from'] = me message['to'] = contacts plaintext_body = html_to_text(body) print(...
5,286,878
def test_check_all_bad_handler_is_type_error_iff_uncallability_exists( uncall_result, str_list_monad, handler, expectation): """ Invalid handler evaluation is conditional having >= 1 uncallable command. """ cmd = "noncmd" with mock.patch.object(piper_utils, "determine_uncallable", ...
5,286,879
def getFileList(dbid, fnr, printi=0, type='A'): """ Get list of Sdicfile objects from Predict file :param dbid: dbid of Predic file :param fnr: file number of Predic file :param printi: print file list if True :param type: select by file type ('A' is Adabas file) :returns: list of Sdicfile na...
5,286,880
def generate_edges(content): """ Yields an edge <vertex vertex weight> to the graph if it's valid. :param content: The raw content of the input file. """ for edge in content: valid_edge = is_valid(edge) if valid_edge: yield valid_edge
5,286,881
def insertWarnings(lines, badCommand): """Insert warnings after a command that is probably to be checked. The text is to be given as a list of lines. A command in this sense can be any text that is not to be followed by an asciiletter """ lineNumber = 0 while lineNumber < len(lines): ...
5,286,882
def rho_p(rank_vector): """Compares each element in the vector to its corresponding value in the null distribution vector, using the probability mass function of the binomial distribution. Assigns a p-value to each element in the vector, creating the betaScore vector. Uses minimum betaScore as rho ...
5,286,883
def find_urls(tree: etree._ElementTree) -> Iterator[str]: """Yield URLs found in the document C{tree}.""" for node in tree.getroot().iter(): for attr in link_attrs_for_node(node.tag): try: yield cast(str, node.attrib[attr]) except KeyError: pass
5,286,884
def test_random_sample_generator(rows, size): """Test counting the number of rows in a generated sample.""" consumer = SampleCollector(columns=[], n=size, consumer=RowCount()) for i in range(rows): consumer.consume(i, []) assert consumer.close() == min(rows, size)
5,286,885
def occupy_seats(data, seat_tolerance, only_adjacent): """ Occupies seats according to rules. :param data: seat map (2d array) :param seat_tolerance: number of discovered seats that can be occupied to still make the person occupy the seat :param only_adjacent: boolean, if True only check directly adjac...
5,286,886
def refresh_plugin_data(request, workflow): """ Function to traverse the directory where the plugins live and check if the folders in there are reflected in the PluginRegistry model. :return: Reflect the changes in the database """ plugin_folder = get_plugin_path() pfolders = [f for f in ...
5,286,887
def get_orthogonal_grid_edges(pix_x, pix_y, scale_aspect=True): """calculate the bin edges of the slanted, orthogonal pixel grid to resample the pixel signals with np.histogramdd right after. Parameters ---------- pix_x, pix_y : 1D numpy arrays the list of x and y coordinates of the slanted...
5,286,888
def rom(a, b,f, eps = 1e-8): """Approximate the definite integral of f from a to b by Romberg's method. eps is the desired accuracy.""" R = [[0.5 * (b - a) * (f(a) + f(b))]] # R[0][0] #print_row(R[0]) n = 1 while True: h = float(b-a)/2**n R.append((n+1)*[None]) # Add an empty r...
5,286,889
def set_style(styles): """ Set the experiment specific plotting style Example: >>> import mplhep as hep >>> hep.set_style("ATLAS") >>> hep.set_style(mplhep.style.CMS) Parameters ---------- styles (`str` or `mplhep.style` `dict`): The experiment style ...
5,286,890
def map_pair_name_to_exchange_name(pair_name): """ We're preparing to add the notion that exchanges can have multiple trading pairs into our system. Each exchange is going to have a single ExchangeData db object but have one wrapper for each pair. Order.exchange_name is going to refer to the pair, b...
5,286,891
async def handle_list_comparisons( project_id: str, session: Session = Depends(database.session_scope), kubeflow_userid: Optional[str] = Header(database.DB_TENANT), ): """ Handles GET requests to /. Parameters ---------- project_id : str session : sqlalchemy.orm.session.Session ...
5,286,892
def get_args(): """ Get command-line arguments """ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Howler's Second Program") parser.add_argument("input", type=str, nargs="+", metavar="str", help="Input messages or files") parser.add_argument("-o", "-...
5,286,893
def load_model(file_name="model.pkl"): """ Parameters: file_name (string): exact path of the target saved model Returns: built chefboost model """ f = open('outputs/rules/'+file_name, 'rb') model = pickle.load(f) #restore modules from its references modules = [] for model_name in model["tr...
5,286,894
def init_weights_simple(m): """function to re-randomize initial weights so the model passes signals straight through""" if isinstance(m, nn.Linear): torch.nn.init.eye_(m.weight) m.weight.data.multiply_(0.9) m.bias.data.fill_(0.00) # if isinstance(m, nn.Linear): # torch.nn.ini...
5,286,895
def locate_template(template): """Locate the template file of a given name.""" *base, ext = template.split('.') if ext != 'yaml': template += '.yaml' return os.path.abspath(os.path.join(TEMPLATE_DIR, template))
5,286,896
def lower_first(string): """Return a new string with the first letter capitalized.""" if len(string) > 0: return string[0].lower() + string[1:] else: return string
5,286,897
def get_annotations_dict(members): """Get __annotations__ from a members map. Returns None rather than {} if the dict does not exist so that callers always have a reference to the actual dictionary, and can mutate it if needed. Args: members: A dict of member name to variable Returns: members['__an...
5,286,898
def exp(pda : pdarray) -> pdarray: """ Return the element-wise exponential of the array. Parameters ---------- pda : pdarray Returns ------- pdarray A pdarray containing exponential values of the input array elements Raises ------ TypeError Rai...
5,286,899