content
stringlengths
22
815k
id
int64
0
4.91M
def fatal_error(message, new_raise=None): """prints a fatal error when running this module""" print print 'natlinkconfigfunctions fails because of fatal error:' print print message print print 'This can (hopefully) be solved by closing Dragon and then running the NatLink/Unimacro/Vocola Conf...
5,330,700
def train_classification(base_iter, model, dataloader, epoch, criterion, optimizer, cfg, writer=None): """Task of training video classificati...
5,330,701
def get_top5(prediction): """return top5 index and value of input array""" length = np.prod(prediction.size) pre = np.reshape(prediction, [length]) ind = np.argsort(pre) ind = ind[length - 5 :] value = pre[ind] ind = ind[::-1] value = value[::-1] res_str = "" logging.info("====...
5,330,702
def add(ctx, name, authority, type_): """Create a new OAuth client.""" request = ctx.obj["bootstrap"]() client = models.AuthClient(name=name, authority=authority) if type_ == "confidential": client.secret = token_urlsafe() request.db.add(client) request.db.flush() id_ = client.id ...
5,330,703
def calculate_parentheses(cases): """Calculate all cases in parameter 'cases' return : case that calculate and it's 24 else return 'No Solutions' Example and Doctest : >>> nums = [5, 5, 9, 5] >>> cases = generate_all_combinations(nums, '+-*/') >>> calculate_parentheses(cases) '( ( 5 + 5 ) +...
5,330,704
def pbkdf2(hash_algorithm, password, salt, iterations, key_length): """ PBKDF2 from PKCS#5 :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an in...
5,330,705
def getLocalUtcTimeStamp(): """ Get the universal timestamp for this machine. """ t = time.mktime(time.gmtime()) isDst = time.localtime().tm_isdst return t - isDst * 60 * 60
5,330,706
def melt_then_pivot_query(df, inspect_result, semiology_term): """ if happy all are the same semiology, after insepction of QUERY_SEMIOLOGY, melt then pivot_table: --- inspect_result is a df Ali Alim-Marvasti July 2019 """ # find all localisation columns present: localisation_l...
5,330,707
def maze_solver(maze: List[List[int]]) -> List[Tuple[int, int]]: """ Finds the path that a light ray would take through a maze. :param maze: 2D grid of cells, where 0 = empty cell, -1 = mirror at -45 degrees, 1 = mirror at 45 degrees :return: The coordinates that the light passed, ordered by time """ validate_maz...
5,330,708
def looks_like_fasta(test_text): """Determine if text looks like FASTA formatted data. Looks to find at least two lines. The first line MUST start with '>' and the second line must NOT start with '>'. Ignores any starting whitespace. """ text = test_text.strip() return FASTA_START.match(...
5,330,709
def firwin_kaiser_bsf(f_stop1, f_pass1, f_pass2, f_stop2, d_stop, fs=1.0, N_bump=0, status=True): """ Design an FIR bandstop filter using the sinc() kernel and a Kaiser window. The filter order is determined based on f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the des...
5,330,710
def extract_text(html_text) -> List[List[str]]: """ :param html_text: :return: """ lines = [i.text.replace("\xa0", "") for i in html_text.find("div", attrs={"class": "contentus"}).findAll("h3")] return [line.split(" ") for line in lines if line]
5,330,711
def multidict(pairs: Iterable[Tuple[X, Y]]) -> Mapping[X, List[Y]]: """Accumulate a multidict from a list of pairs.""" rv = defaultdict(list) for key, value in pairs: rv[key].append(value) return dict(rv)
5,330,712
def total_inequalities_generator(block): """ Generator which returns all inequality Constraint components in a model. Args: block : model to be studied Returns: A generator which returns all inequality Constraint components block """ for c in activated_block_component_gener...
5,330,713
def test_rc_with_failing_module(shell, tmpdir, monkeypatch, capsys, xession): """Test that an RC file which imports a module that throws an exception .""" monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False") tmpdir.join("my_failing_modu...
5,330,714
def read_images(pathname): """ Read the images to a list given a path like 'images/cropped/*' :param pathname: file path :return: a list of color images and a list of corresponding file names """ images_path = sorted(glob.glob(pathname)) images = [] names = [] for path in images_path...
5,330,715
def repack(cfile): """ Re-pack line-transition data into lbl data for strong lines and continuum data for weak lines. Parameters ---------- cfile: String A repack configuration file. """ banner = 70 * ":" # Parse configuration file: args = parser(cfile) files, dbtype...
5,330,716
def cov(path): """ Run a test coverage report. :param path: Test coverage path :return: Subprocess call result """ cmd = "py.test --cov-report term-missing --cov {0}".format(path) return subprocess.call(cmd, shell=True)
5,330,717
def visualize_camera_movement(image1, image1_points, image2, image2_points, is_show_img_after_move=False): """ Plot the camera movement between two consecutive image frames :param image1: First image at time stamp t :param image1_points: Feature vector for the first image :param image2: First image...
5,330,718
def get_rgb_masks(data, separate_green=False): """Get the RGGB Bayer pattern for the given data. See `get_rgb_data` for description of data. Args: data (`numpy.array`): An array of data representing an image. separate_green (bool, optional): If the two green channels should be separated, ...
5,330,719
def _parse_ax(*args, **kwargs): """ Parse plotting *args, **kwargs for an AxesSubplot. This allows for axes and colormap to be passed as keyword or position. Returns AxesSubplot, colormap, kwargs with *args removed""" axes = kwargs.pop('axes', None) cmap = kwargs.get('cmap', None) if ...
5,330,720
def deactivate_call_later(monkeypatch): """Impede o uso de call_later""" monkeypatch.setattr(Agent_, "call_later", lambda self, time, method, *args: 1)
5,330,721
def _get_context(): """Determine the most specific context that we're in. Implementation from TensorBoard: https://git.io/JvObD. Returns: _CONTEXT_COLAB: If in Colab with an IPython notebook context. _CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook context (e.g., from runn...
5,330,722
def loadSHSMFCCs(IDs): """ Load all of the 12-dim MFCC features """ IDDict = getSHSIDDict() fin = open("SHSDataset/MFCC/bt_aligned_mfccs_shs.txt") mfccs = {} count = 0 while True: ID = fin.readline().rstrip() if not ID: break ID = IDDict[ID] if...
5,330,723
def __createTransactionElement(doc,tran): """ Return a DOM element represents the transaction given (tran) """ tranEle = doc.createElement("transaction") symbolEle = __createSimpleNodeWithText(doc, "symbol", tran.symbol) buyEle = __createSimpleNodeWithText(doc, "buy", "true" if tran.buy else "fa...
5,330,724
def received_information(update: Update, context: CallbackContext) -> int: """Store info provided by user and ask for the next category.""" text = update.message.text category = context.user_data['choice'] context.user_data[category] = text.lower() del context.user_data['choice'] update.message...
5,330,725
def set_payout_amount(): """ define amount of insurance payout NB must match what was defined in contract constructor at deployment """ return 500000e18
5,330,726
def process_season_data(*args) -> pd.DataFrame: """ Takes multiple season data frames, cleans each and combines into single dataframe. """ return pd.concat( map( lambda df: basketball_reference.process_df_season_summary( df=df, url_type="season_summary_per_game" ...
5,330,727
def descr(key): """Print a description of the physical constant corresponding to the input key.""" print('Description of ',key,':') print(' Name: ',all[key][0]) print(' Symbol (if avail.): ',all[key][1]) print(' Value: ',all[key][2]) print(' Standard deviation: ',a...
5,330,728
def daemonize(pidfile, logfile=None, user='ubuntu', drop=True): """ Make a daemon with the given pidfile and optional logfile """ # Disconnect from controlling TTY as a service try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "f...
5,330,729
def build_frame(station_num: int, snapshots_num: int): """Function to build citi_bike Frame. Args: station_num (int): Number of stations. snapshot_num (int): Number of in-memory snapshots. Returns: CitibikeFrame: Frame instance for citi-bike scenario. """ matrices_cls = gen...
5,330,730
def test_RunLog(test_client, test_user_1): """ runlog should add an entry into the useinfo table as well as the code table """ test_user_1.login() kwargs = dict( course=test_user_1.course.course_name, sid="test_user_1", div_id="test_activecode_1", code="this is a un...
5,330,731
def rucklidge(XYZ, t, k=2, a=6.7): """ The Rucklidge Attractor. x0 = (0.1,0,0) """ x, y, z = XYZ x_dt = -k * x + y * (a - z) y_dt = x z_dt = -z + y**2 return x_dt, y_dt, z_dt
5,330,732
def resolve(dirs, *paths): """ Joins `paths` onto each dir in `dirs` using `os.path.join` until one of the join results is found to exist and returns the existent result. :param dirs: A list of dir strings to resolve against :param paths: Path components to join onto each dir in `dirs` :return ...
5,330,733
def multiext(prefix, *extensions): """Expand a given prefix with multiple extensions (e.g. .txt, .csv, _peaks.bed, ...).""" if any((r"/" in ext or r"\\" in ext) for ext in extensions): raise WorkflowError( r"Extensions for multiext may not contain path delimiters " r"(/,\)." ) re...
5,330,734
def sum_range(n, total=0): """Sum the integers from 1 to n. Obviously the same as n(n+1)/2, but this is a test, not a demo. >>> sum_range(1) 1 >>> sum_range(100) 5050 >>> sum_range(100000) 5000050000L """ if not n: return total else: raise TailCall(sum_range...
5,330,735
def parallel_evaluation_mp(candidates, args): """ Evaluate the candidates in parallel using ``multiprocessing``. This function allows parallel evaluation of candidate solutions. It uses the standard multiprocessing library to accomplish the parallelization. The function assigns the evaluation of ea...
5,330,736
def _default_tcrsampler_human_beta(default_background = None, default_background_if_missing=None): """ Responsible for providing the default human beta sampler 'britanova_human_beta_t_cb.tsv.sampler.tsv' Returns ------- t : tcrsampler.sampler.TCRsampler """ from tcrsampler.sampler import T...
5,330,737
def _dblock_to_raw( mkh5_f, dblock_path, garv_annotations=None, apparatus_yaml=None, ): """convert one mkh5 datablock+header into one mne.RawArray Ingest one mkh5 format data block and return an mne.RawArray populated with enough data and channel information to use mne.viz and the mne.Epochs, mne.E...
5,330,738
def _get_positive_mask(positive_selection, cls_softmax, cls_gt): """Gets the positive mask based on the ground truth box classifications Args: positive_selection: positive selection method (e.g. 'corr_cls', 'not_bkg') cls_softmax: prediction classification softmax scores cls...
5,330,739
def plot_filters(xs, ys, path): """ Plot the filters of a nn Params: xs (list of integers): list of x coordinate for points on which the filters are evaluated. ys (list of integers): list of y coordinate for points on which the filters are evaluated. path (str...
5,330,740
def make_bash_profile(home_dir, nano_dir): """Creates a .bash_profile file for nano setup Adds nano to the path and sets the default editor to nano """ nano_path = make_posix_path(nano_dir) contents = '\n'.join(['', '# Add nano to path and set as default editor', ...
5,330,741
def max_min_index(name_index): """Return maximum and minimum value with country of a column from df.""" country_and_name = df_copy[["country", name_index]] counrties_in_name_index = country_and_name.sort_values(name_index).dropna() min_value = [ list(counrties_in_name_index[name_index])[0], ...
5,330,742
def add_bold_line(latex: str, index: int) -> str: """Makes a provided line number bold """ lines = latex.splitlines() cells = lines[index].split("&") lines[index] = r'\bfseries ' + r'& \bfseries '.join(cells) return '\n'.join(lines)
5,330,743
async def test_if_fires_on_entity_change_with_for_multiple_force_update(hass, calls): """Test for firing on entity change with for and force update.""" assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { ...
5,330,744
def square(V,resp,weight): """Computes the expansion coefficients with a least squares regression""" if np.any(weight): Vt = V.T v1 = Vt.dot(np.transpose(weight*Vt)) v2 = Vt.dot(np.transpose(weight*resp.T)) coef = np.linalg.solve(v1,v2) else: coef = np.linalg.lstsq(V,r...
5,330,745
async def test_async_get_data_ZeversolarError(): """Fetch inverter data throws an error.""" url = "test" with pytest.raises(ZeversolarError): my_inverter = Inverter(url) await my_inverter.async_get_data()
5,330,746
def _unwrap_function(func): """Unwrap decorated functions to allow fetching types from them.""" while hasattr(func, "__wrapped__"): func = func.__wrapped__ return func
5,330,747
def test_invalid_backup_target_nfs(request, admin_session, harvester_api_endpoints): """ Backup Restore Testing Covers: Negative backup-and-restore-03-Create Backup Target Negative """ resp = admin_session.get(harvester_api_endpoints.get_backup_t...
5,330,748
def add_shell(shell): """Add <shell> to /etc/shells if it's not already there.""" etc_shells = open('/etc/shells') valid_shells = etc_shells.read().split() etc_shells.close() if shell not in valid_shells: etc_shells = open('/etc/shells', 'a') print(shell, file=etc_shells) etc...
5,330,749
def get_data(exception: bool = True, key_form: str = "data") -> "dict or None": """Função captura os dados de uma rota. A captura é feita caso a rota seja com `JSON` ou `Multipart-form` caso contrario lança um exceção. As imagens são capturadas na função `get_files`. `exception` campo boleano opcional ...
5,330,750
def run_perceptron(): """ Fit and plot fit progression of the Perceptron algorithm over both the linearly separable and inseparable datasets Create a line plot that shows the perceptron algorithm's training loss values (y-axis) as a function of the training iterations (x-axis). """ for n, f in ...
5,330,751
def local_predict(args): """Runs prediction locally.""" session, _ = session_bundle.load_session_bundle_from_path(args.model_dir) # get the mappings between aliases and tensor names # for both inputs and outputs input_alias_map = json.loads(session.graph.get_collection('inputs')[0]) output_alias_map = json...
5,330,752
def get_dec_log(uid): """Convenience method to look up inc_log for a uid.""" rv = query_db('select dec_log from user where uid = ?', [uid], one=True) return rv[0] if rv else None
5,330,753
def _iptables_restore(iptables_state, noflush=False): """Call iptable-restore with the provide tables dump :param ``str`` iptables_state: Table initialization to pass to iptables-restore :param ``bool`` noflush: *optional* Do not flush the table before loading the rules. """ # Use l...
5,330,754
def rescale_to_unit_interval(X_train, X_val, X_test): """ Scaling all data to [0,1] w.r.t. the min and max in the train data is very important for networks without bias units. (data close to zero would otherwise not be recovered) """ X_train = np.array(X_train, dtype=np.float32) X_val = np....
5,330,755
def removeItem(request): """ Removes item from logged in customers basket. """ if request.method == 'POST': cust = User.objects.get(username=request.user.username) item_id = request.POST["item_id"] item = Item.objects.get(id=item_id) b_item = Basket.objects.get(customer=cust, item=item) if(b_item): b_i...
5,330,756
def read_file(repo, name): """Read JSON files.""" with open(repo + '/' + name + '.txt') as file: data = [d.rstrip() for d in file.readlines()] file.close() return data
5,330,757
def vis_img_resize(): """ Returns: """ img_rd_1 = np.random.randint(0, 255, (640, 480, 3), dtype=np.uint8) img_rd_2 = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) tar_size = (416, 416) img_1, _ = utils.img_preprocess_fix_ratio(img_rd_1, tar_size) img_2, _ = utils.img_prepro...
5,330,758
def add_end_slash(value: str): """ Added a slash at the end of value """ if type(value) != str: return value return value if value.endswith("/") else value + "/"
5,330,759
def shift_fill(a, n, axis=0, fill=0.0, reverse=False): """ shift n spaces backward along axis, filling rest in with 0's. if n is negative, shifts forward. """ shifted = np.roll(a, n, axis=axis) shifted[:n] = fill return shifted
5,330,760
def str2bool(v:Union[str, bool]) -> bool: """ finished, checked, converts a "boolean" value possibly in the format of str to bool Parameters ---------- v: str or bool, the "boolean" value Returns ------- b: bool, `v` in the format of bool References ----------...
5,330,761
def test_dsl_cmd_shell_override(): """Override shell arg from dict shell input.""" obj = CmdStep('blahname', Context({'cmd': {'run': 'blah', 'cwd': 'pathhere', 'shell': True, ...
5,330,762
def _none_or_int_or_list(val): """Input conversion - expecting None, int, or a list of ints""" if val is None: return None elif isinstance(val, list): return list(map(int, val)) else: return int(val)
5,330,763
def verify_kms_ca_only(): """ Verify KMS deployment with only CA Certificate without Client Certificate and without Client Private Key """ log.info("Verify KMS deployment with only CA Certificate") secret_names = get_secret_names() if ( "ocs-kms-client-cert" in secret_names ...
5,330,764
def hour_of_day(datetime_col): """Returns the hour from a datetime column.""" return datetime_col.dt.hour
5,330,765
def pad_lists(lists, pad_token, seq_lens_idx=[]): """ Pads unordered lists of different lengths to all have the same length (max length) and orders length descendingly Arguments: lists : list of 1d lists with different lengths (list[list[int]]) pad_token : padding value (int) ...
5,330,766
def step1(records): """An iterator for step 1. Produces a stream of `giss_data.Series` instances. :Param records: An iterable source of `giss_data.Series` instances (which it will assume are station records). """ # without_strange = records without_strange = drop_strange(record...
5,330,767
def sum_naturals(n): """Sum the first N natural numbers >>> sum_naturals(5) 15 """ total = 0 k = 1 while k <= n: total += k k += 1 return total
5,330,768
def _gaussian_log_sf(x, mu, sigma): """Log SF of a normal distribution.""" if not isinstance(x, chainer.Variable): x = chainer.Variable(x) return _log_ndtr(-(x - mu) / sigma)
5,330,769
def example2(): """Run example for problem with input lines.""" print("\nEXAMPLE 2") lines = SAMPLE_INPUT2.strip("\n").split("\n") result = solve2(lines) expected = 12 print(f"'sample-input' -> {result} (expected {expected})") assert result == expected print("= " * 32)
5,330,770
def sort_list_files(list_patches, list_masks): """ Sorts a list of patches and masks depending on their id. :param list_patches: List of name of patches in the folder, that we want to sort. :param list_masks: List of name of masks in the folder, that we want to sort. :return: List of sorted lists, r...
5,330,771
def get_model(name): """ get_model """ if name not in __factory: raise KeyError("unknown model:", name) return __factory[name]
5,330,772
def main(): """Prints the OS name, version, and architecture.""" os, version, arch = os_version_arch() if version == "": print("%s-%s" % (os, arch)) else: print("%s-%s-%s" % (os, version, arch))
5,330,773
def defaults_to_cfg(): """ Creates a blank template cfg with all accepted fields and reasonable default values Returns: config (ConfigParser): configuration object containing defaults """ config = configparser.ConfigParser(allow_no_value=True) config.add_section("General") config.set("Gen...
5,330,774
def check_sentence_for_coins(sentence: str) -> str: """Returns the corresponding binance pair if a string contains any words refering to a followed coins Args: sentence (str): the sentence Returns: str: the binance pair if it contains a coins, otherwise returns 'NO_PAIR' """ coin = n...
5,330,775
def testBoard3(): """ Test a 10x10 board with 10 mines to see if tiles are being flagged properly. """ testBoard1() # flag tile at (0,0), (0,1), etc. b.flagTileAt(0,0) b.flagTileAt(0,1) b.flagTileAt(0,2) b.flagTileAt(0,3) b.flagTileAt(0,4) b.flagTileAt(0,5) b.flagTileAt(0...
5,330,776
def to24Bit(color8Bit): """The method allows you to convert the 8-bit index created by the color.to8Bit method to 24-bit color value.""" # We ignore first one, so we need to shift palette indexing by one return palette[color8Bit + 1]
5,330,777
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Plex sensor.""" name = config.get(CONF_NAME) plex_user = config.get(CONF_USERNAME) plex_password = config.get(CONF_PASSWORD) plex_server = config.get(CONF_SERVER) plex_host = config.get(CONF_HOST) plex_port = ...
5,330,778
def read_json_method(data): """ Reformatting Valve key/value format to JSON and returning JSON. """ # default vars parent = [] depth = 0 vdict = {} # init json and add opening bracket vjson = "{" # replace tabs with spaces data.replace("\t", " ") # split into lin...
5,330,779
def make_bag(): """Create a bag.""" return from_sequence( [1, 2], npartitions=2 ).map(allocate_50mb).sum().apply(no_allocate)
5,330,780
def get_testdata_files(pattern="*"): """ Return test data files from dicom3d data root directory """ data_path = join(DATA_ROOT, 'test_files') files = walk_data( base=data_path, pattern=pattern, search_files=True, search_dirs=False) return [filename for filename in files if not filename.endswith('.py')]
5,330,781
def safe_text(obj): """Safely turns an object into a textual representation. Calls str(), then on Python 2 decodes the result. """ result = qcore.safe_str(obj) if isinstance(result, bytes): try: result = result.decode("utf-8") except Exception as e: result =...
5,330,782
def evaluate_blueprints(blueprint_q: mp.Queue, input_size: List[int]) -> List[BlueprintGenome]: """ Consumes blueprints off the blueprints queue, evaluates them and adds them back to the queue if all of their evaluations have not been completed for the current generation. If all thei...
5,330,783
def assert_equal(actual: List[str], desired: List[str]): """ usage.scipy: 1 usage.skimage: 1 usage.statsmodels: 37 """ ...
5,330,784
def view_database(database_name, query_criteria='Indexes'): """ 查看指定数据库信息 View specified database information :param database_name: 数据库名称。Database name. :param query_criteria: 查询条件,'Indexes'查询此数据库包含什么物质。'survey'查询数据库中的数据概括。 Query_criteria,'indexes' queries what substances...
5,330,785
def run_noble_coder(text, noble_coder): """ Run Noble Coder Args: text: the text to feed into Noble Coder noble_coder: the execution path of Noble Coder Returns: The perturbation agent """ pert_agent = None with tempfile.TemporaryDirectory() as dirname: with ...
5,330,786
def print_chart(string): """Split a string into letters, then 'chart' it.""" bar_dict = defaultdict(list) for char in string: char = char.lower() if char in ALPHABET: bar_dict[char].append(char) pprint.pprint(bar_dict, width=110)
5,330,787
def xor(*args): """True if exactly one of the arguments of the iterable is True. >>> xor(0,1,0,) True >>> xor(1,2,3,) False >>> xor(False, False, False) False >>> xor("kalimera", "kalinuxta") False >>> xor("", "a", "") True >>> xor("", "", "") False """ retur...
5,330,788
def proc(log_file, thread, circ_file, hisat_bam, rnaser_file, reads, outdir, prefix, anchor, lib_type): """ Build pseudo circular reference index and perform reads re-alignment Extract BSJ and FSJ reads from alignment results Returns ----- str output file name """ from utils im...
5,330,789
def zjitter(jitter=0.0, radius=5): """ scan jitter is in terms of the fractional pixel difference when moving the laser in the z-direction """ psfsize = np.array([2.0, 1.0, 3.0]) # create a base image of one particle s0 = init.create_single_particle_state(imsize=4*radius, radiu...
5,330,790
def append_column(rec, col, name=None, format=None): """ Append a column to the end of a records array. Parameters ---------- rec : recarray Records array. col : array_like Array or similar object which will be converted into the new column. name : str, optional Name...
5,330,791
def dfa2nfa(dfa): """Copy DFA to an NFA, so remove determinism restriction.""" nfa = copy.deepcopy(dfa) nfa.transitions._deterministic = False nfa.automaton_type = 'Non-Deterministic Finite Automaton' return nfa
5,330,792
def count_related_m2m(model, field): """Return a Subquery suitable for annotating a m2m field count.""" subquery = Subquery(model.objects.filter(**{"pk": OuterRef("pk")}).order_by().annotate(c=Count(field)).values("c")) return Coalesce(subquery, 0)
5,330,793
def deap_processor(individual=1): """ initial function prepared data we need according to the condition :param session: session in [1, 2, 3] means which session of experiment :param individual: there are 15 individuals participate this experiment, this parameter reply number 1 to...
5,330,794
def main(): """Main function""" logging.info("[> Reporter is starting ] 0%") parser.add_argument("input", help="The path of input file or folder") parser.add_argument("output", help="The path of output file or folder") parser.add_argument("-f", "--folder", action='store...
5,330,795
def create_car(sql: Session, car: CarsCreate): """ Create a record of car with its Name & Price """ new_car = Cars( Name=car.Name, Price=car.Price ) sql.add(new_car) sql.commit() sql.refresh(new_car) return new_car
5,330,796
def train(train_loader, model, criterion, optimizer, args, epoch): """Train process""" '''Set up configuration''' batch_time = AverageMeter() data_time = AverageMeter() am_loss = AverageMeter() vec_loss = AverageMeter() dis_loss = AverageMeter() ske_loss = AverageMeter() kps_loss = A...
5,330,797
def fetch_folder_config(path): """Fetch config file of folder. Args: path (str): path to the wanted folder of the config. Returns: dict. the loaded config file. """ config = {} config_path = os.path.join(path, DOC_YML) if os.path.exists(config_path): with open(confi...
5,330,798
def test_pre_cli_version(run): """version should print dork.__version__ """ out, err = run(dork.cli.the_predork_cli, [], *("", "-v")) assert dork.__version__ in out, \ "Failed run the dork.cli.the_predork_cli method: {err}"\ .format(err=err)
5,330,799