content
stringlengths
22
815k
id
int64
0
4.91M
def sidak_correction(significance, numtests): """ Sidak correction. TODO: docstring - better explanaition Parameters ---------- significance : float Significance of each individual test. numtests : int The number of hypothesis tests performed. Returns ------- ...
5,308,500
def place_value(value, sample_args, context=None): """E.g., "Q: What is the tens digit of 31859? A: 5.""" del value # unused for now if context is None: context = composition.Context() entropy, sample_args = sample_args.peel() integer = number.integer(entropy, signed=False, min_abs=1) ...
5,308,501
def rep_mat(argin, n, m): """ Ensures 1D result """ return np.squeeze(repmat(argin, n, m))
5,308,502
def value_or_default(value, default=np.nan): """ Returns the given value if it is not none. Otherwise returns the default value. Args: value: The value. default: The default. Returns: Returns the given value if it is not none. Otherwise returns the default value. """ # ...
5,308,503
def type_to_python(typename, size=None): """type_to_python(typename: str, size: str) -> str Transforms a Declarations.yaml type name into a Python type specification as used for type hints. """ typename = typename.replace(' ', '') # normalize spaces, e.g., 'Generator *' # Disambiguate explici...
5,308,504
def build_find_cmd(opts, paths): """ Builds teh cmd file using ctags. Returns cmd based on the following template: 'find {0} -type f {1} | etags -' """ find_args = build_find_args(get_exts(opts)) return ['find']+paths+['-type', 'f']+find_args
5,308,505
def histeq(x, n=1024, dim=None): """Histogram equalization Notes ----- .. The minimum and maximum values of the input tensor are preserved. .. A piecewise linear transform is applied so that the output quantiles match those of a "template" histogram. .. By default, the template histogram...
5,308,506
def _trim_context(lines, context_size): """Trim context lines that don't surround changes from Differ results yields (line, leftnum, rightnum, gap) tuples""" # circular buffer to hold context lines context_buffer = [None] * (context_size or 0) context_start = context_len = 0 # number of context lines lef...
5,308,507
def mc(data): """ Modulus calculation Calculated sqrt(real^2+imag^2) """ return np.sqrt(data.real**2+data.imag**2)
5,308,508
def make_safe_label_value(string): """ Valid label values must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. If the label value is then greater than 63 chars once made s...
5,308,509
def reducePoly(ps): """ Return the basis (e.g., a min subset of ps that implies ps) of the set of eqts input ps using Groebner basis sage: var('a y b q k') (a, y, b, q, k) sage: rs = reducePoly([a*y-b==0,q*y+k-x==0,a*x-a*k-b*q==0]) sage: assert set(rs) == set([a*y - b == 0, q*y + k - x =...
5,308,510
def _get_saver_or_default(): """Returns the saver from SAVERS collection, or creates a default one. This method is used by other members of the training module, such as `Scaffold`, or `CheckpointSaverHook`. Returns: `Saver`. Raises: RuntimeError: If the SAVERS collection already has more than one i...
5,308,511
def GetExecutable(executable, location=None): """Returns the path to the given executable or None if it is not found. This algorithm provides a reasonably accurate determination of whether or not the given executable is on the machine and can be used without knowing its full path. An optional path can be adde...
5,308,512
def Bool(value): """Returns a Boolean constant with the given value. :param value: Specify the value :returns: A Boolean constant with the given value """ return get_env().formula_manager.Bool(value)
5,308,513
def validate_config(config, check_with_data): """ Check that the config passed as argument is a valid configuration. :param config: A config dictionary to fetch. :param check_with_data: Whether we should use the available OpenData to check the config values. :return: ``True`` if the configu...
5,308,514
def get_one_idle_marine(obs): """ check if any idle marine are available :return idle_scv_pos: [x, y], if no, return None """ for unit in obs.observation.feature_units: if unit.unit_type == units.Terran.Marine and int(unit.order_length) == 0: return [unit.x, unit.y] return No...
5,308,515
def create_title_font(name, style_name): """ Defines a paragraph style for titles """ return ParagraphStyle(name, fontName=name, fontSize=TITLE_FONT_SIZE, parent=style[style_name], alignment=ALIGNMENT...
5,308,516
def display_board(board): """Display game board on screen.""" print("\n\t", board[0], "|", board[1], "|", board[2]) print("\t", "---------") print("\t", board[3], "|", board[4], "|", board[5]) print("\t", "---------") print("\t", board[6], "|", board[7], "|", board[8], "\n")
5,308,517
def myfunc_s( step ): """ Function used for the making the computation of overlaps parallel via python multiprocessing """ s_sd = step3.mapping.ovlp_mat_arb( sd_states_reindexed_sorted[step], sd_states_reindexed_sorted[step], S_ks[0][step], use_minimal=False ) #print(step, "s_sd as CMATRIX <1|1...
5,308,518
def get_auc_roc_curve(y_true, y_pred, n_classes, labels=None): """Plot visualization. Parameters ---------- y_true : sparse labels integers y_pred : prediciton probabilities n_classes : number dataset classes labels=None : name of class labels Returns ------- matplotlib.pyplot.Figure """ y_true=(np.eye(n_cl...
5,308,519
def species_download_coding(species_id): """ Generates a fasta file with all coding sequences for a given species :param species_id: Internal ID of the species :return: Response with the fasta file """ output = [] current_species = Species.query.get(species_id) sequences = db.engine.ex...
5,308,520
def check_not_modified(request, last_modified): """Handle 304/If-Modified-Since With Django v1.9.5+ could just use "django.utils.cache.get_conditional_response", but v1.9 is not supported by "logan" dependancy (yet). """ if_modified_since = parse_http_date_safe(request.META.get('HTTP_IF_MODIFIED_S...
5,308,521
def create_action_client(action): """Creates corresponding ROS action client. Args: action: ROS action name. Returns: Corresponding actionlib.SimpleActionClient instance. None if action server not found. """ action_cls = get_action_class(action) client = actionlib.Simpl...
5,308,522
def find_reachable_vertices(g: Graph, sources: set) -> set: """ Returns the set of vertices of a graph which are reachable from a set of source vertices. Args: g: Graph, an instance of `Graph` sources: set, a set of integers representing the source vertices Returns: The set o...
5,308,523
def create_course(): """ Администратор может создать учебный курс, указав его название и текстовое описание. """ answer = blank_resp() try: if current_user.status != 'admin': raise Exception('Only admins can create course') form = CourseForm(request.form) if form.va...
5,308,524
def generate_password(length=16, symbolgroups=DEFAULT_PASSWORD_SYMBOLS): """Generate a random password from the supplied symbol groups. At least one symbol from each group will be included. Unpredictable results if length is less than the number of symbol groups. Believed to be reasonably secure (with...
5,308,525
def colorize(color, text, *, kind='fg'): """ ** Adds the flags that allow to format the color text. ** Parameters ---------- color : str or tuple Either the name of the color in str, or the result of the function ``_str_to_color``. text : str The text to be formatted. ...
5,308,526
def interpret_result(yhati, threshold=0.5): """ :param yhati: result of prediction for a file :return: String: the language """ for i in range(0, len(yhati)): if yhati[i] > threshold: return defs.langs[i]
5,308,527
def _create_debug_sp_tpls_data(sp, tpls, gap_threshold): """Preprocess sp and tpls for "test_generate_trips_*.""" # create table with relevant information from triplegs and staypoints. tpls["type"] = "tripleg" sp["type"] = "staypoint" sp_tpls = sp[ ["started_at", "finished_at", "user_id", "t...
5,308,528
def rewrite_ast(node, name, expr, assumed_result): """ Based on the assumed value of an expression, re-writes the AST tree to constants where possible. """ if name[0] == "CompareOperator": return compare.compare_rewrite(node, name, expr, assumed_result) elif name[0] == "ContainsOperator...
5,308,529
def getMatrixRepresentation(values, shouldTranspose, n, Z, rateNumerator, rateDenominator): """ @param values: a list of strings, ('-' for empty cell). These represent the values @param shouldTranspose: if True, the values are given column by column (first col1 from top to bottom, then co...
5,308,530
def test_graph_custom_x(builddir): """ Test the graph feature """ runner = CliRunner() with patch.dict("os.environ", values=PATCHED_ENV, clear=True): result = runner.invoke( main.cli, ["--path", builddir, "graph", "src/test.py", "raw.loc", "-x", "raw.sloc"], ) ass...
5,308,531
def addItem(item: items.Item) -> None: """ The method for adding an item to the database. This method consumes the Item! Parameters: item (serverLib.items.Item): The item to add to the database. """ if not isinstance(item, items.Item): raise exceptions.InvalidInput # V...
5,308,532
def Install(vm, package_name='python-pip'): """Install pip on the VM.""" vm.InstallPackages(package_name) if vm.PYTHON_PIP_PACKAGE_VERSION: vm.RemoteCommand( 'sudo pip install --upgrade ' '--force-reinstall pip=={0}'.format(vm.PYTHON_PIP_PACKAGE_VERSION)) else: vm.RemoteCommand('sudo pip...
5,308,533
def make_auth_anonymous(): """Format an AUTH command line for the ANONYMOUS mechanism Jeepney's higher-level wrappers don't currently use this mechanism, but third-party code may choose to. See <https://tools.ietf.org/html/rfc4505> for details. """ from . import __version__ trace = hexlify...
5,308,534
def change_volume(delta_volume, category=None): """Changes the volume for all sound objects unless category is specified.""" global SOUNDS if category is None: VOLUME["main"] += delta_volume VOLUME["main"] = max(0, min(VOLUME["main"], 100)) for dictionary in SOUNDS.values(): ...
5,308,535
def cal_s11_1_port_short(model): """This action should select the short class""" commands = { Model.HP_8753D: 'CLASS11B', } return commands.get(model)
5,308,536
def torch_to_np(tensors): """Convert PyTorch tensors to numpy arrays. Args: tensors (tuple): Tuple of data in PyTorch tensors. Returns: tuple[numpy.ndarray]: Tuple of data in numpy arrays. Note: This method is deprecated and now replaced by `metarl.torch._functions.to_numpy`. ...
5,308,537
def select_cycle(data, cycle=-1, min_length=0): """ Select current cycle. Notes ----- Calls automatically :func:`detect_strain_cycles()` if needed. Sets `irange` attribute of `data`. """ if not len(data.cycles): data = detect_strain_cycles(data) data.icycle = cycle try:...
5,308,538
def test_get_status(mock_requests): """Test if get_status() returns a valid status based on mocked data.""" mock_requests.get.return_value.text = """ <stopInfo created="2020-10-28T21:51:58" stop="Ranelagh" stopAbv="RAN"> <message>Green Line services operating normally</message> <...
5,308,539
def wavelet_analysis(signal, p_exp=None, wt_name='db3', j1=1, j2=10, gamint=0.0, normalization=1, weighted=True): # TODO make function for coef only, use it when p_exp is None """ Compute wavelet coefficient and wavelet leaders. Parameters ---------- signal : ndarray, shap...
5,308,540
def welcome(): """List all available api routes.""" return ( f" Hawaii Climate API Surf's Up <br/>" f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start<br/>" f"/api/v1.0/start/end" ...
5,308,541
def transfer(sender, receiver): """ Send datagrams from `sender` to `receiver`. """ datagrams = 0 from_addr = CLIENT_ADDR if sender._is_client else SERVER_ADDR for data, addr in sender.datagrams_to_send(now=time.time()): datagrams += 1 receiver.receive_datagram(data, from_addr, n...
5,308,542
def _rapRperiAxiFindStart(R,E,L,pot,rap=False,startsign=1.): """ NAME: _rapRperiAxiFindStart PURPOSE: Find adequate start or end points to solve for rap and rperi INPUT: R - Galactocentric radius E - energy L - angular momentum pot - potential rap - if Tr...
5,308,543
def beta_divergence(X, Y, b): """ \beta-divergence Parameters: X: NMFで推定したスペクトログラム Y: 真のスペクトログラム(=入力) b: beta-factor Returns: beta-divergenceの値 """ RX,RY = _adjust_vector_dimensions(X, Y) if b == 1: d = (RY*(sp.log(RY+0.00001)-sp.log(RX+0.00001)...
5,308,544
def _tasks_scheduler_config(venv_path, project_config) -> Tuple[List[Dict], List[str]]: """ tasks_scheduler supervisor config """ async_tasks_config = { 'name': 'async_tasks', 'command': f"{venv_path}/bin/python run.py async-tasks", 'directory': project_config['PROJECT_PATH'], '...
5,308,545
def init_loadlimit_router(loadlimit_notation: str = None): """initializes a route where a client (or any other network peer) can inquire what opal clients are currently connected to the server and on what topics are they registered. If the OPAL server does not have statistics enabled, the route will ...
5,308,546
def plot_props(f_infos, results, show_figure=False, write_path=None, ax=None, add_legend=True, ordering=None, cmap=None): """Given results, plot proportions of how often each function as called. Args: f_infos: List of Namespace for function info used. results: Dict method -> List ...
5,308,547
def addfollowers(db, api, uid, force=False): """ Crawl followers using the followers/list api endpoint and populate the follow colloection. Since this endpoint returns user objects, we also add them into the database users collection. """ last = db.lastscan.find_one({'id': uid, 'action': 'followers'}) no...
5,308,548
def draw_lines(img, lines, color=[255, 0, 0], thickness=2): """ NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that...
5,308,549
def getSimilarChars(): """When user runs this script, similar characters file may be provided as one of optional arguments. User creates similar character groups and put each group on a new line in file and separate those character by comma. E.g. ჟ,უ,ქ,ჭ,ჰ so the method can parse this file and creates ...
5,308,550
def sanitize_post_body(body): """ >>> sanitize_post_body(None) '' >>> sanitize_post_body(11) '' >>> sanitize_post_body('#this is a h1') 'this is a h1' >>> sanitize_post_body('```lorem ipsum dolor sit amet``` There are many variations of passages') 'lorem ipsum dolor sit amet Ther...
5,308,551
def test_put_user_to_group(web_server, browser, dbsession, init): """Check that we can assign users to groups in admin interface.""" b = browser from websauna.system.user.models import Group create_logged_in_user(dbsession, init.config.registry, web_server, browser, admin=True) # Create a group ...
5,308,552
def precipite(): """Return a JSON list of precipitations for last 12 months from the dataset.""" #create the session session = Session(engine) # Find the most recent date in the data set. recent_date=session.query(measurement.date).order_by(measurement.date.desc()).first() # Design a query to r...
5,308,553
def validate_components_object(definition_object): """ :param definition_object: """ for k, v in definition_object.items(): if k == "schemas": validate_schema_object(v) continue
5,308,554
def caching_module_getattr(cls): """ Helper decorator for implementing module-level ``__getattr__`` as a class. This decorator must be used at the module toplevel as follows:: @caching_module_getattr class __getattr__: # The class *must* be named ``__getattr__``. @property # ...
5,308,555
def smallDF(numCells: int): """Creates Xarray of a specific # of experiments Zscores all markers per experiment but pSTAT5 normalized over all experiments Outputs amount of experiments and cell types as an Xarray""" # numCells = Amount of cells per experiment flowArrow = pq.read_table("/opt/andrew/F...
5,308,556
def logging(self): """ This method logs the current objective function values """ if self.objFunc is None: raise RuntimeError("Logging method must be executed after compilation method") if self.log is None: self.log = pd.DataFrame(columns=self.objFunc.getFuncs()) self.log.ind...
5,308,557
def test_test_py_ok(style_checker): """Run checker against test.py (OK version) """ move('src/test.py.rename_me-ok', 'src/test_ok.py') p = style_checker.run_style_checker('gps', 'src/test_ok.py') style_checker.assertEqual(p.status, 0, p.image) style_checker.assertRunOutputEmpty(p)
5,308,558
def test_pipeline_requires_stages_definition(tmpdir): """ To create a pipeline, define stages (execution steps). """ class NoStagesPipeline(SafeTestPipeline): pass name = "test-pipe" # Sensitivity: test exception for bad case. with pytest.raises(TypeError): NoStagesPipeline(name=n...
5,308,559
def random(N, prng=None): """Create N p(correct) sampled from a uniform distribution (0-1)""" prng = process_prng(prng) return prng.rand(N), prng
5,308,560
def carregar_dados_site(): """ Abrindo a lista de portais da transparência e tratando informações que serão tratados como NaN para o pandas. """ return rows.import_from_csv("dados/lista_portais.csv")
5,308,561
def min_query(): """Convert sentence to query """ return {'hello', 'world', 'of', 'geek'}
5,308,562
async def setup_comp_0(hass): """Initialize components.""" _setup_sensor(hass, 45) hass.states.async_set(ENT_SWITCH, STATE_OFF) await hass.async_block_till_done() assert await async_setup_component( hass, DOMAIN, { "humidifier": { "platform": "gene...
5,308,563
def format_timedelta(days: int = 0, hours: int = 0, minutes: int = 0, seconds: int = 0) -> str: """Returns a simplified string representation of the given timedelta.""" s = '' if days == 0 else f'{days:d}d' if hours > 0: if len(s) > 0: s += ' ' s += f'{hours:...
5,308,564
def create(organisation_id): """Create a new Role.""" form = RoleForm() organisation = Organisation().get(organisation_id=organisation_id) grades = Grade().list(organisation_id=organisation_id) if grades: form.grade.choices = [(grade["id"], grade["name"]) for grade in grades] practices...
5,308,565
def _try_encode(text, charset): """Attempt to encode using the default charset if none is provided. Should we permit encoding errors?""" if charset: return text.encode(charset) else: return text.encode()
5,308,566
def ones(array_shape: Union[int, Sequence[int]]) -> Array: """Create and fill a shape with ones.""" return full(array_shape, 1.0)
5,308,567
def _fit_curve(fun, x, y, init): """Initial curve fit, without errors.""" fit, cov = scipy.optimize.curve_fit(fun, x, y, p0=init, maxfev=MAX_CURVEFIT_FEV) LOG.info(f"Initial DA fit: {fit} with cov {cov}") return fit, np.sqrt(np.diag(cov))
5,308,568
def init_vocabulary(tax, tax_name, vocab): """init a vocabulary""" for k, term in tax[tax_name].items(): nterm = Term() nterm.identifier = string_as_identifier(term['name']) nterm.description = term['name'] nterm.vocabulary_id = vocab.identifier if term['parents'][0] != ...
5,308,569
def pattern_match(form, token): """ This provides a quick way to extract the contents of a token list, and see if it matches an expected pattern. Variable elements are bound to names in the returned object, to allow for easy retrieval. If the token stream matches: >>> pattern_match(['pointer-t...
5,308,570
def primalDualSeparable_optimize( prob, K=None, z_0=None, stepsize=None, log_freq=None, log_prefix=None, log_init=True, print_freq=None,): """ Algorithm: Primal-Dual algorithm for separable smooth convex-concave minmax problems of the form g(x, y) = f(x) + <y, Ax> - h(y) [THO]: Lifted Primal-Dual Met...
5,308,571
def accuracy(letters, target_string): """ Comparing accuracy to the correct answer. Args: letters(np.array): (num_chars, ) target_string(str) Return: float: accuracy. """ count = 0 assert len(letters) == len(target_string) for i in range(len(target_string)): ...
5,308,572
def update(debug, board, update_all): """Updates related sdkconfig files based on the build directory version that was likely modified by menuconfig.""" board_make = pathlib.Path(f"boards/{board}/mpconfigboard.mk") for line in board_make.read_text().split("\n"): if line.startswith("IDF_TARGET")...
5,308,573
def _lint(definition_filename: str) -> bool: """Lints the provided job definition file.""" if not os.path.isfile(_YAMLLINT_FILE): print(f"! The yamllint file ({_YAMLLINT_FILE}) is missing") return False with open(definition_filename, "rt", encoding="UTF-8") as definition_file: erro...
5,308,574
def make_nda_token(credentials): """ Create NDA token by getting credentials from config file. If no config file exists yet, or user specified to make a new one by entering their NDA credentials as CLI args, then create one to store NDA credentials. :param args: argparse namespace containing all CLI...
5,308,575
def compute_internal_work_compression(form, force): """Compute the work done by the internal compressive forces of a structure. Parameters ---------- form : FormDiagram The form diagram. force : ForceDiagram The force diagram. Returns ------- float The internal ...
5,308,576
def list_(router_generator) -> Callable: """ list action default using fastapi-pagination to process paginate """ resource = router_generator.cls() action_func = getattr(resource, 'list') # noinspection PyProtectedMember,PyShadowingNames,PyUnresolvedReferences def route(request: Request = N...
5,308,577
def WD_shift_kernel(X, Y=None, l = 3, shift_range = 1): """Weighted degree kernel with shifts. Compute the mixed spectrum kernel between X and Y: K(x, y) = \sum_{d = 1}^{l} \sum_j^{L-d} \sum_{s=0 and s+j <= L} beta_d * gamma_j * delta_s * (k_d^{spectrum}(x[j+s:j+s+d],y[j:j+d]) + ...
5,308,578
def _populate_entity(m): """ """ if not m: return None entity = AuthUserEntity(key=get_key_from_resource_id(m.id)) entity.username = m.username entity.first_name = m.first_name entity.last_name = m.last_name entity.email = m.email return entity
5,308,579
async def cringo_card(list_of_emojis: List[List[str]]) -> List[List[str]]: """This makes the Cringo! card complete with headers.""" top_row = ['🇦', '🇧', '🇨', '🇩', '🇪', '🇫'] side_column = ['<:lemonface:623315737796149257>', '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣'] list_of_emojis.insert(0, top_ro...
5,308,580
def get_com_data(ticker=None): """ Loads stock data from yahoo and saves it as .csv for each company """ path = path_to_string(COM_DATA_DIR) if not os.path.exists(path): os.makedirs(path) if ticker is None: tickers = get_tickers() else: tickers = [ticker] start =...
5,308,581
def search_Sequence_Stmt(stmt, node, config, gentype=None): """ Identifying a name in Sequence_Stmt node""" pass
5,308,582
def send_logs(masid: int, log_config: datamodels.LoggerConfig, log_queue: queue.Queue): """ wait for logs in the queue and send them to logger (to be executed in seperate thread) """ log_on = os.environ['CLONEMAP_LOGGING'] if log_on == "ON": while True: log = log_queue.get() ...
5,308,583
def mock_data(): """ Initialize the database.""" faker = Faker() print("Mocking") for i in range(1,100): print(i) user = find_or_create_user(faker.first_name(), faker.last_name(), faker.email(), "Password1") for j in range(0, random.randint(0, 15)): pizza = Pizza( ...
5,308,584
def count(object): """ count(object): Count the number of elements in the given object. An element is defined as one of the 7 datatypes supported by ssdf (dict/struct, tuple/list, array, string, int, float, None). """ n = 1 if isstruct(object) or isinstance(o...
5,308,585
def prepare(desc_file, nocheck_init): """Create and prepare the temporary run directory. The temporary run directory is created with a UUID as its name. Symbolic links are created in the directory to the files and directories specifed to run NEMO. The output of :command:`hg parents` is recorded in ...
5,308,586
def get_http_method(query): """Work out if this should be GET, POST, PUT or DELETE""" lower_query = query.strip().lower() http_method = "GET" for method in METHOD_MAP: if method[0] in lower_query: http_method = method[1] break return http_method
5,308,587
def insert_torch_tensor(obj, parent_grp, obj_name): """funtion to insert a torch tensor as a dataset Arguments: obj {object} -- object to save parent_grp {hdf5 group} -- group where to dump obj_name {str} -- name of the object """ insert_numpy(obj.cpu().detach().numpy(), parent_...
5,308,588
def FlowInterestEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
5,308,589
def add_entities(doctest_namespace: dict[str, object]) -> None: """ Inserts entities into doctest namespaces so that imports don't have to be added to all examples. https://docs.pytest.org/en/stable/doctest.html#doctest-namespace-fixture """ doctest_namespace["Money"] = Money doctest_namespa...
5,308,590
def create_trainable_class(epochs_per_generation=50): """Creates a tuneLFADS class with specified number of epochs per generation. Uses static variable that can be accessed by instances. """ # make epochs_per_generation global so it's visible inside class def global global_epg global_epg = epoch...
5,308,591
def lucky_enough(luck=0): """ Check if you lucky enough. :param luck: should be an int between 0-100 :return: Bool """ return random.randint(0, 99) < luck
5,308,592
def relu(attrs, inputs, proto_obj): """Computes rectified linear function.""" return 'relu', attrs, inputs
5,308,593
def application_type(value): """ Return aiohttp application defined in the value. """ try: module_name, app_name = value.split(":") except ValueError: module_name, app_name = value, "app" module = importlib.import_module(module_name) try: if app_name.endswith("()"): ...
5,308,594
def remote_empty(draw: st.DataObject) -> TemporaryDirectory: """Create an empty git remote repository.""" root = TemporaryDirectory() _run_helper(args=["init", "--bare"], cwd=root.name) return root
5,308,595
def _reformat_stack(stack): """Post processes the stack trace through _relative_path().""" out = stack.splitlines(True) def replace(l): m = re.match(RE_STACK_TRACE_FILE, l, re.DOTALL) if m: groups = list(m.groups()) groups[1] = _relative_path(groups[1]) return ''.join(groups) return ...
5,308,596
def adaboost_predict ( trees, alphas, X ): """ Predict labels for test data using a fitted AdaBoost ensemble of decision trees. # Arguments trees: a list of decision tree dicts alphas: a vector of weights for the trees X: an array of sample data, where rows are samples ...
5,308,597
def check_multiple_insert_param(columns_to_insert, insert_values_dict_lst): """ Checks if the pararmeter passed are of correct order. :param columns_to_insert: :param insert_values_dict_lst: :return: """ column_len = len(columns_to_insert) for row in insert_values_dict_lst: if co...
5,308,598
def KK_RC4(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ return ( Rs + (R_values[0] / (1 + w * 1j * t_values[0])) + (R_values[1] / (1 + w * 1j * t_values[1])) + (R_values[2] / (1...
5,308,599