content
stringlengths
22
815k
id
int64
0
4.91M
def RandomJavascriptValue(): """Generates code for a random javascript expression. Returns: Code for a javascript expression. """ roll = random.random() if roll < 0.3: return '"' + RandomIdentifier() + '"' elif roll < 0.6: return str(random.randint(-10000000, 10000000)) elif roll...
5,302,300
def add_hydrogen(mol): """Add hydrogens to saturate atomic valences. Args: mol (moldesign.Molecule): Molecule to saturate Returns: moldesign.Molecule: New molecule with all valences saturated """ pbmol = mol_to_pybel(mol) pbmol.OBMol.AddHydrogens() newmol = pybel_to_mol(pbm...
5,302,301
def typelogged_module(md): """Works like typelogged, but is only applicable to modules by explicit call). md must be a module or a module name contained in sys.modules. """ if not pytypes.typelogging_enabled: return md if isinstance(md, str): if md in sys.modules: md = sy...
5,302,302
def ler_blockchain(index=None, hash_bloco=None, origem=None, destino=None): """Retorna um bloco se especificado seu index ou hash. Caso contrário, retorna todo o bloco""" blockchain = ler_arquivo() if index is not None: for bloco in blockchain['blocks']: if bloco['index'] == int(inde...
5,302,303
def main() -> None: """The main program. Process command line options, setup the environment and invoke the desired functions. """ parser = _prepare_parser() args = parser.parse_args() cfg_path = ArcFace.arcface_code_directory / 'configs' / 'ulf_test.yaml' arcface = ArcFace(cfg_path=cfg_p...
5,302,304
def register_engine_renderer_handler( newtype, renderer_handler, override = False ): """register a new shape type and its engine renderer handler """ from . import ShapeComputationEngineRenderer ShapeComputationEngineRenderer.register(newtype, renderer_handler, override = override) return
5,302,305
def _GetLogTag(filename): """Get the tag of a log.""" regex = re.compile(r'\d+\-\d+(:?\-(?P<tag>.+))?.h5') match = regex.search(filename) if match and match.group('tag'): return match.group('tag') elif filename.endswith('.h5'): return filename[:-3] else: return ''
5,302,306
def sigsearch(): """Signal searching routine using the analyzer's "Find RF" routine""" Instrument.write_str_with_opc("CONFigure:AFRF:MEAS:FREQuency:COUNter:AUTomatic ON") # Automatically switch analyzer to the detected frequency Instrument.write_str_with_opc("INITiate:AFRF:MEAS:FREQuency:COUNter") # Start...
5,302,307
def sphere4(x: np.ndarray) -> float: """ Translated sphere function. The most classical continuous optimization testbed. If you do not solve that one then you have a bug. """ return float(np.sum((x - 4.)**2))
5,302,308
def Event_pick_graph_point(graph, vol, label, nodesOnly=False, axes=None, vis=True): """ As snap_picked_point_to_graph but bound to axes with key control Use p key to get picked point """ if axes is None: axes = vv.gca() point = dict() # Define callback function @axes.eventKeyDown.Bi...
5,302,309
def test_markerfacecolors(axis): """Are the marker face colors correct?""" # inherit the color from the line axis.plot([1, 2.17, 3.3, 4], [2.5, 3.25, 4.4, 5], marker='o', color='c') pc = LinePlotChecker(axis) pc.assert_markerfacecolors_equal(['c']) # add another line, using rgb axis.plot([1...
5,302,310
def get_relation_field_related_name(model, field_name): """获取关系字段的 related_name""" field = get_relation_field(model, field_name) if not field: return related_name = field.remote_field.related_name if field.one_to_one: return field.remote_field.name, field if related_name is Non...
5,302,311
def positional_encoding(position, d_model): """ Positional encoding is used to take into account the order of tokens in a sentence. The output of this function will be added to the embeddings. """ angle_rads = get_angles( np.arange(position)[:, np.newaxis], np.arange(d_model)[np.newaxi...
5,302,312
def l2_norm(x: numpy.ndarray, y: numpy.ndarray) -> numpy.ndarray: """Euclidean distance between two batches of points stacked across the first dimension.""" return numpy.linalg.norm(x - y, axis=1)
5,302,313
def extract_features_wotarget_14_dlstream(inifile): """Adapted version of extract_features_wotargat_14bp to work with fast feature extraction code within DLStream Reduced feature selection based on recursive feature elimination for social behavior between 2 mice (anogenital approach, attack, etc.) """ ...
5,302,314
def get_maximisation(model_filename, max_epoch=3, learning_rate=0.1): """ Get a maximisation instance for the given model and set the max epoch and learning rate. :param model_filename: The filepath to the model. :param max_epoch: The maximum amount of epochs, gradient ascent parameter. :param learn...
5,302,315
def applydownsample(summary_occurrences, downsample): """ Downsample a categorized collection of systems according to a ruleset. Arguments: - summary_occurrences: dict produced by categorizeattractors - downsample: system ruleset where the values are the number of each system type to keep (if int) ...
5,302,316
def lpi( experiment, with_evc_tree=True, model="RandomForestRegressor", model_kwargs=None, n_points=20, n_runs=10, **kwargs, ): """ Make a bar plot to visualize the local parameter importance metric. For more information on the metric, see original paper at https://ml.inform...
5,302,317
def _disable_df_interactive_hint_formatter(): """Restores the original html formatter for Pandas DataFrames.""" key = 'text/html' if key in _original_formatters: formatters = _IPython.get_ipython().display_formatter.formatters formatters[key].pop('pandas.core.frame.DataFrame', None) formatters[key].fo...
5,302,318
def discover_preferences_pluggables(): """ Discovers the pluggable modules on the directory and subdirectories of the preferences package and attempts to register them. Pluggable modules should subclass Pluggable Base classes. """ preferences = Preferences() packages = preferences.get_packages([...
5,302,319
def get_queue(queue_id): # noqa: E501 """Get a queue by its ID Returns the queue for a given ID # noqa: E501 :param queue_id: The ID of the queue :type queue_id: str :rtype: Queue """ return 'do some magic!'
5,302,320
def ilarisHitProb(at,vt): """ at: AT of attacking character vt: VT of defending character return: probability that attacking character will hit defending character """ # 47.5 is the chance without any bonus # 47.5-((y-41)*y)/8 is the added chance per bonus # (at>vt) is extra if at>vt bec...
5,302,321
def create_eval_loaders(options, eval_type, keyframes, total_batch_size = 8, trajectory = ''): """ create the evaluation loader at different keyframes set-up """ eval_loaders = {} if trajectory == '': trajectories = eval_trajectories(options.dataset) else: trajectories ...
5,302,322
def rec2gtk(r, formatd=None, rownum=0, autowin=True): """ formatd is a dictionary mapping dtype name -> mlab.Format instances This function creates a SortedStringsScrolledWindow (derived from gtk.ScrolledWindow) and returns it. if autowin is True, a gtk.Window is created, attached to the Sorte...
5,302,323
def edges2d(Z): """ Like `edges` but for 2d arrays. The size of both axes are increased by one. This is used internally to calculate graitule edges when you supply centers to `~matplotlib.axes.Axes.pcolor` or `~matplotlib.axes.Axes.pcolormesh`. Parameters ---------- Z : array-like ...
5,302,324
def run_ftp_stopped_test(ftpserver_fixture): """ Tests if the Server is unreachable after shutdown, by checking if a client that tries to connect raises an exception. Parameters ---------- ftpserver_fixture: PytestLocalFTPServer """ ftpserver_fixture.stop() ftp = FTP() if USE_P...
5,302,325
def GetGerritPatchInfoWithPatchQueries(patches): """Query Gerrit server for patch information using PatchQuery objects. Args: patches: A list of PatchQuery objects to query. Returns: A list of GerritPatch objects describing each patch. Only the first instance of a requested patch is returned. Ra...
5,302,326
def test_read_data_file_needs_file(tmpdir): """Reading a non-existent dictionary file raises.""" pn = tmpdir.join('noSuchDict').strpath assert not os.path.isfile(pn) with pytest.raises(IOError): read_data_file(pn)
5,302,327
def test_account_transfer_from_address_send_to_itself(): """ Case: transfer tokens from address to the same address. Expect: invalid transaction error is raised with account cannot send tokens to itself error message. """ mock_context = create_context(account_from_balance=ACCOUNT_FROM_BALANCE, accou...
5,302,328
def save_dashboard_settings(message): """ Save the settings into the cookie """ session["settings"] = message['settings']
5,302,329
def random_string() -> str: """Return a random string of characters.""" letters = string.ascii_letters return "".join(random.choice(letters) for i in range(32))
5,302,330
def universal_path(path: str) -> str: """ Converts a path name from its operating system-specific format to a universal path notation. Universal path notation always uses a Unix-style "/" to separate path elements. A universal path can be converted to a native (operating system-specific) path via th...
5,302,331
def set_vector(iif, dq, rq): """A file to initialize a vector from an another vector. If the first dimension is different, i.e. the two vectors correspond to a different number of beads, then the ring polymer contraction/expansion is used to rescale the original vector to the one used in the simulation, ...
5,302,332
def build_fhir_profile(request,context={}, template="", extn="json.html", ): """ Build a FHIR Profile in JSON Use to submit to FHIR Server :param template: :param extn: json.html or json.xml (use .html to enable ...
5,302,333
def notify_via_one_signal(access_token, title, message): """ Send a push notification to the user via OneSignal. Arguments: access_token (str): Access token for the API request. title (str): Notification title. message (str): Notification body. """ try: response = re...
5,302,334
def compare_package_to_github(local_data_json, github_location, package_version, extensions_hashed, args): """Downloads the npm package from GitHub and warns about discrepancies. Args: local_data_json (dict): The JSON generated by the current invocation of this...
5,302,335
def one_mask_generation(tokenizer, model, sentence, num_select=5, masked_sentence=None, ending="."): """ Function to get the most likely word (post softmax) to fill in the end of the sentence. Example usage: one_mask_generation(BERT tokenizer, BERT model, "The apple is ") """ if masked_sentence == N...
5,302,336
def create_control_in_program_scope(selenium, program): """Create control via UI.""" controls_service = webui_service.ControlsService(selenium) controls_service.open_widget_of_mapped_objs( program).tree_view.open_map().click_create_and_map_obj() control = entities_factory.ControlsFactory().create() cont...
5,302,337
def run_test(**kwargs): """ runs a single test :param kwargs: :return: time, accuracy result """ ppc = kwargs['hog'] b = fetch_sw_orl() tic = time.time() # split the data in X_train, X_test, y_train, y_true = train_test_split(b.data, b.target, test_size=0.2, stratify=b.target) ...
5,302,338
def dj(*args, **kwargs): """DJ, the Django CLI.""" pass
5,302,339
def zac(waves, calcs, lenght, sigma, flat, decay, wfin="waveform", wfout="wf_zac", test=False): """ ZAC filter. inputs are in microsec (lenght, sigma, flat, decay) """ wfs = waves[wfin] clk = waves["settings"]["clk"] # Hz nwfs, nbin = wfs.shape[0], wfs.shape[1] # convert params to n...
5,302,340
def label_image_to_one_hot_stack( label: np.ndarray, num_classes: int = -1, channels_first: bool = False, dtype: np.dtype = np.uint8 ) -> np.ndarray: """Converts a label image into a stack of binary images (one-hot). The binary image at index 'i' in the stack contains the pixels...
5,302,341
def doc_handle_n_get(event: "Event", *args: Sequence[Any]) -> UserReturnType: """Documentation for handlers bound to ``evt.EVT_N_GET``. User implementation of this event handler is required if one or more services that use N-GET are to be supported. If a handler is not implemented and bound to ``evt.EV...
5,302,342
def pacing_rhythm_detector(raw_sig:np.ndarray, fs:Real, sig_fmt:str="channel_first", ret_prob:bool=True, verbose:int=0) -> Real: """ finished, checked, to be improved (fine-tuning hyper-parameters in cfg.py), Parameters: ----------- raw_sig: ndarray, the raw 12-lead ecg signal, with units in mV...
5,302,343
def loop(mac_addr, adc, pin_out): """ Turns on output pin Reads ADC Value POSTs to InfluxDB Turns off output (vcc) pin to avoid electrolysis Sleeps for """ while True: # Turn output on so ADC device gets power pin_out.on() # Wait after turning pin on for accurate ...
5,302,344
def main(args=None): """ Main entry point. """ if args is None: args = sys.argv[1:] text = ' '.join(args) if text: if text == 'initial_patterns': initial_patterns() else: parser = NumeralParser() result = parser.parse(text) ...
5,302,345
def tfrecord_dataset(tfr_data_files_pattern, batch_size, seq_length, seq_depth, target_length, num_targets, mode, use_static_batch_size=False, repeat=Tr...
5,302,346
def bbox_structure_to_square(bbox): """Function to turn from bbox coco struture to square. [x,y,width,height] -> [min_height, min_width, max_height, max_width] """ x,y,width,height = bbox sq = [y,x,y+height,x+width] return sq
5,302,347
def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str: """Replace `regex` with `replacement` twice on `original`. This is used by string normalization to perform replaces on overlapping matches. """ return regex.sub(replacement, regex.sub(replacement, original))
5,302,348
def tobase64(x): """ python2/3 compatible conversion to urlsafe base64 encoding """ return tostr(base64.urlsafe_b64encode(tobytes(x))).replace('=', '')
5,302,349
def retrieve_tags_for_picture(picture): """Retrieve all tags for picture.""" database = get_db() return database.retrieve_tags_for_picture(picture)
5,302,350
def _make_serving_input_fn(tf_transform_output): """Creates an input function reading from raw data. Args: tf_transform_output: Wrapper around output of tf.Transform. Returns: The serving input function. """ raw_feature_spec = common.RAW_DATA_FEATURE_SPEC.copy() # Remove label since it is not avai...
5,302,351
def ref_properties_from_header(filename): """Look inside FITS `filename` header to determine instrument, filekind. """ # For legacy files, just use the root filename as the unique id path, _parts, ext = _get_fields(filename) serial = os.path.basename(os.path.splitext(filename)[0]) header = data...
5,302,352
def auto_buy_item(info, ordered_items, place, settings): """ Proceeds to auto-buy the item that is in stock. Notifies the user if notifications are enabled. """ if delegate_purchase(info.get('webshop'), info.get('url'), settings): print("[=== ITEM ORDERED, HOORAY! ===] [=== {} ===]".format(p...
5,302,353
def lint_pylint(context): """ Lint code with pylint """ context.run("pylint {}".format(" ".join(PYTHON_DIRS)))
5,302,354
def accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float: """ Calculate accuracy of given predictions Parameters ---------- y_true: ndarray of shape (n_samples, ) True response values y_pred: ndarray of shape (n_samples, ) Predicted response values Returns ------- ...
5,302,355
def update_self(to_screen, verbose): """Update the program file with the latest version from the repository""" UPDATE_URL = "https://rg3.github.io/youtube-dl/update/" VERSION_URL = UPDATE_URL + 'LATEST_VERSION' JSON_URL = UPDATE_URL + 'versions.json' UPDATES_RSA_KEY = (0x9d60ee4d8f805312fdb15a62f87...
5,302,356
def write_temp_file(content, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True): """写临时文件 .""" with NamedTemporaryFile(mode, buffering, encoding, newline, suffix, prefix, ...
5,302,357
def test_add_term_parameters_units(): """ Test adding parameters to the DL object with units """ dl = eex.datalayer.DataLayer("test_add_parameters_units") two_body_md = eex.metadata.get_term_metadata(2, "forms", "harmonic") three_body_md = eex.metadata.get_term_metadata(3, "forms", "harmonic") ...
5,302,358
def check_for_updates() -> None: """Identifies whether the track instance is git versioned, fetches from upstream and checks whether there are updates to pull""" log().info("Check for remote app updates on git remote..") def git_cmd(cmd) -> str: result = subprocess.run( ["git"] + cmd...
5,302,359
def push_to_gh(git_repo_names, tmp_root, gh_username): """Push local Git repos to Github repos.""" os.chdir(tmp_root) for i, git_repo_name in enumerate(git_repo_names): my_print(f"Pushing repo {i}/{len(git_repo_names)}") os.chdir(git_repo_name) cmd = f"git remote add gh_origin g...
5,302,360
def create_metadata_table(ifu_list): """Build a FITS binary table HDU containing all the meta data from individual IFU objects.""" # List of columns for the meta-data table columns = [] # Number of rows to appear in the table (equal to the number of files used to create the cube) n_rows = ...
5,302,361
def set_layout_properties(layout_name, properties_dict, base_url=DEFAULT_BASE_URL): """Sets the specified properties for the specified layout. Unmentioned properties are left unchanged. Run ``getLayoutNames`` to list available layouts. Run ``getLayoutPropertyNames`` to list properties per layout. Arg...
5,302,362
def get_data(query): """ Author - Jonathan Steward Function - Used to get data from the Database based on a pre-defined SQL Query Inputs - string - query to use when getting data returns - list - resulting data """ try: DBconnection = connector.connect( user="root", ...
5,302,363
def load_pickle(filename): """ Loads a serialized object Parameters: ----------- filename : string """ return pickle.load(open(filename,'rb'))
5,302,364
def fasta_pred(fasta_file,pred_file,cutoff=-3,hits_only=False): """ """ pred_dict = read_predictions(pred_file) kmer_size = len(list(pred_dict.keys())[0]) all_kmers = {} seq_name = None current_sequence = [] header = ["#-->"] header.append("binds") header.append("best") ...
5,302,365
def parse_args(): """Parse arguments. Returns: argument namespace """ # Parse arguments parser = argparse.ArgumentParser() parser.add_argument('--load-model', help=("Path from which to load parameters and model weights " "for model found by hyperparameter s...
5,302,366
def clientsNamed(app): """A dictionary of client fixtures for all authenticated users. Keyed by user (eppn), the values are corresponding client fixtures. """ return {user: makeClient(app, user) for user in NAMED_USERS}
5,302,367
def load_build_configuration_from_source( build_configuration: BuildConfiguration, backends1: List[str], backends2: List[str] ) -> None: """Installs pants backend packages to provide BUILD file symbols and cli goals. :param build_configuration: The BuildConfiguration (for adding aliases). :param backen...
5,302,368
def to_np_tuple(prop: Union[int, Iterable]) -> np.ndarray: """Creates a np array of length 2 from a Conv2D property. E.g., stride=(2, 3) gets converted into np.array([2, 3]), where the height_stride = 2 and width_stride = 3. stride=2 gets converted into np.array([2, 2]). """ if type(prop) == in...
5,302,369
def tetrode_identity_shuffle(multiunit): """Shuffle the correspondence between tetrodes and spike time """ n_tetrodes = len(multiunit.tetrodes) rand_tetrode_index = np.random.randint( low=0, high=n_tetrodes, size=n_tetrodes) return multiunit.isel(tetrodes=rand_tetrode_index)
5,302,370
def ceph_version(): """Retrieve the local version of ceph.""" if os.path.exists('/usr/bin/ceph'): cmd = ['ceph', '-v'] output = check_output(cmd).decode('US-ASCII') output = output.split() if len(output) > 3: return output[2] else: return None ...
5,302,371
def test_raidenapi_channel_lifecycle( raiden_network, token_addresses, deposit, retry_timeout, settle_timeout_max ): """Uses RaidenAPI to go through a complete channel lifecycle.""" node1, node2 = raiden_network token_address = token_addresses[0] token_network_address = views.get_token_network_addre...
5,302,372
def is_silent(data_chunk): """Returns 'True' if below the 'silent' threshold""" return max(data_chunk) < THRESHOLD
5,302,373
def get_properties(value): """ Converts the specified value into a dict containing the NVPs (name-value pairs) :param value: :return: """ rtnval = None if isinstance(value, dict): # value is already a Python dict, so just return it rtnval = value elif '=' in value: ...
5,302,374
def union(llist_1, llist_2): """ Returns union of two provided LinkedLists Args: - llist_1(LinkedList): data to be written into the new block - llist_2(LinkedList) Returns: - True if the block was added. Otherwise False """ if llist_1 is Non...
5,302,375
def qft(qubits): """ Performs an in-place quantum fourier transform on the given register. Parameters: qubits (list[QubitPlaceholder]): The register to apply the QFT to Returns: A program containing the QFT gates. Remarks: Note that by the established conventions, the QFT ...
5,302,376
def pay_worker_bonus(job_id, worker_id, api, con=None, assignment_id=None, send_notification=False): """ :param job_id: :param worker_id: :param bonus_cents: :param api: :param overwite: :param con: :param assignment_id: :returns True if payment was done, False otherwise """ ...
5,302,377
def policy_and_value_opt_step(i, opt_state, opt_update, get_params, policy_and_value_net_apply, log_probab_actions_old, value_predictions_ol...
5,302,378
def check_hits_in_ellipse(ellipses: np.array, hits: np.array) -> np.array: """Returns mask for specified hits, True if hit in ellipse, False otherwise """ k_hits = len(hits) / len(ellipses) duplicated_ellipses = np.repeat(ellipses, k_hits, axis=0) centers = duplicated_ellipses[:, :2] ...
5,302,379
def test_default_upper_bonuses(): """Check that the default upper secton bonus rules are set correctly.""" bonuses = yh.DEFAULT_UPPER_BONUSES expected_types = { "Upper Section Bonus": rl.ThresholdBonusRule, } assert len(bonuses) == 1 assert all([ bonuses[idx].name == name and isi...
5,302,380
def get_optional_boolean_arg(args: Dict, argument_name: str) -> Optional[bool]: """ Extracts the argument from Demisto arguments, and in case argument exists, returns the boolean value of the argument. Args: args (Dict): Demisto arguments. argument_name (str): Name of the argument. ...
5,302,381
def get_jaddr_from_comments(pp_lst, comment_lst): """ @brief reads in jump addresses wich were set by the reverse engineer @param pp_lst List of PseudoInstructions in push/pop represtentation @param comment_lst List of comments @return List of tuples (set jump address, address of jump instr...
5,302,382
def main(): # pylint: disable=too-many-statements """Main entry point""" parser = argparse.ArgumentParser(prog='mediafire-cli', description=__doc__) parser.add_argument('--debug', dest='debug', action='store_true', default=False, help='Enable de...
5,302,383
def CalculateMeanValue(str_lengths:list): """ This function calculates the mean over all values in a list. :param str_lengths:list: lengths of all strings """ try: return int(round(sum(str_lengths)/len(str_lengths))) except Exception as ex: template = "An exception of type {0...
5,302,384
def radangle(p0,p1): """ Radian angle between two points on a sphere in lon-lat (x,y) Parameters ---------- p0 : first point as a lon,lat tuple p1 : second point as a lon,lat tuple Returns ------- d : radian angle in radians Example ------- >>> p0 = (-87.8935...
5,302,385
def fetch_tokens( w3url: str = typer.Option(None), db_uri: str = typer.Option(None), ): """Starts searching the blockchain for ERC20 tokens, and saves their addresses in the given database.""" EnvConfig.set_environment(w3url, db_uri) w3 = Web3Client() crud = Crud() _setup_is_fetch_status...
5,302,386
def processFailedNum(failed_number): """show errors.""" if failed_number > 20 and failed_number < 26: print 'ERROR: Input Connection Address Is Incorrect' if failed_number == 20: print 'uArm: Please Connect uArm first '
5,302,387
def annToMask(anno, height, width): """ Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask. :return: binary mask (numpy 2D array) """ rle = annToRLE(anno, height, width) mask = maskUtils.decode(rle) return mask
5,302,388
def install_casa_distro(base_dir, builder): """Install casa_distro.""" builder.install_casa_distro('/casa/casa-distro')
5,302,389
def get_pdm_terms(site_index, n, adj_sites=4, shift=0): """ inputs: site_index (int): center site index n (int): number of sites in lattice (for enforcing periodic boundary conditions) adj_site (int): how many adjacent sites to collect pop and coherence values from shift (int): r...
5,302,390
def clean_transcription(raw_string: str) -> str: """ Cleans up input transcriptions to replace any special characters with text :param raw_string: Input string to be cleaned :return: Cleaned string of alphas """ if not raw_string: raise ValueError parsed = raw_string.lower().replace(...
5,302,391
def system(cmd, stdin=None, **kwargs): """A simple front-end to python's horrible Popen-interface which lets you run a single shell command (only one, semicolon and && is not supported by os.execvp(). Does not catch OSError! :param cmd: command to run (a single string or a list of strings). :param ...
5,302,392
def test_patch_00(): """Check that patches are correctly created from points in 00 corner.""" halfwidth = 1 im_width = 5 im_height = 5 image = np.arange((im_height * im_width)).reshape((im_height, im_width)) n = 2 * halfwidth + 1 # 0,0 corner p_data = np.zeros((n, n), dtype=int) - 1 ...
5,302,393
def assert_expr(code, valuetype=ast.expr): """ Raise an error when `code` is not an expression. >>> assert_expr('0') >>> assert_expr('a[1]') >>> assert_expr('a[1] + b.c') >>> assert_expr('a; b') #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TraitsCLIAttri...
5,302,394
def glass(number): """ Return an array of Sellmeier coefficients for glass. The glasses all have a number. This number is used to look up the Sellmeier coefficients for glass. The number can be looked up with `ofiber.glass_name`. Use like this:: num = ofiber.glass_index("SiO2") ...
5,302,395
def isnan(x: _cpp.Variable) -> _cpp.Variable: """ Element-wise isnan (true if an element is nan). """ return _call_cpp_func(_cpp.isnan, x)
5,302,396
def set_grouped_config_view(): """ Sets a grouped config collection. There are some variables, one variable with a string as default value, one with a boolean as default value, one with an integer as default value, one with choices and one hidden variable. These variables are grouped in two subgroup...
5,302,397
def get_api_key(project_name, sh_env_var="CWL_ICA_API_KEY_SH", key_path_env_var="PROJECT_API_KEY_PATH"): """ Create a file using the contents of sh_env_var, run said file with key_path_env_var set to project_name This should then return an api-key. This is done with a similar idea to GIT_SSH. Your sh_e...
5,302,398
def supply(request, page_name): """supply view_objects for user status.""" _ = page_name _ = request #todays_users = Profile.objects.filter(last_visit_date=datetime.datetime.today()) rounds_info = challenge_mgr.get_all_round_info() start = rounds_info["competition_start"] daily_status = Da...
5,302,399