content
stringlengths
22
815k
id
int64
0
4.91M
def ring_substituents(gra): """ Determine substituent groups on a ring to produce a graph of graphs where the top level key of a ring_gra is the order of the atm keys that define the ring aka (a1, a2, a3, a4, a5, a6) a1 is the 0th position of the ring so a3-a5 have a 1-3 in...
5,299,000
def test_gradient_descent(): """Test of `GradientDescent`.""" gd = GradientDescent(iterations=1) X = np.array([[1]]) y = np.array([[2]]) gd.build(lambda X, y, theta: theta, lambda X, y, theta: theta) assert gd(X, y) == np.zeros(1)
5,299,001
def matchnocase(word, vocab): """ Match a word to a vocabulary while ignoring case :param word: Word to try to match :param vocab: Valid vocabulary :return: >>> matchnocase('mary', {'Alice', 'Bob', 'Mary'}) 'Mary' """ lword = word.lower() listvocab = list(vocab) # this trick catc...
5,299,002
def validate_export_data_coco( project: RBProject, tasks: Dict[str, Dict], groundtruth_task_ids: List[str] ) -> None: """Export and validate test data for coco format.""" # All tasks exported_data = project.export.coco_format(False) assert len(exported_data["images"]) == len(tasks) validate_coco...
5,299,003
def kmeans_rand(hmm, X): """ Helper function for use in HiddenMarkovModel.fit(...). This method accepts an hmm and packed data. It randomly initializes the parameters using the init_params_random(), then it sets the sentroids using the kmean algorithm. Note, this function only works if the states a...
5,299,004
def table_start_fn(ctx, token): """Handler for table start token "{|".""" if ctx.pre_parse: return text_fn(ctx, token) close_begline_lists(ctx) _parser_push(ctx, NodeKind.TABLE)
5,299,005
def theory_atom(s: str, mode: int=0) -> AST: """ Convert string to theory term. """ if mode==2: v = Extractor(parse=True) else: v = Extractor() def visit(stm): v(stm) if mode==0 or mode==2: clingo.ast.parse_string(f"{s}.", visit) elif mode==1: cl...
5,299,006
def train_non_parametric_filter(nb_epochs, train_input, train_target, e, edge, f, gamma=1e-6, alter_thresh = False): """ Training process to learn a non parametric filter. Attributes: - nb_epochs : Number of epochs to train - train_input : Initial filtered signal ...
5,299,007
def read_cobs(years=('2020'), comet=None, start=None, stop=None, allowed_methods=('S', 'B', 'M', 'I', 'E', 'Z', 'V', 'O'),): """Returns a `CometObservations` instance containing the COBS database.""" if years == 'all': years = tuple(range(2018, 2020)) # Read the data data = [] ...
5,299,008
def Position( line: _PrimitiveLineCharNumber, character: Optional[_CharNumberOrMarker] = None, *, _default_character: _CharNumberOrMarker = CharNumber(0), ) -> typing.Position: """ Returns a [Position](https://microsoft.github.io/language-server-protocol/specification#position) object for a ...
5,299,009
def notify_refurbished_product_available( event: events.RefurbishedProductAvailable, uow: UnitOfWork, context: Dict[str, Any], ): """Notify the event in a Slack channel""" text = f"\nFound {len(event.products)} {event.product}(s):\n\n" for p in event.products: if p.savings_price == 0: ...
5,299,010
def get_first_timestamp(log_file, search_text): """Get the first timestamp of `search_text' in the log_file Args: log_file search_text (str) Returns: timestamp: datetime object """ timestamp = None with open(log_file, "r") as f: content = [next(f) for x in range...
5,299,011
def velocity_r(trk, t_vel, r, on=True): """Randomly change the velocity of a note in a track""" time = 0 j = 0 c_t_vel = t_vel[j][0] if on: msg_t = "note_on" else: msg_t = "note_off" for msg in trk: if msg.type == msg_t: r_mod = c_t_vel*r msg.v...
5,299,012
def test_construct_time_context_aware_series(time_df3): """Unit test for `construct_time_context_aware_series`""" # Series without 'time' index will result in a MultiIndex with 'time' df = time_df3 expected = df['value'] time_index = pd.Index(df['time']) expected.index = pd.MultiIndex.from_array...
5,299,013
def samples2metadata_local(samples: List[str], config: dict) -> dict: """ """ sampledict = dict() for sample in samples: if os.path.exists(expand(f'{{fastq_dir}}/{sample}.{{fqsuffix}}.gz', **config)[0]): sampledict[sample] = dict() sampledict[sample]["layout"] = "SINGLE"...
5,299,014
def beinflumatred(infl_mat): """ Calculate a reduced influence coefficient matrix from a complete influence coefficient matrix. Parameters ---------- infl_mat: ndarray The complete influence coefficient matrix. Returns ------- reduced_infl_mat: ndarray The reduced ...
5,299,015
def get_fetaure_names(df, feature_name_substring) : """ Returns the list of features with name matching 'feature_name_substring' """ return [col_name for col_name in df.columns if col_name.find(feature_name_substring) != -1]
5,299,016
def test_flat_age_prior_weights(): """ Test for flat age prior """ log_age = np.array([6.0, 7.0, 8.0, 9.0, 10.0]) log_age_prior_model = {"name": "flat"} log_age_prior = compute_age_prior_weights(log_age, log_age_prior_model) expected_log_age_prior = [1, 1, 1, 1, 1] np.testing.assert_allc...
5,299,017
def load_data_from_experiment_root_dir(path, str_filter='/*/*/*/*/args.json', original_args=False, target_fn=None, use_hash=False, sort_best_model_fn=None): """Entry point of almost all experiments reader Here we load the full statistics of a given experiment. Parameters ---------- p...
5,299,018
def SLessBA(target, weight, poses, disps, intrinsics, ii, jj, fixedp=1): """ Structureless Bundle Adjustment """ pass
5,299,019
def gaussian_1st_deriv(sigma, t, amplitude=1, plot=False): """ Basic gaussian pulse with units in time std_time is the standard deviation of the pulse with units of t Example ------- Example 1:: dt=1e-9 t=np.arange(0,0.001+dt/2,dt) t-=t.mean() std_time=1e-4 s=gaussian_1st_deriv(sigma = std_time, ...
5,299,020
def ISNUMBER(value): """ Checks whether a value is a number. >>> ISNUMBER(17) True >>> ISNUMBER(-123.123423) True >>> ISNUMBER(False) True >>> ISNUMBER(float('nan')) True >>> ISNUMBER(float('inf')) True >>> ISNUMBER('17') False >>> ISNUMBER(None) False >>> ISNUMBER(datetime.date(2011,...
5,299,021
def git_tag_now(prefix): """Tag the current branch HEAD with a timestamp""" import datetime assert hasattr(env, 'project_path') with _cd_project_root(): run('git tag %s-%s' % (prefix, datetime.datetime.now().strftime('-%Y-%m-%d-%H-%M-%S')))
5,299,022
def pearson_transform( matrix: ExpMatrix, min_exp_thresh: float = 0.001) -> ExpMatrix: """Uses pearson residuals to stabilize variance.""" invalid_errstate = 'warn' if np.issubdtype(matrix.values.dtype, np.float32): if np.amin(matrix.values) >= 0: invalid_errstate = 'ignore' ...
5,299,023
def get_domains_for_ip(ip): """ Get the list of domains associated with an IP address. :param ip: :return: """ return __scraper.run(ip)
5,299,024
def sharesnet18(**kwargs): """ ShaResNet-18 model from 'ShaResNet: reducing residual network parameter number by sharing weights,' https://arxiv.org/abs/1702.08782. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, ...
5,299,025
def dgraph2adjacency(dgraph: nx.DiGraph) -> np.ndarray: """Gets the dense adjancency matrix from the graph. Args: dgraph: Directed graph to compute its adjancency matrix. Returns: Adjacency matrix of the given dgraph in dense format (np.array(n * n)). Raises: None. """ ...
5,299,026
def format_meters(cm): """Returns an example user-input meters string.""" if cm < 100: return format_cm(100) m = cm // 100 cm_part = format_cm(cm % 100) suffixes = ["meters", "metres", "m", "ms"] suffix = random.choice(suffixes) spacing_1 = random.randrange(3)*" " spacing_2 = random.randrange(3)*" ...
5,299,027
def convert_atts_to_list_of_quats(atts): """Convert ``atts`` to a flat list of Quat objects Parameters ---------- atts : Quat, list Attitudes Returns ------- list Flat list of Quat objects """ if isinstance(atts, Quat): out = [Quat(q) for q in atts.q.reshape...
5,299,028
def process_evaluation_epoch(global_vars: dict, eval_metric=None, tag=None): """ Calculates the aggregated loss and WER across the entire evaluation dataset """ eloss = torch.mean(torch.stack(global_vars['EvalLoss'])).item() hypotheses = global_vars['predictions'] references = global_vars['trans...
5,299,029
def create_macosx_export_file(export_file, functions_list): """ Creates MacOSX export file :param export_file: object that is returned by open function :param functions_list: list of functions for dynamic library """ export_file.writelines(map(lambda x: '_' + x + '\n', functions_list))
5,299,030
async def list_pop_communities(context, limit:int=25): """List communities by new subscriber count. Returns lite community list.""" limit = valid_limit(limit, 25, 25) sql = "SELECT * FROM bridge_list_pop_communities( (:limit)::INT )" out = await context['db'].query_all(sql, limit=limit) return [(r[...
5,299,031
def api_methods(): """ API symbols that should be available to users upon module import. """ return { 'point', 'scalar', 'scl', 'rnd', 'inv', 'smu', 'pnt', 'bas', 'mul', 'add', 'sub' }
5,299,032
def fly_scan_with_camera(name: str, comment: str, n_cycles: int = 1, delay: float = 0, **kwargs): """ Trajectory Scan - Runs the monochromator along the trajectory that is previously loaded in the controller N times Parameters ---------- name : str Name of the scan - it will be stored in th...
5,299,033
def geo_rescore(pid, model, method): """Apply geographic rescoring.""" logging.info(str((pid, model, method))) session = SESSION() try: numpy.seterr(all='raise') session.query(Model) \ .filter_by(filename=model) \ .one() nms_method = scores.METHODS[meth...
5,299,034
def is_prime(n): """Determine if input number is prime number Args: n(int): input number Return: true or false(bool): """ for curr_num in range(2, n): # if input is evenly divisible by the current number if n % curr_num == 0: # print("current num:", curr_n...
5,299,035
def test_event_subscribe(http_server): """Events exposed in an HTTP server can be subscribed to with an HTTP GET request.""" exposed_thing = next(http_server.exposed_things) event_name = next(six.iterkeys(exposed_thing.thing.events)) href = _get_event_observe_href(exposed_thing, event_name, http_server...
5,299,036
def create_agent_runner_fixture(agent_path, agent_name, args=None): """Create a pytest fixture for running a given OCS Agent. Parameters: agent_path (str): Relative path to Agent, i.e. '../agents/fake_data/fake_data_agent.py' agent_name (str): Short, unique name for the agent ...
5,299,037
def remove_pycache(c, src = root): """ search for `__pycache__` directories and delete them :param c: :param path: path to start searching :return: """ if src is None: src = str(root) c.run("find {} -name __pycache__ -type d -print0 | sudo xargs -0 /bin/rm -fr".format(src))
5,299,038
def add_navigators(path_to_notes: str = None, core_navigators: list = None, show_nb_title_in_nav: bool = True, show_index_in_nav: bool = True) -> None: """Adds navigators to each notebook in the collection. Adds top and bottom navigators to each notebook...
5,299,039
def test_igw_attach_bad_vpc_boto3(): """ internet gateway fail to attach w/ bad vpc """ ec2 = boto3.resource("ec2", "us-west-1") igw = ec2.create_internet_gateway() with pytest.raises(ClientError) as ex: igw.attach_to_vpc(VpcId=BAD_VPC) ex.value.response["ResponseMetadata"]["HTTPStatusCode"...
5,299,040
def test_identify_s3_url_for_dataset_version(temp_config, dataset_name, dataset_version, dataset_backend, expected_url): """ GIVEN: A temporary config, a dataset name, version, backend, and expected url WHEN: The assets url is pulled from the path factory with these parameters THEN: The expected url sho...
5,299,041
def limpatv(par): """ #### Função para limpar a tela da TreeView antes de mostrar os dados :param par: informa o nome da TreeView """ treev = par treev.delete(*treev.get_children()) """ * OU: for i in treev.get_children(): treev.delete(i) """
5,299,042
def q2m(q): """ Find the rotation matrix corresponding to a specified unit quaternion. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/q2m_c.html :param q: A unit quaternion. :type q: 4-Element Array of floats :return: A rotation matrix corresponding to q :rtype: 3x3-Element Array ...
5,299,043
def eval_multiple(exprs,**kwargs): """Given a list of expressions, and keyword arguments that set variable values, returns a list of the evaluations of the expressions. This can leverage common subexpressions in exprs to speed up running times compared to multiple eval() calls. """ for e in exp...
5,299,044
def test_trending(): """ Quick trending test for claims with different support patterns. Actually use the run() function. """ # Create a fake "claims.db" for testing # pylint: disable=I1101 dbc = apsw.Connection(":memory:") db = dbc.cursor() # Create table db.execute(""" ...
5,299,045
def create_user(**params): # **: dynamic list of arguments. # we can basically add as many arguments as we want """Helper function to create new user that you're testing with""" return get_user_model().objects.create_user(**params)
5,299,046
async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ bomcon = BOMConnectivity() # breakpoint() if not await bomcon.check_station(data[CONF_ZONE], data[CONF_WMO]): ...
5,299,047
def inner_loop_function(model, config): """ Execute single cross-validation trial """ test_set, ds = config tic = time.time() df = execute_gluonts_dataframe(model, ds, test_set ) res = execute_gluonts_json(df) toc = time.time() res['time'] = toc-tic return df, res
5,299,048
def findSEH(modulecriteria={},criteria={}): """ Performs a search for pointers to gain code execution in a SEH overwrite exploit Arguments: modulecriteria - dictionary with criteria modules need to comply with. Default settings are : ignore aslr, rebase and safeseh protected modules criteria - d...
5,299,049
def _to_instruction(idl_ix: _IdlInstruction, args: Tuple) -> Instruction: """Convert an IDL instruction and arguments to an Instruction object. Args: idl_ix: The IDL instruction object. args: The instruction arguments. Raises: ValueError: If the incorrect number of arguments is pro...
5,299,050
def sample_coordinates(mask, num_train_vols, num_val_vols, vol_dims=(96, 96, 96)): """ Sample random coordinates for train and validation volumes. The train and validation volumes will not overlap. The volumes are only sampled from foreground regions in the mask. Parameters ---------- mask...
5,299,051
def get_deformation( screw_axis, # Rotation params. with_rotation = True, fix_axis_vertical = False, # Scaling params. with_isotropic_scaling = False, min_scale = 0.5, max_scale = 1.5, ): """Get screw axis encoding of per-point rigid transformation. Args: screw_axis: [*batch, 6]...
5,299,052
def load_component_entity_from_yaml( path: str, mock_machinelearning_client: MLClient, context={}, is_anonymous=False, fields_to_override=None, ) -> ParallelComponent: """Component yaml -> component entity -> rest component object -> component entity""" with open(path, "r") as f: cfg...
5,299,053
def ngram2mgram(input_file, output_file, n, m, words=False, ascii_idngram=False): """ Takes either a word n-gram file, or an id n-gram file and outputs a file of the same type where m < n. """ cmd = ['ngram2mgram', '-n', n, '-m', m] if words and ascii_idngram: ...
5,299,054
def nash_do_transfer_from(ctx, Caller, args): """Transfers the approved token at the specified id from the t_from address to the t_to address Only a whitelisted DEX can invoke this function :param StorageContext ctx: current store context :param list args: 0: bytearray t_from: transfer fro...
5,299,055
def test_ap_wpa2_eap_aka_config(dev, apdev): """EAP-AKA configuration options""" params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap") hapd = hostapd.add_ap(apdev[0], params) eap_connect(dev[0], hapd, "AKA", "0232010000000000", password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6d...
5,299,056
def dki_wf(): """dti workflow""" from nipype import Workflow, Node, Function # Load data # Load data def data_loading(fdwi, fbvals, fbvecs, fmask, foutdir): from dipy.io.image import load_nifti from dipy.io.image import load_nifti_data from dipy.io.gradients...
5,299,057
def import_channels(): """ Import the channels in `channels_to_import` using the command line interface. """ current_role = env.effective_roles[0] channels_to_import = env.roledefs[current_role]['channels_to_import'] for channel_id in channels_to_import: import_channel(channel_id) pu...
5,299,058
def convert_numbers(data): """ Function to replace numerical numbers with their text counterparts. :param data: The text data to be searched. :return: The text data with numerical numbers replaced with textual representation. """ inf = inflect.engine() for word in data: if word.isdi...
5,299,059
def mkdir(*paths): """Create directories and any parent directory that doesn't exist""" for path in paths: run('mkdir -p {0}'.format(path))
5,299,060
def linear_discriminant_analysis(df): """ Determine weights for Fischer linear discriminant analysis of df. @param df pandas dataframe with output in column 'state' states must be 1 or -1; @return list of weights and weight threshold. """ # separate df in states group_by = df....
5,299,061
def update_sample_group_attachments(user: User, sample_group: SampleGroup, samples: List[Sample]) -> SampleGroup: """ Make the only samples attached to a group those in sample_ids :param user: :param sample_group: :param samples: :return: """ if is_write_permitted(user, sample_group) and...
5,299,062
def check_for_tokens(): """ Checks if the required API keys for Spotify has been set. :param name: Name to be cleaned up :return string containing the cleaned name """ log.debug('Checking for tokens') CLIENT_ID = getenv('SPOTIPY_CLIENT_ID') CLIENT_SECRET = getenv('SPOTIPY_CLIENT_SECRET')...
5,299,063
def make_reference(mol): """ Takes an molecule graph (e.g. as read from a PDB file), and finds and returns the graph how it should look like, including all matching nodes between the input graph and the references. Requires residuenames to be correct. Notes ----- The match between h...
5,299,064
def get(url, params, proxies, headers): """Send a request with the GET method.""" response = requests.get(url, params=params, proxies=proxies, headers=headers) return response
5,299,065
def upgrade(): """Upgrade database.""" # ### commands auto generated by Alembic - please adjust! ### op.add_column('analysis_articles_impact', sa.Column('creation_date', sa.DateTime(), nullable=False)) op.add_column('analysis_articles_impact', sa.Column('journal', sa.String(length=150), nullable=False))...
5,299,066
def _parse_input(ip: Union[List, str], network: str = '255.255.255.255', workers: int = default_processes): """ convert the ip, network into a structure containing address/masks """ # if this is list split it into worker tasks if isinstance(ip, list): tasks = split_addrs(ip, workers=workers) els...
5,299,067
def test_switch_condition_set_define_attr_mix_branch_and_default(): """Test set bot :class:`Branch` and :class:`Default` to attribute on :class:`SwitchCondition`.""" task = Task(TEST_NAME, TEST_TYPE) switch_condition = SwitchCondition( Branch("unittest1", task), Branch("unittest2", task), Default(ta...
5,299,068
async def send( bot: "Bot", event: Event, message: Union[str, Message, MessageSegment], at_sender: bool = False, reply_message: bool = False, **params: Any, ) -> Any: """默认回复消息处理函数。""" event_dict = event.dict() params.setdefault("detail_type", event_dict["detail_type"]) if "use...
5,299,069
def remove_duplicate_vertices_cmd(): """ Remove duplicate vertices a CityJSON file. Only the geometry vertices are processed, and not those of the textures/templates. """ def processor(cm): print_cmd_status('Remove duplicate vertices') cm.remove_duplicate_vertices() retur...
5,299,070
def plot_avg_firing_rate_based_on_movement( tracking: pd.DataFrame, unit: pd.Series, ax: plt.axis ): """ Plots a units average firing rate during different kinds of movements """ movements = ( "moving", "walking", "turning_left", "turning_right", "tone_on"...
5,299,071
def account_ids_equal(account_id_a, account_id_b): """ Compare two account IDs while discarding the account prefix :return: Whether the account IDs are equal :rtype: bool """ return account_id_a[-60:-8] == account_id_b[-60:-8]
5,299,072
def plot_implicit(ax, fn, bbox=(-2.5, 2.5)): """ create a plot of an implicit function fn ...implicit function (plot where fn==0) bbox ..the x,y,and z limits of plotted interval""" xmin, xmax, ymin, ymax, zmin, zmax = bbox*3 A = np.linspace(xmin, xmax, 100) # resolution of the contour B = np.l...
5,299,073
def run_simulation_with_temporary_output(simulation): """ This is needed to run the test suite with Travis-CI. Otherwise, the process will attempt to write outputs to the working directory, resulting in a permission error. Parameters ---------- simulation : phaseflow.Simulatio...
5,299,074
def run_experiment(run, save, views, datapath, load_and_process_data, savepath): """ :param run: method that runs real experiment given data :type: function :param save: method that saves experiment results to JSON file :type: function :param views: dictionary of indices for the weak sig...
5,299,075
def add_group_predictors(dataset_id, participants): """ Adds group predictors using participants.tsv Args: participants - path to participants tsv dataset_id - Dataset model id subjects - subject ids to processed Output: Ids of group predictors added """ gp_ids = [] ...
5,299,076
def action_from_trinary_to_env(action) -> int: """ Maps trinary model output to int action understandable by env """ assert action in (0, 1, 2), f'Wrong action: {action}' return { 0: 0, 1: 2, 2: 5 }[action]
5,299,077
def hex_value(image): """ Get the dice value of a hex. :param image: The game image. :return: An int of the hex value or None if a invalid value is found. """ grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(grey, 200, 255, cv2.THRESH_BINARY_INV) value_contour = f...
5,299,078
def test_repr(): """Test __repr.""" assert repr(setlist()) == 'setlist()' assert repr(setlist(range(4))) == 'setlist((0, 1, 2, 3))' assert repr(frozensetlist()) == 'frozensetlist()' assert repr(frozensetlist('abc')) == "frozensetlist(('a', 'b', 'c'))"
5,299,079
def handler(event, _): """ Lambda handler """ order_id = event["detail"]["new"]["orderId"] new_total = event["detail"]["new"]["total"] old_total = event["detail"]["old"]["total"] logger.info({ "message": "Received modification of order {}".format(order_id), "orderId": order...
5,299,080
def get(filename, target=None, serial=None): """ Gets a referenced file on the device's file system and copies it to the target (or current working directory if unspecified). If no serial object is supplied, microfs will attempt to detect the connection itself. Returns True for success or rais...
5,299,081
def download_by_word(word, output_dir="./output", engines=('baidu',), concurrency=True, size_type=None): """ 根据关键词和指定的搜索引擎抓取图片 :param word: 关键词 :param output_dir: 输出目录 :param engines: 搜索引擎列表 :param concurrency: 是否并发下载 :param size_type: 尺寸 """ engines = map(lambda x: x.lower(), engin...
5,299,082
def get_market_name(market: str = None) -> str: """ 입력된 값에 대한 마켓의 종류를 반환하는 함수 Parameters ---------- market: str 마켓에 대한 약어 혹은 마켓의 풀네임 Returns ------- str 입력된 값에 대한 마켓 타입 Raises ------ ValueError 입력된 값에 대한 마켓의 타입을 알 수 없을때 """ if market: ...
5,299,083
def freezeScalesForHierarchy(node): """ Freeze scales on a transform and all its descendants without affecting pivots. Does this by parenting all children to the world, freezing, then restoring the hierarchy. Args: node (pm.PyNode): A Transform node """ hierarchy = getTransformHierarchy...
5,299,084
def listdir(path: str, excludes: t.Container[str] = None) -> t.Iterator[str]: """ List all dir inside specific path. Args: path (str): path to be explore. excludes (Container[str], optional): dirname to exclude. Defaults to None. Yields: Iterator[str]: absolute path of subdirec...
5,299,085
def _get_registered_typelibs(match='HEC River Analysis System'): """ adapted from pywin32 # Copyright (c) 1996-2008, Greg Stein and Mark Hammond. """ # Explicit lookup in the registry. result = [] key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib") try: num = 0 ...
5,299,086
def contact(): """ Function is invoked when requests is made to url: dommainname/contact :return: a rendered template for the about page """ # Accesses the contact form and renders it in the contact html file # Submits the filled form and sends the values in a mail to a configured e...
5,299,087
def convert_rst_formatting(text): """ Convert rst syntax for formatting to markdown in a given text. """ # Remove :class:, :func: and :meth: markers. To code-links and put double backquotes # (to not be caught by the italic conversion). text = _re_func_class.sub(r"[``\1``]", text) # Remove :...
5,299,088
def get_setup_file(): """Serve the SSDP setup file.""" out = "<?xml version=\"1.0\"?>\n" + \ "<root xmlns=\"urn:schemas-upnp-org:device-1-0\">\n" + \ "<specVersion>\n" + \ "<major>1</major>\n" + \ "<minor>0</minor>\n" + \ "</specVersion>\n" + \ "<URLB...
5,299,089
def ofxPluginPath(): """ nuke.ofxPluginPath() -> String list List of all the directories Nuke searched for OFX plugins in. @return: String list """ return list()
5,299,090
def nersc_job(jobname, path, logroot, desisetup, commands, machine, queue, nodes, cnodes, ppns, minutes, multisrun=False, openmp=False, multiproc=False, shifterimg=None,debug=False): """Create a SLURM script for use at NERSC. Args: """ if len(commands) == 0: raise RuntimeError("List o...
5,299,091
def index_sentence_with_vocabulary(sentence, word2id, sequence_length=None, knowledge_path=None): """index sentence with vocabulary, return list of index""" # print("index_sentence_with_vocabulary:",knowledge_path) result_list = tokenize_sentence(sentence, knowledge_path=knowledge_path) result_list = re...
5,299,092
def set_android_token(request): """ Android's push notification tokens. Not sure why I can't find this function in the Android code. """ user = get_user(request) tokens = MUserNotificationTokens.get_tokens_for_user(user.pk) token = request.POST['token'] logging.user(user, "~FCUpdat...
5,299,093
def file_md5(file_path: str) -> str: """Compute the md5 hex digest of a binary file with reasonable memory usage.""" md5_hash = hashlib.md5() with open(file_path, 'rb') as f: while True: data = f.read(65536) if not data: break md5_hash.update(data)...
5,299,094
def get_parameters(model, unique_variance=False): """ Returns the true parameters of a given model. :param model: Model ID. :param unique_variance: indicates whether the variance should be unique :return: Mixture weights, means and covariances. """ if model == Model.M1: return get_p...
5,299,095
def collection(request, *args, **kwargs): """ REST main collection request handler. **Supported HTTP methods:** * GET * DELETE * PUT * POST :param request: Request object :param args: arguments :param kwargs: Dictionary (keyword arguments). Known kwargs listed below. **In...
5,299,096
def _(shape: numpy.ndarray): """ Handle point arrays or bounding boxes """ from .centrography import mean_center if shape.ndim == 2: return mean_center(shape).squeeze() elif shape.ndim == 1: assert shape.shape == (4,) xmin, ymin, xmax, ymax = shape return numpy.c...
5,299,097
def mkt(vdf, column: str, ts: str, p=1000, alpha: float = 0.05): """ --------------------------------------------------------------------------- Mann Kendall test (Time Series trend). \u26A0 Warning : This Test is computationally expensive. It is using a CROSS JOIN during the computation. The com...
5,299,098
def cli(ctx, path, **kwds): """Open latest Planemo test results in a web browser.""" click.launch(path)
5,299,099