content
stringlengths
22
815k
id
int64
0
4.91M
def sequence_plus_one(x_init, iter, dtype=int): """ Mathematical sequence: x_n = x_0 + n :param x_init: initial values of the sequence :param iter: iteration until the sequence should be evaluated :param dtype: data type to cast to (either int of float) :return: element at the given iteration a...
5,337,000
def _is_test_product_type(product_type): """Returns whether the given product type is for tests purposes or not.""" return product_type in ( apple_product_type.ui_test_bundle, apple_product_type.unit_test_bundle, )
5,337,001
def legend(labels=[""], handlecolors=[""], handlelength=1, handletextpad=None, loc=None, **kwargs): """ Alias function of plt.legend() with most frequently used parameters. Args: labels (sequence of strings) handlescolors (list) handlelength (None/int/float) handletextpad (N...
5,337,002
def _synced(method, self, args, kwargs): """Underlying synchronized wrapper.""" with self._lock: return method(*args, **kwargs)
5,337,003
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" return meta('NewBase', bases, {})
5,337,004
def team(slug): """The team page. Shows statuses for all users in the team.""" db = get_session(current_app) team = db.query(Team).filter_by(slug=slug).first() if not team: return page_not_found('Team not found.') return render_template( 'status/team.html', team=team, ...
5,337,005
def mask_layer(layer, mask, mask_value = np.nan): """apply a mask to a layer layer[mask == True] = mask_value """ layer[mask] = mask_value return layer
5,337,006
def test_ice_removed(): """ Testing that all ice is removed when gems are matched on top. All gems should match and remove the ice underneath. Grid is 2 by 3. :return: """ print("\nBoard 1:\n") print(b) # ice should be like this ice_grid = [[-1] * columns0 for _ in ran...
5,337,007
def tag_neutron_resources(resources): """Set tags to the provided resources. param resources: list of openstacksdk objects to tag. """ tags = CONF.neutron_defaults.resource_tags if not tags: return os_net = clients.get_network_client() for res in resources: try: ...
5,337,008
def test_rbfed_cpfp_transaction(revault_network, bitcoind): """We don't have explicit RBF logic, but since we signal for it we should be able to replace a previous CPFP with a higher-fee, higher-feerate one. NOTE: we unfortunately can't replace it with one adding new to_be_cpfped transactions as it woul...
5,337,009
def write_batch_list_windows(output_folder, decomb=False): """Write batch file which will encode videos when runt Find videos Build output name Rename file if output exists Encode video Copy Exif data from old video to new Remove old video """ error = " || goto :error" content = ...
5,337,010
def test_get_sig_diffusion(): """ """ fueltype_lookup = { 'solid_fuel': 0, 'gas': 1, 'electricity': 2, 'oil': 3, 'heat_sold': 4, 'biomass': 5, 'hydrogen': 6, 'heat': 7} technologies = { 'boilerA': read_data.TechnologyData( ...
5,337,011
def generate_twitch_clip(user_id): """Generate a Twitch Clip from user's channel. Returns the URL and new clip object on success.""" user = User.get_user_from_id(user_id) twitch_id = str(user.twitch_id) payload_clips = {"broadcaster_id": TEST_ID or twitch_id} # Edit this to test r_clips = r...
5,337,012
def purge(dir, pattern): """ Delete files whose names match a specific pattern. Example: purge("/usr/local/nagios/etc/cfgs/hosts", "^i-.*\.cfg$") equals to rm -rf i-*.cfg :param dir: the directory under which to delete files :param pattern: regex pattern :return: None """ for f in os.lis...
5,337,013
def get_disabled(): """ Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled """ return _get_svc_list(status="DISABLED")
5,337,014
def calling_method(): """ call recursive method :return: list all post 2 days delta-time """ list_posts = list() return create_json_poyload(list_posts)
5,337,015
def check_notifier(notifiers): """Check if the configured notifier really exists.""" notifiers_available = { "syslog": notify_syslog, "pushover": notify_pushover, "mail": notify_mail, "twilio": notify_twilio } notifiers_valid = [] for notifier in notifiers: tr...
5,337,016
def read_json(path): """ Read a BayesNet object from the json format. This format has the ".bn" extension and is completely unique to pyBN. Arguments --------- *path* : a string The file path Returns ------- None Effects ------- - Instantiates and sets a ne...
5,337,017
def solve_primal(run_id, problem, mip_solution, solver): """Solve primal by fixing integer variables and solving the NLP. If the search fails and f `mip_solution` has a solution pool, then also try to find a feasible solution starting at the solution pool points. Parameters ---------- run_id :...
5,337,018
def domain_tokenizer(iterator): """Tokenizer generator. Args: iterator: Input iterator with strings. Yields: array of tokens per each value in the input. """ for value in iterator: yield DOMAIN_TOKENIZER_RE.findall(value)
5,337,019
def SpliceContinuations(tree): """Given a pytree, splice the continuation marker into nodes. Arguments: tree: (pytree.Node) The tree to work on. The tree is modified by this function. """ def RecSplicer(node): """Inserts a continuation marker into the node.""" if isinstance(node, pytree.Leaf...
5,337,020
def rayleigh(flow_resis, air_dens, sound_spd, poros, freq=np.arange(100, 10001, 1)): """ Returns through the Rayleigh Model the Material Charactheristic Impedance and the Material Wave Number. Parameters: ---------- flow_resis : int Resistivity of th...
5,337,021
def test_regress_234(): """Test task_exit checkpointing with fast tasks""" run_race(0)
5,337,022
def set_iam_policy(project_id: str, policy: dict, token: str) -> dict: """Sets the Cloud IAM access control policy for a ServiceAccount. Args: project_id: GCP project ID. policy: IAM policy. token: Access token from the Google Authorization Server. Returns: A dict containin...
5,337,023
def feature_set_is_deployed(db: Session, fset_id: int) -> bool: """ Returns if this feature set is deployed or not :param db: SqlAlchemy Session :param feature_set_id: The Feature Set ID in question :return: True if the feature set is deployed """ d = db.query(models.FeatureSetVersion). \ ...
5,337,024
def test_remove_iid(): """Test if entry with iid is successfully removed.""" iid_manager, obj_a = get_iid_manager() assert iid_manager.remove_iid(0) is None assert iid_manager.remove_iid(1) == obj_a
5,337,025
def main(file_loc, cores=16) -> None: """main. Args: file_loc: cores: Returns: None: """ print(file_loc) files = os.listdir(file_loc) if cores > 1: with Pool(processes=cores) as pool: jobs = [pool.apply_async(func=html_to_txt, args=(f, file_loc)...
5,337,026
def get_retry_request( request: Request, *, spider: Spider, #response: Response, reason: Union[str, Exception] = 'unspecified', max_retry_times: Optional[int] = None, priority_adjust: Optional[int] = None, logger: Logger = retry_logger, stats_base_key: str = 'retry', ): """ R...
5,337,027
async def graf(request: Request): """ Zobrazí graf nameranej charakteristiky """ localtime = time.asctime(time.localtime(time.time())) print("Graf; Čas:", localtime) return templates.TemplateResponse("graf.html", {"request": request, "time": localtime})
5,337,028
def version(): """Show the version of the software.""" from jsub import version as jsub_version click.echo('JSUB version: %s' % jsub_version())
5,337,029
def mapRangeUnclamped(Value, InRangeA, InRangeB, OutRangeA, OutRangeB): """Returns Value mapped from one range into another where the Value is clamped to the Input Range. (e.g. 0.5 normalized from the range 0->1 to 0->50 would result in 25)""" return lerp(OutRangeA, OutRangeB, GetRangePct(InRangeA, InRa...
5,337,030
def folders(request): """Handle creating, retrieving, updating, deleting of folders. """ if request.method == "GET": q = bookshelf_models.Folder.objects.filter(owner=request.user) data = [[e.guid, e.title] for e in q] if request.method == "POST": if "create" in request.POST: ...
5,337,031
def reponame(url, name=None): """ Determine a repo's cloned name from its URL. """ if name is not None: return name name = os.path.basename(url) if name.endswith('.git'): name = name[:-4] return name
5,337,032
def specified_options(opts: argparse.Namespace, exclude=None) -> Dict: """ Cast an argparse Namespace into a dictionary of options. Remove all options that were not specified (equal to None). Arguments: opts: The namespace to cast. exclude: Names of options to exclude from the result. ...
5,337,033
def test_reordering_sequential(sorted_entries_seq): """ Ensures the reordering logic works as expected. This test simply provides sequential sort order values and try to reorder them. """ qs = SortedModel.objects nodes = sorted_entries_seq operations = {nodes[5].pk: -1, nodes[2].pk: +3} ...
5,337,034
def Sort_list_by_Prism_and_Date(lst): """ Argument: - A list containing the prism name, position of recording, decimal year, position and meteo corrected position for each prism. Return: - A list containing lists of prisms sorted by name and date. """ #text must be a converted GKA fil...
5,337,035
def log(message: str) -> Generator: """指定したメッセージ付きで開始と終了のログを出力するコンテキストマネージャを返します。 >>> with log('hello'): ... print('world') START: hello world END: hello :type message: str :param message: メッセージ :rtype: typing.Generator :return: コンテキストマネージャ """ print(f'START: {messa...
5,337,036
def MostrarRaices(raizBiseccion, raizNewton, raizNewtonModificado, raizSecante, tolerancia): """ Mostrara por pantalla las raices obtenidas dependiendo de los dos tipos distintos de tolerancia. Si no se obtuvo raiz durante su busqueda, se mostrara un mensaje indicando el metodo que fallo """ if tole...
5,337,037
def _convert_to_RVector(value, force_Rvec=True): """ Convert a value or list into an R vector of the appropriate type. Parameters ---------- value : numeric or str, or list of numeric or str Value to be converted. force_Rvec : bool, default True If `value` is not a...
5,337,038
def submit(expression): """ Update the plotted function to the new math *expression*. *expression* is a string using "t" as its independent variable, e.g. "t ** 3". """ ydata = eval(expression) l.set_ydata(ydata) ax.relim() ax.autoscale_view() plt.draw()
5,337,039
def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) temp=e_x / e_x.sum(axis=0) # only difference if np.isnan(temp).any()==True: return [0.0,1.0,0.0] else: return temp
5,337,040
def fetch_events_art_history(base_url='https://www.sas.upenn.edu'): """ Fetch events from Art History Department """ page = requests.get(urljoin(base_url, '/arthistory/events')) page_soup = BeautifulSoup(page.content, 'html.parser') range_pages = max([int(n_page.text) for n_page in page_soup.fin...
5,337,041
def calc_Q(nu=0.0,delta=0.0,lam=1.0,ret_k=False): """ Calculate psic Q in the cartesian lab frame. nu and delta are in degrees, lam is in angstroms if ret_k == True return tuple -> (Q,ki,kr) """ (ki,kr) = calc_kvecs(nu=nu,delta=delta,lam=lam) Q = kr - ki if ret_k == True: ...
5,337,042
def build_data(args): """ build test data """ task_name = args.task_name.lower() processor = reader.MatchProcessor(data_dir=args.data_dir, task_name=task_name, vocab_path=args.vocab_path, ...
5,337,043
def _generate_index(): """Helper function to generate the index page from `main_readme.rst`""" with codecs.open('main_readme.rst', 'r', encoding='utf-8', errors='ignore') as f: main_readme = f.read() index_rst = '' index_rst += '.. Syncurity SDK documentation master file, created by\n' inde...
5,337,044
def load(config_path = None, config_files = None, state_path = "~/.tcf", ignore_ssl = True): """Load the TCF Library configuration This is needed before you can access from your client program any other module. :param config_path: list of strings containing UNIX-style paths (DIR:DIR) ...
5,337,045
def main(): """Main entry point.""" instance = generative_model.CreateInstanceFromFlags() with tempfile.TemporaryDirectory(prefix="deeplearning_clgen_docker_") as d: ExportInstance(instance, pathlib.Path(d), FLAGS.docker_base_image) subprocess.check_call(["docker", "build", d])
5,337,046
def before_example(scenario, outline, steps): """Record the "before example" event.""" record_event('example', '{') record_example_event('before', scenario, outline, steps) record_event('types', 'before example')
5,337,047
def format_date(d): """Date format used in the report.""" if type(d) == str: d = dateutil_parse(d) return d.isoformat()
5,337,048
def pytorch_argmax(op): """Implementation of argmax for pytorch.""" def _impl(x, dim): dim = tuple(sorted(dim)) n = () for _s in range(len(x.shape)): if _s not in dim: n = n + (_s,) n = n + dim x = x.permute(n) ns = x.shape[0 : -len(di...
5,337,049
def apply_rows(applicators, rows): """ Yield rows after applying the applicator functions to them. Applicators are simple unary functions that return a value, and that value is stored in the yielded row. E.g. `row[col] = applicator(row[col])`. These are useful to, e.g., cast strings to numeric ...
5,337,050
def merge_databases(parent_db, other): """Merge ``other`` into ``parent_db``, including updating exchanges. All databases must be SQLite databases. ``parent_db`` and ``other`` should be the names of databases. Doesn't return anything.""" from . import databases from .backends import ( ...
5,337,051
def get_wine_quality(num_rows=None): """ Wine Quality dataset from UCI repository ( https://archive.ics.uci.edu/ml/datasets/Wine+Quality Using the white wine data set, not the red. - Dimensions: 4898 rows, 12 columns. - Task: Regression :param num_rows: :return: X,y """ filenam...
5,337,052
def _check_not_matrix(**kwargs): """ If any value in *kwargs* is a `np.matrix`, raise a TypeError with the key name in its message. """ for k, v in kwargs.items(): if isinstance(v, np.matrix): raise TypeError(f"Argument {k!r} cannot be a np.matrix")
5,337,053
def parse_eos(eos): """Function to interpret input as an EOS""" if hasattr(eos, 'asq_of_rho_p'): return eos # already is EOS class if eos == 'H' or eos == 'h': return SimpleHydrogen() try: return Ideal(float(eos)) # try parsing as a gamma value except ValueError: ra...
5,337,054
def get_2D_hse_kpoints(struct_for_path, ibzkpth): """ Args: struct_for_path: Structure from which linemode k-points will be generated. ibzkpth: Returns: the Kpoints file object in the form of a string ready for execution by MPInterfaces calibr...
5,337,055
async def verify(context: Context) -> List[ImageSourceVerifyImageSignatures]: """Verifies an image(s).""" results = [] ctx = get_context_object(context) try: results = await _verify(ctx) except Exception as exception: # pylint: disable=broad-except if ctx["verbosity"] > 0: ...
5,337,056
def read_cache(logger: logging.Logger, cache_file: str) -> CachedData: """Read file with Py pickle in it.""" if not cache_file: return CachedData() if not os.path.exists(cache_file): logger.warning("Cache file '%s' doesn't exist.", cache_file) return CachedData() with open(cach...
5,337,057
def neutralize(word, g, word_to_vec_map): """ Removes the bias of "word" by projecting it on the space orthogonal to the bias axis. This function ensures that gender neutral words are zero in the gender subspace. Arguments: word -- string indicating the word to debias g -- numpy-array o...
5,337,058
def loadRowCluster(ndPage,algo): """ load cluster algo = aglo """ xpCluster = f".//Cluster[@algo='{algo}']" lClusters= ndPage.xpath(xpCluster) return lClusters
5,337,059
def _elementwise(f): """ Enables elementwise operations The wrapper implements two different modes of argument evaluation for given p_1,..., p_k that represent the predicted distributions and and x_1,...,x_m that represent the values to evaluate them on. "elementwise" (default): Repeat the sequenc...
5,337,060
def is_valid_task_id(task_id): """ Return False if task ID is not valid. """ parts = task_id.split('-') if len(parts) == 5 and [len(i) for i in parts[1:]] == [8, 4, 4, 4]: tp = RE_TASK_PREFIX.split(parts[0]) return (len(tp) == 5 and all(i.isdigit() for i in tp[::2])...
5,337,061
def setlocale(newlocale): """Set the locale""" try: locale.setlocale(locale.LC_ALL, newlocale) except AttributeError: # locale is None pass # it looks like some stuff isn't initialised yet when this is called the # first time and its init gets the locale settings from the environmen...
5,337,062
def figure_14_9(): """Return the unweighted, undirected graph from Figure 14.9 of DSAP. This is the same graph as in Figure 14.10. """ E = ( ('A', 'B'), ('A', 'E'), ('A', 'F'), ('B', 'C'), ('B', 'F'), ('C', 'D'), ('C', 'G'), ('D', 'G'), ('D', 'H'), ('E', 'F'), ('E', 'I'), ('F' 'I'), ('G', 'J'), ('G',...
5,337,063
def audit_umbrelladns(networks_fwrules): """Accepts a list of firewall rules for a client Checks for rules to allow DNS lookups to Umbrella and deny all other DNS lookups. Returns a list of clients and a boolean of whether Umbrella DNS is configured properly""" umbrelladns_audit = [] host1 =...
5,337,064
def _type_is_valid(policy_type_id): """ check that a type is valid """ if SDL.get(A1NS, _generate_type_key(policy_type_id)) is None: raise PolicyTypeNotFound(policy_type_id)
5,337,065
def test_check_metadata_unique_full_name_values(): """ METADATA.pb: check if fonts field only has unique "full_name" values. """ check = CheckTester(googlefonts_profile, "com.google.fonts/check/metadata/unique_full_name_values") # Our reference FamilySans family is good: font = ...
5,337,066
def convert_samples_library(c, lib_ids): """ Change Library ID in samples_library_tags table """ c.execute('alter table samples_library rename to old_samples_library') c.execute('''CREATE TABLE "samples_library" ( "id" varchar(10) NOT NULL PRIMARY KEY, "library_name" varchar(100) NOT NULL UN...
5,337,067
def parse_element_container(elem: ET.Element) -> Tuple[Types.FlexElement, ...]: """Parse XML element container into FlexElement subclass instances. """ tag = elem.tag if tag == "FxPositions": # <FxPositions> contains an <FxLots> wrapper per currency. # Element structure here is: ...
5,337,068
def _is_smooth_across_dateline(mid_lat, transform, rtransform, eps): """ test whether the CRS is smooth over the dateline idea borrowed from IsAntimeridianProjToWGS84 with minor mods... """ left_of_dt_x, left_of_dt_y, _ = rtransform.TransformPoint(180-eps, mid_lat) right_of_dt_x, right_of_dt_y, ...
5,337,069
def build_frame_csvs_airsim(loader, save_path): """ @params: [loader (obj)] @returns: None Takes data from loader and compiles it into csv frames for training TODO: CURRENTLY DOES NOT WORK WITH CARLA """ fn_train = os.path.abspath('./datasets/{}'.format(save_path)) unique_poses = np.uni...
5,337,070
def reverse_args(func: Func) -> fn: """ Creates a function that invokes func with the positional arguments order reversed. Examples: >>> concat = sk.reverse_args(lambda x, y, z: x + y + z) >>> concat("a", "b", "c") 'cba' """ func = to_callable(func) return fn(lambda ...
5,337,071
def ar(x, y, z): """Offset arange by z/2.""" return z / 2 + np.arange(x, y, z, dtype='float')
5,337,072
def cli(profile, region, table, properties,primary): """DynamoDB properties removal Tool.""" count = dynamodb.scan_table_and_remove(profile, region, table, properties,primary) print("{} records updated".format(count))
5,337,073
def conv_node(command,comm): """ This function converts values from one unit to another unit. This function requires the 'pint' module. For this function to work, the input should be of the from '!conv(unit_1,unit_2)'. """ print "conv_node" print command #To get re.search to wark, I'll ...
5,337,074
def dot(inputs, axes, normalize=False, **kwargs): """Functional interface to the `Dot` layer. Args: inputs: A list of input tensors (at least 2). axes: Integer or tuple of integers, axis or axes along which to take the dot product. normalize: Whether to L2-normalize samples along the ...
5,337,075
def delete_queue(name, region, opts=None, user=None): """ Deletes a queue in the region. name Name of the SQS queue to deletes region Name of the region to delete the queue from opts : None Any additional options to add to the command line user : None Run hg as...
5,337,076
def get_all_methods(klass): """Get all method members (regular, static, class method). """ if not inspect.isclass(klass): raise ValueError pairs = list() for attr, value in inspect.getmembers( klass, lambda x: inspect.isroutine(x)): if not (attr.startswith("__") or attr....
5,337,077
def _suffix_directory(key: pathlib.Path): """Converts '/folder/.../folder/folder/folder' into 'folder/folder'""" key = pathlib.Path(key) shapenet_folder = key.parent.parent key = key.relative_to(shapenet_folder) return key
5,337,078
def setDesktop( studyID ): """This method sets and returns TRUST_PLOT2D desktop""" global moduleDesktop, desktop if studyID not in moduleDesktop: moduleDesktop[studyID] = DynamicDesktop( sgPyQt ) moduleDesktop[studyID].initialize() desktop = moduleDesktop[studyID] return desktop
5,337,079
def load(file_path: str): """Used for loading dataset files that have been downloaded. Args: file_path: Path to file to be loaded. Returns: x: Data used to train models. y: Dataset labels. Example: >>> data,labels = load("model/mnist.npz") >>> # Prin...
5,337,080
def xrefchar(*args): """ xrefchar(xrtype) -> char Get character describing the xref type. @param xrtype: combination of Cross-Reference type flags and a cref_t of dref_t value (C++: char) """ return _ida_xref.xrefchar(*args)
5,337,081
def problem_5_14_8(scalars, vectors): """ >>> u = list2vec([1,1,0,0]) >>> v = list2vec([0,1,1,0]) >>> w = list2vec([0,0,1,1]) >>> x = list2vec([1,0,0,1]) >>> problem_5_14_8([1, -1, 1], [u, v, w]) == x True >>> problem_5_14_8([-1, 1, 1], [u, v, x]) == w True >>> problem_5_14_8([1,...
5,337,082
def atomic(fn, self, *args, **kwargs): """ Atomic method. """ return self._atom(fn, args, kwargs)
5,337,083
def cal_loss(images): """ break it down into training steps. Args: images: input images. """ generated_images = generator(noise, training=False) real_output = discriminator(images, training=False) fake_output = discriminator(generated_images, training=False) gen_loss = generator_loss(fake_output) ...
5,337,084
def test_run_helloworld_sync_error(sync_service): """Execute the helloworld example with erroneous command.""" # -- Setup ---------------------------------------------------------------- # # Start a new run for the workflow template. with sync_service() as api: workflow_id = create_workflow(...
5,337,085
def log_param(key, value): """ Log a parameter under the current run, creating a run if necessary. :param key: Parameter name (string) :param value: Parameter value (string, but will be string-ified if not) """ run_id = _get_or_start_run().info.run_uuid MlflowClient().log_param(run_id, key,...
5,337,086
def check_dynamic_fields(conn, concurrently, dataset_filter, excluded_field_names, fields, name, rebuild_indexes=False, rebuild_view=False): """ Check that we have expected indexes and views for the given fields """ # If this type has time/space fields, create composite indexes...
5,337,087
def set_dict_if_set(_dest, _attribute, _value): """Set a dict attribute if value is set""" if _value is not None: _dest[_attribute] = _value
5,337,088
def main(mode="output", device_id=None): """Run a Midi example Arguments: mode - if 'output' run a midi keyboard output example 'input' run a midi event logger input example 'list' list available midi devices (default 'output') device_id - midi device number; if N...
5,337,089
def default_configuration(log_file=None): """Basic all-encompassing configuration used in tests and handlers. Raises: PermissionDenied if the log file is not writable """ global _new_handler reset_configuration() # We must have a log file available. if not log_file and not _root_l...
5,337,090
def text_to_string(filename, useEncoding): """Read a text file and return a string.""" with open(filename, encoding=useEncoding, errors='ignore') as infile: return infile.read()
5,337,091
def forward_propagation(x, paras, bn_paras, decay=0.9): """ forward propagation function Paras ------------------------------------ x: input dataset, of shape (input size, number of examples) W: weight matrix of shape (size of current layer, size of previous layer) b: bias vec...
5,337,092
def sentence_indexes_for_fragment(fragment: Fragment, sentences: list) -> list: """Get the start and end indexes in the whole article for the sentences encompassing a fragment.""" start_sentence_index = sentence_index_for_fragment_index(fragment.start, sentences) end_sentence_index = sentence_index_for_frag...
5,337,093
def _watchos_extension_impl(ctx): """Implementation of watchos_extension.""" top_level_attrs = [ "app_icons", "strings", "resources", ] # Xcode 11 requires this flag to be passed to the linker, but it is not accepted by earlier # versions. # TODO(min(Xcode) >= 11): Make ...
5,337,094
def train_and_eval(trial: optuna.Trial, ex_dir: str, seed: [int, None]): """ Objective function for the Optuna `Study` to maximize. .. note:: Optuna expects only the `trial` argument, thus we use `functools.partial` to sneak in custom arguments. :param trial: Optuna Trial object for hyper-para...
5,337,095
def print_good(string, **kwargs): """print string in green """ okgreen = '\033[92m' reset = '\033[39m' print(okgreen + string + reset, **kwargs)
5,337,096
def alert_query(alert, authz): """Construct a search query to find new matching entities and documents for a particular alert. Update handling is done via a timestamp of the latest known result.""" # Many users have bookmarked complex queries, otherwise we'd use a # precise match query. query = ...
5,337,097
def iscomment(s): """ Define what we call a comment in MontePython chain files """ return s.startswith('#')
5,337,098
def convert_embeddings(srcPath, dstPath): """ :param srcPath: path of source embeddings :param dstPath: path of output """ vocab = {} id = 0 wrongCnt = 0 with open(srcPath, 'r', encoding='utf-8') as fin: lines = fin.readlines() wordNums = len(lines) line = lines[0...
5,337,099