content
stringlengths
22
815k
id
int64
0
4.91M
def convert_mg_l_to_mymol_kg(o2, rho_0=1025): """Convert oxygen concentrations in ml/l to mymol/kg.""" converted = o2 * 1/32000 * rho_0/1000 * 1e6 converted.attrs["units"] = "$\mu mol/kg$" return converted
36,700
def parse_defines(root: xml.etree.ElementTree.Element, component_id: str) -> List[str]: """Parse pre-processor definitions for a component. Schema: <defines> <define name="EXAMPLE" value="1"/> <define name="OTHER"/> </defines> Args: root: root ...
36,701
def wheel(string = None): """ Spinning ascii wheel keep alive, user string is optional Args: string (str) : String to display before the spinning wheel Returns: none """ _wheel(string)
36,702
def make_f_beta(beta): """Create a f beta function Parameters ---------- beta : float The beta to use where a beta of 1 is the f1-score or F-measure Returns ------- function A function to compute the f_beta score """ beta_2 = beta**2 coeff = (1 + beta_2) def...
36,703
def _autohint_code(f, script): """Return 'not-hinted' if we don't hint this, else return the ttfautohint code, which might be None if ttfautohint doesn't support the script. Note that LGC and MONO return None.""" if script == 'no-script': return script if not script: script = noto_fonts.script_key_to...
36,704
def infostring(message=""): """Info log-string. I normally use this at the end of tasks. Args: message(str): A custom message to add. Returns: (str) """ message.rstrip().replace("\n", " ") return tstamp() + "\t## INFO ## " + message + "\n"
36,705
def handler(event, _): """ Lambda handler """ # Input event: # https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#cognito-user-pools-lambda-trigger-event-parameter-shared logger.debug({ "message": "Input event", ...
36,706
def geo_point_n(arg, n): """Return the Nth point in a single linestring in the geometry. Negative values are counted backwards from the end of the LineString, so that -1 is the last point. Returns NULL if there is no linestring in the geometry Parameters ---------- arg : geometry n : in...
36,707
def replace_pasture_scrubland_with_shrubland(df, start_col, end_col): """Merge pasture and scrubland state transitions into 'shrubland'. 1. Remove transitions /between/ scrubland and pasture and vice versa. 2. Check there are no duplicate transitions which would be caused by an identical set of cond...
36,708
def init_random_seed(seed: int) -> None: """Initialize random seed of Python's random module, NumPy, and PyTorch. Args: seed: Seed value. """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed)
36,709
def get_storage_backend_descriptions() -> List[dict]: """ Returns: """ result = list() for backend in SUPPORTED_STORAGE_BACKENDS: result.append(get_storage_backend(backend).metadata) return result
36,710
def main(): """ main function """ # parse command-line parameters parser = argparse.ArgumentParser( description='generate SPEXone L1A product simulating a science orbit') parser.add_argument('--navigation_data', default=None, help=('navigation data used to initial...
36,711
def get_business_with_most_location() -> Tuple: """ Fetches LA API and returns the business with most locations from first page :return Tuple: business name and number of locations """ response = _fetch_businesses_from_la_api() business_to_number_of_location = dict() if response.status_c...
36,712
def degrees_to_polynomial(degrees: AbstractSet[int]) -> Poly: """ For each degree in a set, create the polynomial with those terms having coefficient 1 (and all other terms zero), e.g.: {0, 2, 5} -> x**5 + x**2 + 1 """ degrees_dict = dict.fromkeys(degrees, 1) return Poly.from_dict(degr...
36,713
def validate_set_member_filter(filter_vals, vals_type, valid_vals=None): """ Validate filter values that must be of a certain type or found among a set of known values. Args: filter_vals (obj or Set[obj]): Value or values to filter records by. vals_type (type or Tuple[type]): Type(s) of...
36,714
def nsi_delete2(ctx, name, force, wait): """deletes a Network Slice Instance (NSI) NAME: name or ID of the Network Slice instance to be deleted """ logger.debug("") nsi_delete(ctx, name, force, wait=wait)
36,715
def reorder_widgets(dashboard_id, widget_data): """ Reorders Widgets given the relative order desired, reorders widgets in the next possible set of numbers i.e if order of widgets is 1, 2, 3 the reordered widgets will have order 4, 5, 6 """ dashboard_widgets = Widget.objects.filter( ...
36,716
def run(weavrs_instance, weavr): """Do the prosthetic activity for a given weavr.""" logging.info(u"Hello, weavr %s" % weavr.key().name()) client = weavrsclient.WeavrsClient(weavrs_instance, weavr) config = client.get_weavr_configuration() logging.info(u"Got configuration: %s" % config)
36,717
def ultimate_1_post(): """Igre ultimativnih križcev in krožcev za enega igralca.""" check_user_id() # Poiščemo igro trenutnega igralca. user_id = int(bottle.request.get_cookie(COOKIE, secret=SECRET)) ultimate_1 = user_tracker.users[user_id][2] if ultimate_1.state == "P": # Določimo začet...
36,718
def start_replication(cur, slot_name=DEFAULT_SLOT_NAME, observable_nodes=None): """Start replication, create slot if not already there.""" replication_parms = {'slot_name': slot_name, 'decode': True} # # notifications only for configured tables, see https://github.com/eulerto/wal2json#parameters if obse...
36,719
def update_many(token, checkids, fields, customerid=None): """ Updates a field(s) in multiple existing NodePing checks Accepts a token, a list of checkids, and fields to be updated in a NodePing check. Updates the specified fields for the one check. To update many checks with the same value, use update...
36,720
def main(start, end, csv_name, verbose): """Run script conditioned on user-input.""" print("Collecting Pomological Watercolors {s} throught {e}".format(s=start, e=end)) return get_pomological_data(start=start, end=end, csv_name=csv_name, verbose=verbose)
36,721
def publish(message: Message) -> None: """ Publishes a message on Taskhawk queue """ message_body = message.as_dict() payload = _convert_to_json(message_body) if settings.IS_LAMBDA_APP: topic = _get_sns_topic(message.priority) _publish_over_sns(topic, payload, message.headers) ...
36,722
def _sub_fetch_file(url, md5sum=None): """ Sub-routine of _fetch_file :raises: :exc:`DownloadFailed` """ contents = '' try: fh = urlopen(url) contents = fh.read() if md5sum is not None: filehash = hashlib.md5(contents).hexdigest() if md5sum and fi...
36,723
def write_dict_to_hdf5( data_dict: dict, entry_point, group_overwrite_level: int = np.inf ): """ Args: data_dict (dict): dictionary to write to hdf5 file entry_point (hdf5 group.file) : location in the nested hdf5 structure where to write to. """ for key, item in data_dic...
36,724
def get_path_to_config(config_name: str) -> str: """Returns path to config dir""" return join(get_run_configs_dir(), config_name)
36,725
def get_orig_rawimage(raw_file, debug=False): """ Read a raw, original LRIS data frame. Ported from LOWREDUX long_oscan.pro lris_oscan() Parameters ---------- raw_file : :obj:`str` Filename debug : :obj:`bool`, optional Run in debug mode (doesn't do anything) Returns ...
36,726
def scan_db_and_save_table_info(data_source_id, db_connection, schema, table): """Scan the database for table info.""" table_info = get_table_info( {}, schema, table, from_db_conn=True, db_conn=db_connection ) old_table_info = fetch_table_info(data_source_id, schema, table, as_obj=True) data...
36,727
def _get_non_heavy_neighbor_residues(df0, df1, cutoff): """Get neighboring residues for non-heavy atom-based distance.""" non_heavy0 = df0[df0['element'] != 'H'] non_heavy1 = df1[df1['element'] != 'H'] dist = spa.distance.cdist(non_heavy0[['x', 'y', 'z']], non_heavy1[['x', 'y', 'z']]) pairs = np.ar...
36,728
def j0(ctx, x): """Computes the Bessel function `J_0(x)`. See :func:`besselj`.""" return ctx.besselj(0, x)
36,729
def mysql2df(host, user, password, db_name, tb_name): """ Return mysql table data as pandas DataFrame. :param host: host name :param user: user name :param password: password :param db_name: name of the pydb from where data will be exported :param tb_name: name of the table from where data ...
36,730
def is_int(number): """ Check if a variable can be cast as an int. @param number: The number to check """ try: x = int(number) return True except: return False
36,731
def load_pretrained_net_weights(net, ckpt_path): """ A function loading parameters (weights and biases) from a previous training to a net RNN instance :param net: An instance of RNN :param ckpt_path: path to .ckpt file storing weights and biases :return: No return. Modifies net in place. """ ...
36,732
def get_versions(api_type=DEFAULT_TYPE): """Search for API object module files of api_type. Args: api_type (:obj:`str`, optional): Type of object module to load, must be one of :data:`API_TYPES`. Defaults to: :data:`DEFAULT_TYPE`. Raises: :exc:`exceptions.NoVersion...
36,733
def convert_dict_time_format(data: dict, keys: list): """ Convert dictionary data values time format. Args: data (dict): Data. keys (list): Keys list to convert """ for key in keys: if data.get(key): str_time = data.get(key)[:-2] + 'Z' # type: ignore ...
36,734
def auto_update_library(sync_with_mylist, silent): """ Perform an auto update of the exported items to Kodi library, so check if there is new seasons/episodes. If sync_with_mylist is enabled the Kodi library will be also synchronized with the Netflix "My List". :param sync_with_mylist: True to e...
36,735
def test_short_equals_forms(): """Check parsed arguments with one character options with =value.""" line = 'doc/*.md --skip="Floats" -s=Cherries -u=MyTEXT -d=CIDER --setup-doctest --fail-nocode' args = parse_collect_line(parser, line) assert args == { "file_glob": "doc/*.md", "skips": ["...
36,736
def model_flux(parameters_dict, xfibre, yfibre, wavelength, model_name): """Return n_fibre X n_wavelength array of model flux values.""" parameters_array = parameters_dict_to_array(parameters_dict, wavelength, model_name) return moffat_flux(parameters_array, x...
36,737
def new_rnn_layer(cfg, num_layer): """Creates new RNN layer for each parameter depending on whether it is bidirectional LSTM or not. Uses the fast LSTM implementation backed by CuDNN if a GPU is available. Note: The normal LSTMs utilize sigmoid recurrent activations so as to retain compatibility CuDNN...
36,738
def firfreqz(h, omegas): """Evaluate frequency response of an FIR filter at discrete frequencies. Parameters h: array_like FIR filter coefficient array for numerator polynomial. e.g. H(z) = 1 + a*z^-1 + b*z^-2 h = [1, a, b] """ hh = np.zeros(omegas.shape, dtype='comple...
36,739
def write_np2pickle(output_fp: str, array, timestamps: list) -> bool: """ Convert and save Heimann HTPA NumPy array shaped [frames, height, width] to a pickle file. Parameters ---------- output_fp : str Filepath to destination file, including the file name. array : np.array Temp...
36,740
def run( client_id_: str, client_secret_: str, server_class=HTTPServer, handler_class=S, port=8080 ) -> str: """ Generates a Mapillary OAuth url and prints to screen as well as opens it automatically in a browser. Declares some global variables to pull data from the HTTP server through the GET endpoint....
36,741
def sort_by_rank_change(val): """ Sorter by rank change :param val: node :return: nodes' rank value """ return abs(float(val["rank_change"]))
36,742
def ping(): """always 200""" status = 200 return flask.Response(response='\n', status=status, mimetype='application/json')
36,743
def lambda_handler(event=None, context=None): """Entry point for lambda, simple try/except/finally with return and raise values""" print(f"EVENT: {json.dumps(event)}") try: response = actions(event) return response except Exception as e: logging.debug(f"Exception: {e}") r...
36,744
def add_gtid_ranges_to_executed_set(existing_set, *new_ranges): """Takes in a dict like {"uuid1": [[1, 4], [7, 12]], "uuid2": [[1, 100]]} (as returned by e.g. parse_gtid_range_string) and any number of lists of type [{"server_uuid": "uuid", "start": 1, "end": 3}, ...]. Adds all the ranges in the lists to th...
36,745
def fetch_rgb(img): """for outputing rgb values from click event to the terminal. :param img: input image :type img: cv2 image :return: the rgb list :rtype: list """ rgb_list = [] def click_event(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: red = i...
36,746
def load_checkpoint(model, pth_file, check=False): """load state and network weights""" checkpoint = torch.load(pth_file, map_location=lambda storage, loc: storage.cuda()) if 'model' in checkpoint.keys(): pretrained_dict = checkpoint['model'] else: pretrained_dict = checkpoint['state_dic...
36,747
def index(context): """Create indexes for the database""" log.info("Running scout index") adapter = context.obj['adapter'] adapter.load_indexes()
36,748
def _get_date_filter_consumer(field): """date.{lt, lte, gt, gte}=<ISO DATE>""" date_filter = make_date_filter(functools.partial(django_date_filter, field_name=field)) def _date_consumer(key, value): if '.' in key and key.split(".")[0] == field: prefix, qualifier = key.split(".", maxspli...
36,749
def plot_matches(ax, image1, image2, keypoints1, keypoints2, matches, title='', keypoints_color='b', matches_color=None, only_matches=False): """Plot matched features. Parameters ---------- ax : matplotlib.axes.Axes Matches and image are drawn in this ax. image1 : (N, M [, 3...
36,750
def list_devices(AccessToken=None, Limit=None, PaginationToken=None): """ Lists the devices. See also: AWS API Documentation :example: response = client.list_devices( AccessToken='string', Limit=123, PaginationToken='string' ) :type AccessToken: string...
36,751
def data_path(fname): """ Gets a path for a given filename. This ensures that relative filenames to data files can be used from all modules. model.json -> .../src/data/model.json """ return join(dirname(realpath(__file__)), fname)
36,752
def _parse_special_functions(sym: sp.Expr, toplevel: bool = True) -> sp.Expr: """ Recursively checks the symbolic expression for functions which have be to parsed in a special way, such as piecewise functions :param sym: symbolic expressions :param toplevel: as this is called recur...
36,753
def write_model_inputs(scenario_directory, scenario_id, subscenarios, subproblem, stage, conn): """ Get inputs from database and write out the model input rps_targets.tab file. :param scenario_directory: string, the scenario directory :param subscenarios: SubScenarios object with all subscenario inf...
36,754
def load_oxfordiiitpets(breed=True) -> core.SceneCollection: """Load the Oxford-IIIT pets dataset. It is not divided into train, validation, and test because it appeared some files were missing from the trainval and test set documents (e.g., english_cocker_spaniel_164). Args: breed: Whether...
36,755
def _do_process_purpose(action): """ Does all the 'hard work' in processing the purpose. Returns a single line of the form symbol, ex_date(yyyy-mm-dd), purpose(d/b/s), ratio(for b/s), value(for d), """ symbol = action.sym.upper() purpose = action.purpose.lower() ex_date = action.ex_date ...
36,756
def test_multiple_input(input_gridsize=128, output_gridsize=64): """ Tests that passing an input grid where every input_gridsize/output_gridsize cell is filled will a value of (input_gridsize/output_gridsize)^3 produces a grid that is homogenously filled with values of 1.0. The test will fail if th...
36,757
def get_airflow_config(version, timestamp, major, minor, patch, date, rc): """Return a dict of the configuration for the Pipeline.""" config = dict(AIRFLOW_CONFIG) if version is not None: config['VERSION'] = version else: config['VERSION'] = config['VERSION'].format( major=major, minor=minor, pa...
36,758
def hash(object: Any) -> _int: """ Returns the hash value of the object (if it has one). """
36,759
def joint(absolute: bool = False,angleX: float = 1.0,angleY: float = 1.0,angleZ: float = 1.0,assumePreferredAngles: bool = False,automaticLimits: bool = False,children: bool = False,component: bool = False,degreeOfFreedom: str = "",exists: str = "",limitSwitchX: bool = False,limitSwitchY: bool = False,limitSwitchZ: boo...
36,760
def find_duplicates(treeroot, tbl=None): """ Find duplicate files in a directory. """ dup = {} if tbl is None: tbl = {} os.path.walk(treeroot, file_walker, tbl) for k,v in tbl.items(): if len(v) > 1: dup[k] = v return dup
36,761
def attach_capping(mol1, mol2): """it is connecting all Nterminals with the desired capping Arguments: mol1 {rdKit mol object} -- first molecule to be connected mol2 {rdKit mol object} -- second molecule to be connected - chosen N-capping Returns: rdKit mol object -- mol1 updated (...
36,762
def up(): """Starts Human Lambdas""" html = Path(__file__).parent / "html" html.mkdir(exist_ok=True) html_tgz = Path(__file__).parent / "frontend.tgz" shutil.unpack_archive(html_tgz, extract_dir=html) click.echo("Human Lambdas web running on http://localhost:8000/") gunicorn = Path(sys.exec...
36,763
def setPSF3Dconstraints(psfConstraints, params, bounds): """ Decipher psf3Dconstraints=[constraint] option and set initial guess params and/or bounds accordingly. Each constraint is a string 'n:val' (strict constraint) or 'n:val1,val2' (loose constraint), for n=0 (delta), 1 (theta), 2,3 (position), ...
36,764
def gather_point(input, index): """ **Gather Point Layer** Output is obtained by gathering entries of X indexed by `index` and concatenate them together. .. math:: Out = X[Index] .. code-block:: text Given: X = [[1, 2, 3], [3, 4, 5], [5, 6, 7]] ...
36,765
def _apply_size_dependent_ordering(input_feature, feature_level, block_level, expansion_size, use_explicit_padding, use_native_resize_op): """Applies Size-Dependent-Ordering when resizing feature maps. See https://arxiv.org/abs/1912.01106 ...
36,766
def delete_provisioning_artifact(AcceptLanguage=None, ProductId=None, ProvisioningArtifactId=None): """ Deletes the specified provisioning artifact. This operation will not work on a provisioning artifact associated with a product that has been shared with you, or on the last provisioning artifact associated wi...
36,767
def distance(s1, s2): """Return the Levenshtein distance between strings a and b.""" if len(s1) < len(s2): return distance(s2, s1) # len(s1) >= len(s2) if len(s2) == 0: return len(s1) previous_row = xrange(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] ...
36,768
def check_file_exists(file_name: str) -> None: """ Checks if the file is on the filesystem and readable :param file_name: Name of the file including the path """ if not isfile(file_name): raise FileNotFoundError(f"Cannot find {file_name}. Check if path is correct!")
36,769
def check_diversity(group, L): """check if group satisfy l-diversity """ SA_values = set() for index in group: str_value = list_to_str(gl_data[index][-1], cmp) SA_values.add(str_value) if len(SA_values) >= L: return True return False
36,770
def getEntries(person): """ Fetch a Advogato member's diary and return a dictionary in the form { date : entry, ... } """ parser = DiaryParser() f = urllib.urlopen("http://www.advogato.org/person/%s/diary.xml" % urllib.quote(person)) s = f.read(8192) while s: parser.fe...
36,771
def sum_values(p, K): """ sum the values in ``p`` """ nv = [] for v in itervalues(p): nv = dup_add(nv, v, K) nv.reverse() return nv
36,772
def _run_doxy(doxy_out_dir, doxyINPUT, is_doxy_recursive): """This runs the command "doxygen" on an input and writes the ouput XML files to a temporary directory. """ doxy_file_patterns = " ".join("*.%s" % fil_ext for fil_ext in file_extensions_dox) # TODO: Create a tmp dir just for this purpose. fil_c...
36,773
def create_owner_team_and_permissions(sender, instance, created, **kwargs): """ Signal handler that creates the Owner team and assigns group and user permissions. """ if created: team = Team.objects.create( name=Team.OWNER_TEAM_NAME, organization=instance.user, create...
36,774
def define_permit_price_targeting_constraints(m): """Constraints used to get the absolute difference between the permit price and some target""" # Constraints to minimise difference between permit price and target m.C_PERMIT_PRICE_TARGET_CONSTRAINT_1 = pyo.Constraint( expr=m.V_DUMMY_PERMIT_PRICE_TA...
36,775
def _startsession (ARG_targetfile): """Writes a blank line and a session header to the targetfile. Parameters ---------- ARG_targetfile : any type that open() accepts as a filename Path to the file that should recieve the new session header. """ if os.path.isfile(ARG_targetfile) is Fals...
36,776
def predict4(): """Use Xception to label image""" path = 'static/Images/boxer.jpeg' img = image.load_img(path,target_size=(299,299)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) pclass = decode_predictions(preds, top=5) ...
36,777
def augment_data(image, label, seg_label, perform_random_flip_and_rotate, num_channels, has_seg_labels): """ Image augmentation for training. Applies the following operations: - Horizontally flip the image with probabiliy 0.5 - Vertically flip the image with probability 0.5 ...
36,778
def protobuf_open_channel(channel_name, media_type): """func""" open_channel_request = pb.OpenChannelRequest() open_channel_request.channel_name = channel_name open_channel_request.content_type = media_type return open_channel_request.SerializeToString()
36,779
def cleanup_rollback_complete(self, dryrun, wait): """Predeploy hook to delete last failed deployment.""" if self.status == "ROLLBACK_COMPLETE": logger.info("Deleting stack in ROLLBACK_COMPLETE state.") if not dryrun: self.delete(dryrun, wait)
36,780
async def update_code_example(q: Q): """ Update code example. """ logging.info('Updating code snippet') copy_expando(q.args, q.client) q.page['code_examples'] = cards.code_examples( code_function=q.client.code_function, theme_dark=q.client.theme_dark ) await q.page.sa...
36,781
def action(update, context): """A fun command to send bot actions (typing, record audio, upload photo, etc). Action appears at top of main chat. Done using the /action command.""" bot = context.bot user_id = update.message.from_user.id username = update.message.from_user.name admin = _admin(use...
36,782
def findPartsLists(path): """gets a list of files/folders present in a path""" walkr = os.walk(path) dirlist = [a for a in walkr] #print dirlist expts = [] for fle in dirlist[0][2]: #print fle if(fle[-4:]=='xlsx'): try: xl_file = pd.read_excel(os.path....
36,783
def plot_grid( basis: "numpy.ndarray" = None, supercell_matrix: "numpy.ndarray" = None, Nmax: int = None, **kwargs ): """Plots lattice points of a unit cell.""" axes = plt.gca() basis = basis[:2, :2].copy() a1 = basis[0, :].copy() a2 = basis[1, :].copy() # p = product(range(-Nmax...
36,784
def borehole_vec(x, theta): """Given x and theta, return vector of values.""" (Hu, Ld_Kw, Treff, powparam) = np.split(theta, theta.shape[1], axis=1) (rw, Hl) = np.split(x[:, :-1], 2, axis=1) numer = 2 * np.pi * (Hu - Hl) denom1 = 2 * Ld_Kw / rw ** 2 denom2 = Treff f = ((numer / ((deno...
36,785
def read_datastore(resource_id): """ Retrieves data when the resource is part of the CKAN DataStore. Parameters ---------- resource_id: str Id for resource Returns ---------- pd.DataFrame: Data records in table format """ r = requests.get( DATASTORE_SEA...
36,786
def new_server_session(keys, pin): """Create SRP server session.""" context = SRPContext( "Pair-Setup", str(pin), prime=constants.PRIME_3072, generator=constants.PRIME_3072_GEN, hash_func=hashlib.sha512, bits_salt=128, bits_random=512, ) username, ...
36,787
def lenzi(df): """Check if a pandas series is empty""" return len(df.index) == 0
36,788
def move_pdfs(directory: str = None) -> None: """Move PDF files into the correct directory.""" direc = directory + os.sep if directory is not None else '' pdfs = glob(direc + '*.pdf') for pdf in pdfs: new = direc + 'PDFs' + os.sep + os.path.split(pdf)[-1] try: os.remove(new...
36,789
def check_exists(path): """Check if a directory or a path is at the received path. Arguments: path: The path to check. Returns: Nothing. Raises: RuntimeError: Raised if nothing exists at the received path. """ if path is None: raise RuntimeError("Got None instead of a valid path.") if no...
36,790
def flatten_in(iterable, pred=None): """Like flatten, but recurse also into tuples/lists not matching pred. This makes also those items get the same flattening applied inside them. Example:: is_nested = lambda e: all(isinstance(x, (list, tuple)) for x in e) data = (((1, 2), ((3, 4), (5, 6...
36,791
def m_step(counts, item_classes, psuedo_count): """ Get estimates for the prior class probabilities (p_j) and the error rates (pi_jkl) using MLE with current estimates of true item classes See equations 2.3 and 2.4 in Dawid-Skene (1979) Input: counts: Array of how many times each rating was giv...
36,792
def make_parser(fn: Callable[[], Parser]) -> Parser: """ Make typed parser (required for mypy). """ return generate(fn)
36,793
def ts2date(ctx: 'click.Context', ts: int) -> None: """unix timestampを日付する Args: ctx: click's Context """ click.echo('UTC: {}'.format(time.gmtime(ts))) click.echo('Local: {}'.format(time.localtime(ts)))
36,794
def mfcc_htk(y, sr, hop_length=2**10, window_length=22050, nmfcc=13, n_mels=26, fmax=8000, lifterexp=22): """ Get MFCCs 'the HTK way' with the help of Essentia https://github.com/MTG/essentia/blob/master/src/examples/tutorial/example_mfcc_the_htk_way.py Using all of the default parameters from there exc...
36,795
def num_to_int(num): """ Checks that a numerical value (e.g. returned by robot) is an integer and not a float. Parameters ---------- num : number to check Returns ------- integer : num cast to an integer Raises ------ ValueError : if n is not an integer """ if ...
36,796
def shuffle_blocks(wmx_orig, pop_size=800): """ Shuffles pop_size*pop_size blocks within the martrix :param wmx_orig: original weight matrix :param pop_size: size of the blocks kept together :return: wmx_modified: modified weight matrix """ assert nPCs % pop_size == 0 np.random.seed(123...
36,797
def test_generate_f_file_queries_contracts(database, monkeypatch): """ generate_f_file_queries should provide queries representing halves of F file data related to a submission This will cover contracts records. """ sess = database.session sess.query(Subaward).delete(synchronize_session=False) ...
36,798
def change(): """ Change language """ lang = request.args.get("lang", None) my_id = None if hasattr(g, 'my') and g.my: my_id = g.my['_id'] data = core.languages.change(lang=lang, my_id=my_id) return jsonify(data)
36,799