content
stringlengths
22
815k
id
int64
0
4.91M
def _generate_questions_per_round( round_tuple: Tuple[str, str], config: dict, tub: str ) -> Generator: """Takes in a dictionary of configuration information for a round and generates QuestionDetail class instances. Parameters ---------- round_tuple : Tuple[str, str] Tuple in the form o...
5,310,400
def tax_calculation(): """Calculates Tax for given income filing status""" # your code starts here. # call above function and print the income Tax in required_format income, filing_status, other_deduction = #your code take input here take_home_salary = # your code print("Take-Home Salary: {}".format(take_...
5,310,401
def unit_cross_product(uvec1, uvec2): """ Returns unit cross product between two unit vectors Ensures the result is itself a unit vector """ cos = np.dot(uvec1, uvec2) sin = math.sqrt(1 - cos**2) # if the number of atoms is > 3 and there are 3 colinear atoms this will fail csc = sin**-1 ...
5,310,402
def new_test_image(): """ Creates an automatically generated test image. In your testing `tearDown` method make sure to delete the test image with the helper function `delete_test_image`. The recommended way of using this helper function is as follows: object_1.image_property.save(*new_test_...
5,310,403
def move_data( uid, array_uri, coverage_vector_uri, cells_vector_uri, outdir_uri, access_key, secret_key, ): """ Placeholder for moving data. Nothing fancy. Not using until more testing is done regarding tiledb.move and tiledb.consolidate. Those routines seem to take a while ...
5,310,404
def _(word): """Returns the translated word from the dict_lang python dict. If the word is not found, it returns the same word (in english) Arguments: word {str} -- word to translate """ global dict_lang if dict_lang == {}: load_dictionary() try: word_...
5,310,405
def diff(f, a, b, n): """An iterative version of a forward differentiation method.""" x = np.linspace(a, b, n+1) y = np.zeros(len(x)) z = np.zeros(len(x)) h = (b-a)/float(n) for i in xrange(len(x)): y[i] = f(x[i]) for i in xrange(len(x)-1): z[i] = (y[i+1] - y[i])/h z[n] =...
5,310,406
def person_created(person, event): """Create initial infrastructure or update existing infrastructure to current requirements (using generation).""" # Set default values for references as z3c.form accesses the # attributes before a value is assigned and gets an AttributeError # otherwise. if not...
5,310,407
def get_minimum(feature): """Get minimum of either a single Feature or Feature group.""" if hasattr(feature, "location"): return feature.location.min() return min(f.location.min() for f in feature)
5,310,408
def compute_average_top_k_loss(loss: tf.Tensor, top_k_percentage: float) -> tf.Tensor: """Computes the avaerage top-k loss per sample. Args: loss: A tf.Tensor with 2 or more dimensions of shape [batch, ...]. top_k_percentage: A float representing the % of pixel that should be...
5,310,409
def isUniqueSFW(str): """ Given a string, checks if the string has unique charachters Note that this solution is inefficient as it takes O(n^2) """ l = len(str) for i in range(l): for j in range(l): if i != j and not ord(str[i]) ^ ord(str[j]): return False ...
5,310,410
def test_symbolic_effective_add(): """Check calculation of effective mode from symbolic.""" assert oschmod.get_effective_mode(0b111000000, "g+x") == 0b111001000 assert oschmod.get_effective_mode(0b111000000, "o+x") == 0b111000001 assert oschmod.get_effective_mode(0b111000000, "u+x") == 0b111000000 a...
5,310,411
def count_doubled(board, colour): """ Function counts doubled pawns """ pass
5,310,412
def pretty_print_POST(req): """ At this point it is completely built and ready to be fired; it is "prepared". However pay attention at the formatting used in this function because it is programmed to be pretty printed and may differ from the actual request. """ print('{}\n{}\n{}'.format...
5,310,413
def test_geodesic_euclid_middle(): """Test euclidean geodesic when alpha = 0.5""" A = 1*np.eye(3) B = 2*np.eye(3) Ctrue = 1.5*np.eye(3) assert_array_almost_equal(geodesic_euclid(A,B,0.5),Ctrue)
5,310,414
def mock_es_client(monkeypatch): """Patches the Elasticsearch library so that a mock client is used.""" mock_client = Mock() monkeypatch.setattr('elasticsearch_dsl.connections.connections.get_connection', mock_client) yield mock_client
5,310,415
def get_3x3_homothety(x,y,z): """return a homothety 3x3 matrix""" a= [x,0,0] b= [0,y,0] c= [0,0,z] return [a,b,c]
5,310,416
def http_die_soon(req): """Disable keep-alive to make HTTP proxy act like SOCKS. By doing this wstan server can remain unchanged, but it will increase latency.""" dropped = [i for i in req.split(b'\r\n') if not _keep_alive.match(i)] end = dropped.index(b'') return b'\r\n'.join(dropped[:end] + [b'Con...
5,310,417
def calculate_percent(data: dict, mode: str = "gte") -> None: """计算Counter形式的百分比。 当 mode 为 gte 时,计算 大于等于 key 的占比; 当 mode 为 lte 时,计算 小于等于 key 的占比。 将结果打印到控制台。 Args: data: Counter形式的数据; mode: 可选值为 gte 和 lte。 Returns: None """ data = gb.dict_sorted(data) x = li...
5,310,418
def non_max_suppression(boxes, scores, threshold): """ Performs non-maximum suppression and returns indices of kept boxes. :param boxes: [N, (y1, x1, y2, x2)]. Notice (y2, x2) lays outside the box. :param scores: 1d array of box scores. :param threshold: :return: """ assert boxes.shape[0...
5,310,419
def extract_glimpse_numpy_like(inp, glimpse_shape, glimpse_offsets, name=None, uniform_noise=None, fill_value=None): """ Based on: https://github.com/tensorflow/tensorflow/issues/2134#issuecomment-262525617 Works like numpy with pixel coordinates starting at (0, 0), returns: inp[:, glimpse_offset[0] : g...
5,310,420
def fftshift(x: numpy.ndarray): """ usage.scipy: 1 usage.skimage: 3 """ ...
5,310,421
def initialize(*args, **kwargs): """ Initialize a new global SingletonPool. Forwards all arguments to the constructor of `SingletonPool()`. After initialization, the instance can be used by invoking `instance()`. Example usage: -------------- ``` import quasardb.pool as pool pool...
5,310,422
def make_config(config, path, data_type, database_dir, threads, assembler): """Write the file `config` and complete the sample names and paths for all files in `path`. Args: config (str): output file path for yaml path (str): fastq/fasta data directory data_type (str): this is eithe...
5,310,423
def readShimadzuDatafile(fn, chapter_num=-1, return_all_sections=False): """ read the ascii data from Shimadzu Lab Solutions software the file appear to be split in to multiple sections, each starts with [section name], and ends with a empty line returns the data in the sections titled ...
5,310,424
def next_not_tail(*args): """next_not_tail(ea_t ea) -> ea_t""" return _idaapi.next_not_tail(*args)
5,310,425
def AddInterestedUserAndUrl(existing_url_key, bots_user_key): """Updates user models's interested_url and url model's interested_user field. This method updates url and bots_user model in trasaction to maintain the atomicity. Args: existing_url_key: Key of the url entity to update (db.Key). bots_user_...
5,310,426
def explore_queryset(): """ Explores a queryset. Meant for extended shell scripting """ qs = SampledRedditThread.objects.filter(url__icontains="wikipedia.org/wiki") for thread in qs: if 'imgur' in thread.url: print(thread.url)
5,310,427
def test_7(rq, isse_path, **kwargs): """Function: test_7 Description: Test: Process multiple files for message. Arguments: (input) rq -> RabbitMQ Publisher instance (input) isse_path -> Directory path to the ISSE Guard directory. """ print(" Test 7: Process multiple file...
5,310,428
def test_pathcheck_list_none(): """Multiple paths ok with none returning match.""" context = Context({ 'ok1': 'ov1', 'pathCheck': ['./{ok1}/x', './arb/{ok1}', '{ok1}/arb/z']}) with patch_logger( 'pypyr.steps.pathcheck', logging.INFO ) as mock_logger_info: pathchecker...
5,310,429
def validate_dataset(path_to_validate): """ Validates folder with assets """ path_to_validate = Path(path_to_validate) if not path_to_validate.exists(): raise FileNotFoundError if not path_to_validate.is_dir(): raise NotADirectoryError children_files_txt = list(path_to_valida...
5,310,430
def sql_to_python_type(sql_type: str) -> type: """Turn an SQL type into a dataframe dtype""" if sql_type.startswith("CHAR(") or sql_type.startswith("VARCHAR("): return pd.StringDtype() elif sql_type.startswith("INTERVAL"): return np.dtype("<m8[ns]") elif sql_type.startswith("TIMESTAMP(")...
5,310,431
def scrape_to_list_value(scraped_rows, i, list_name): """insert row of rows of scraped data input i for skipping rows return value in dollars""" to_scrape = scraped_rows[i::7] list_name = [] for i in range(len(to_scrape)): num = float(to_scrape[i][0].replace(',', '.')) num_dollar...
5,310,432
def _marathon(config_schema, info): """ :param config_schema: Whether to output the config schema :type config_schema: boolean :param info: Whether to output a description of this subcommand :type info: boolean :returns: process return code :rtype: int """ if config_schema: ...
5,310,433
def setup_debugging(options): """Parses and applies options @param options: parameters: debug, debug_module, debug_log_only, logfile """ global logfilename, logfile # not too nice way of sharing code, but it is necessary because code from this file # can't be accessed elsewhere on every distribution, and we can'...
5,310,434
def write_file(d, file_name, file_content, ctx): """Creates the directory d if it does not yet exist and writes a file to it named file_name with file_content in it. """ d = d.replace('.', os.sep) wd = os.getcwd() try: os.makedirs(d, 0o777) except OSError as exc: if exc.errn...
5,310,435
def example_station_config(): """ Returns path to temp yaml file with station config. """ sims_path = get_qcodes_path('instrument', 'sims') test_config = f""" instruments: lakeshore: type: qcodes.instrument_drivers.Lakeshore.Model_336.Model_336 enable_forced_reconnect: true address: GP...
5,310,436
def process_owner_me_query(): """Return features that the current user owns.""" user = users.get_current_user() if not user: return [] features = models.Feature.get_all(filterby=('owner', user.email())) feature_ids = [f['id'] for f in features] return feature_ids
5,310,437
def test_loader_macro_token(): """ Test macros XML macros with @ expansions in text """ with TestToolDirectory() as tool_dir: tool_dir.write( """ <tool> <expand macro="inputs" foo="hello" /> <expand macro="inputs" foo="world" /> <expand macro="inputs" /> <macros> ...
5,310,438
def velocity_traj(arr, dt=1.0, axis=0, endpoints=True): """Calculate velocity from `arr` (usually coordinates) along time`axis` using timestep `dt`. Central differences are used (example x-coord of atom 0: ``x=coords[:,0,0]``):: v[i] = [ x[i+1] - x[i-1] ] / (2*dt) which returns nstep-2 po...
5,310,439
def getPerturbationMeasures( fName, tmpDataPath = None, keepAnalysisFile = False ): """ performes perturbation measures using Praat's default settings @param fName the name of the WAV file that should be analyzed @param tmpDataPath the path for temporary files. if None, see @ref runPraatScript @param keepA...
5,310,440
def litho_ruler( height = 2 , width = 0.5, spacing = 1.2, scale = [3,1,1,1,1,2,1,1,1,1], num_marks = 21, layer = 0, ): """ Creates a ruler structure for lithographic measurement with marks of varying scales to allow for easy reading by eye. Parameters ---------- height :...
5,310,441
def create_recurrent_model(vocab_size = 10000, num_oov_buckets = 1, embedding_size = 96, latent_size = 670, num_layers = 1, name = 'rnn', shared_embedding = F...
5,310,442
def get_template(template_name): """ Returns a lxml Element containing the new terminal layout. """ template_path = path_template(template_name) new_division = ET.parse(template_path) return new_division.find("div")
5,310,443
def get_nodes_from_vpc_id(vpc_id): """ calculate node-ids from vpc_id. If not a vpc_id, then single node returned """ try: vpc_id = int(vpc_id) except ValueError as e: return ["%s" % vpc_id ] if vpc_id > 0xffff: n1 = (0xffff0000 & vpc_id) >> 16 n2 = (0x0000ffff & vpc_id) ...
5,310,444
def format_config_vals(config_vals): """Format an iterable of config values from a config object.""" text_buffer = StringIO() for i, k, v in config_vals: val = "" if v is None else str(v) text_buffer.write( (" " * i) + colorize(pad_line(str(k) + ":", 20, "left"), c...
5,310,445
def extract_imports(node: Module) -> List[ParsedImport]: """Extract parsed imports from module.""" node_imports = [] for node_import in node.iter_imports(): from_module = '' import_data = [] for part in filter_nodes(node_import, [Name, Keyword, Operator]): value = part.va...
5,310,446
def optimize_k_knn(X_train, y_train, X_test, y_test, min_k=3, max_k=10, score='micro'): """ Find best k neighbor number for KNN model based on scores on testing data Score is based on f1_score, for options refer to sklearn.metrics """ k_f1 = [] for k in range(min_k, max_k+1): knn = ...
5,310,447
def run_cmd(*args): """Run the provided arguments """ runner = CliRunner() return runner.invoke(main, args)
5,310,448
def condor_r_step(wkspace, sys=None, job_name="rank", dag=None): """Generate a condor job for running the ranking steps. Parameters ---------- wkspace : pathlib.Path Path of the config file. sys : list(str), optional Specific ystematics to use. job_name : str Name for th...
5,310,449
def utc2local(utc_time): """ UTC time to local time. UTC time format: 2020-02-02T02:02:02.202002Z, formatting UTC timestamp according to "%Y-%m-%dT%H:%M:%S.%fZ". :param utc_time: UTC time :return: local time """ local_format = "%Y-%m-%d %H:%M:%S" # The format "%Y-%m-%dT%H:%M:%S.%...
5,310,450
def _custom_openapi(app: FastAPI): """Custom OpenAPI schema generator function, supporting: - Cache the schema - Set custom logo in ReDoc """ if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title=settings.title, version=settings.version, ...
5,310,451
def get_hidden_states( model: BertModel, sent_data: np.array ) -> torch.Tensor: """ Grab the hidden state values from the model using the sentence data, and return the tensor. :param model: A BertModel object, already instantiated. :param sent_data: The sentence data extracted from ...
5,310,452
def test_get_cache_file_loc_not_file(monkeypatch): """Irregular existing cache files will raise FileExistsError""" def mock_exists(x): return True def mock_isfile(x): return False monkeypatch.setattr(os.path, "exists", mock_exists) monkeypatch.setattr(os.path, "isfile", mock_isfil...
5,310,453
def search(term, category=Categories.ALL, pages=1, sort=None, order=None): """Return a search result for term in category. Can also be sorted and span multiple pages.""" s = Search() s.search(term=term, category=category, pages=pages, sort=sort, order=order) return s
5,310,454
def UninstallService(): """Uninstall the service.""" service_main = _MainServiceScriptPath() if not service_main: logging.error('Unexpected: missing service main script [%s].', service_main) return False try: if _IsServiceInStatus(win32service.SERVICE_RUNNING) and not StopService(): logging.e...
5,310,455
def update_self_profile(request): """ Get current session profile details """ user = get_object_or_404(User, id=request.user.id) user.first_name = request.data['first_name'] user.last_name = request.data['last_name'] user.save() return HttpResponseRest(request, {})
5,310,456
def ex_verb_voice(sent, ex_set, be_outside_ex=True): """ Finds verb voice feature. 1. One of the tokens in the set must be partisip - VBG 2. One of the tokens in the set must be lemma 'be' 3. VBN's head has lemma 'be' If none of the tokens is verb, returns string 'None' @param sent Lis...
5,310,457
def do_legacy_learn(): """Repeatedly broadcast a legacy switch message, so you can learn a socket to the pattern""" # get device house_code = get_house_code() device_index = get_device_index() # Use a MiHomeLight as it has the longest TX time device = energenie.Devices.MIHO008((house_code, devi...
5,310,458
def toggle_wireframe_on_selected(): """ Toggle wireframe on selected. If we're currently in "wireframe everything" mode, switch to wireframe on selected. """ set_wireframe_mode('selected' if get_wireframe_mode() != 'selected' else 'none')
5,310,459
def add_sensorgroup_filter_by_ihost(query, value): """Adds an sensorgroup-specific filter to a query. Filters results by hostid, if supplied value is an integer. Otherwise attempts to filter results by UUID. :param query: Initial query to add filter to. :param value: Value for filtering results by...
5,310,460
def compute_residuals(data, targets, weights): """ Squared error function. param list(list(float)) data: independent variable(s) param list targets: dependent variable param list weights: weight vector """ assert type(weights) == list residuals = [] for i, values in enumerate(data)...
5,310,461
def get_webapp(): """ start web applicatioin """ # get template file and static file path. templatepath = os.path.join(config_parser.ConfigParser.get_rootpath(), "ui/templates") staticfilepath = os.path.join(config_parser.ConfigParser.get_rootpath(), "ui/static") # create applicatio...
5,310,462
def _at_least_x_are_equal(a, b, x): """At least x of a and b Tensors are equal.""" match = tf.equal(a, b) match = tf.cast(match, tf.int32) return tf.greater_equal(tf.reduce_sum(match), x)
5,310,463
def _imergeother(*args, **kwargs): """ Like :merge, but resolve all conflicts non-interactively in favor of the other `p2()` changes.""" success, status = _imergeauto(localorother='other', *args, **kwargs) return success, status, False
5,310,464
def MakeExtractor(sess, config, import_scope=None): """Creates a function to extract features from an image. Args: sess: TensorFlow session to use. config: DelfConfig proto containing the model configuration. import_scope: Optional scope to use for model. Returns: Function that receives an image...
5,310,465
def process_version_warning_banner(app, doctree, fromdocname): """ Insert an ``admonition`` with a custom/general message. """ banner = VersionWarningBanner(app, doctree) for document in doctree.traverse(nodes.document): banner = banner.get_banner_node() if isinstance(banner, nodes....
5,310,466
def visual_compare(file_names): """ This script is to visualize evaluation results simultaneously. Args: file_names (array of string): file names to be draw speed profile. """ # instantiate the class robots = [] records = [] for i in range(1,len(file_names)): f = open(fi...
5,310,467
def main(): """ Clears outputs from Notebook. Print errors and help messages as needed """ if len(sys.argv) == 1: print('\t') print('\tClean Output of Jupyter Notebook Files (note: must be in JSON format)') print('\t') print('\t\t-f : Force read of non-ipynb file') ...
5,310,468
def identifyTextures( datFile ): # todo: this function should be a method on various kinds of distinct dat file objects """ Returns a list of tuples containing texture info. Each tuple is of the following form: ( imageDataOffset, imageHeaderOffset, paletteDataOffset, paletteHeaderOffset, width, height, imageTy...
5,310,469
def solution(resources, args): """Problem 3 - Version 1 Find the largest prime factor with the use of this project's prime number utilities. Parameters: args.number The number whose largest prime factor to find Return: Return the largest prime factor of args.number. """ ...
5,310,470
def mint_fake_OCEAN(config): """ Does the following: 1. Mints tokens 2. Distributes tokens to TEST_PRIVATE_KEY1 and TEST_PRIVATE_KEY2 """ addresses_file = config.address_file with open(addresses_file) as f: network_addresses = json.load(f) web3 = Web3(provider=get_web3_connecti...
5,310,471
def get_player_actions(game, player): """ Returns player's actions for a game. :param game: game.models.Game :param player: string :rtype: set """ qs = game.action_set.filter(player=player) return set(list(qs.values_list('box', flat=True)))
5,310,472
def test_change_units(tmp_path): """Test extraction and unit conversion""" kgo_dir = acc.kgo_root() / "extract/change_units" kgo_path = kgo_dir / "kgo.nc" input_path = kgo_dir / "../basic/input.nc" output_path = tmp_path / "output.nc" args = [ input_path, "--constraints", ...
5,310,473
def mock_library(**attributes): """ Used to replace an attribute the library that :func:`dist.load` returns. Useful for replacing part of the compiled library as part of the test. """ ffi, library = dist.load() return patch.object( dist, "load", lambda: [ffi, LibraryWrapper(library,...
5,310,474
def CV_IS_SPARSE_MAT_HDR(*args): """CV_IS_SPARSE_MAT_HDR(CvMat mat) -> int""" return _cv.CV_IS_SPARSE_MAT_HDR(*args)
5,310,475
def parse_host_port(endpoint, default_protocol): """ parse protocol, host, port from endpoint in config :type: string :param endpoint: endpoint in config :type: baidubce.protocol.HTTP or baidubce.protocol.HTTPS :param default_protocol: if there is no scheme in endpoint, ...
5,310,476
def nfvi_kube_rootca_update_generate_cert(expiry_date, subject, callback): """Kube RootCA Update - Generate Cert""" cmd_id = _infrastructure_plugin.invoke_plugin( 'kube_rootca_update_generate_cert', expiry_date=expiry_date, subject=subject, callback=callback) return cmd_id
5,310,477
def _default_link_table2table(left, right): """Find default reference link between left and right tables. Returns (keyref, refop). Raises exception.ConflictModel if no default can be found. """ if left == right: raise exception.ConflictModel('Ambiguous self-link for table %s' % left)...
5,310,478
def quit_() -> None: """Quits the program, returns None.""" win.quit() win.destroy() return None
5,310,479
def create_lkas_ui(packer, main_on, enabled, steer_alert): """Creates a CAN message for the Ford Steer Ui.""" if not main_on: lines = 0xf elif enabled: lines = 0x3 else: lines = 0x6 values = { "Set_Me_X80": 0x80, "Set_Me_X45": 0x45, "Set_Me_X30": 0x30, "Lines_Hud": lines, "Ha...
5,310,480
def recover_password(user: schemas.UserBase) -> JSONResponse: """ Password Recovery """ db_user = get_active_user(email=user.email) if db_user is None: return JSONResponse(status_code=404, content={ "message": "The user with this email " "does not...
5,310,481
def plot_ellipses_MacAdam1942_in_chromaticity_diagram_CIE1960UCS( chromaticity_diagram_callable_CIE1960UCS=( plot_chromaticity_diagram_CIE1960UCS), chromaticity_diagram_clipping=False, ellipse_kwargs=None, **kwargs): """ Plots *MacAdam (1942) Ellipses (Observer PGN)* ...
5,310,482
def get_pytorch_device() -> torch.device: """Checks if a CUDA enabled GPU is available, and returns the approriate device, either CPU or GPU. Returns ------- device : torch.device """ device = torch.device("cpu") if torch.cuda.is_available(): device = torch.device("cuda:0") ...
5,310,483
def test_execution_store(cfg): """ Creates a proper test_execution store based on the current configuration. :param cfg: Config object. Mandatory. :return: A test_execution store implementation. """ logger = logging.getLogger(__name__) if cfg.opts("results_publishing", "datastore.type") == "...
5,310,484
def test_render_checkpoint_new_notebook_with_available_data_asset( deterministic_asset_dataconnector_context, titanic_expectation_suite, checkpoint_new_notebook_assets, ): """ What does this test and why? The CheckpointNewNotebookRenderer should generate a notebook with an example SimpleCheckpoi...
5,310,485
def creat_order_num(user_id): """ 生成订单号 :param user_id: 用户id :return: 订单号 """ time_stamp = int(round(time.time() * 1000)) randomnum = '%04d' % random.randint(0, 100000) order_num = str(time_stamp) + str(randomnum) + str(user_id) return order_num
5,310,486
def get_rst_title_char(level): """Return character used for the given title level in rst files. :param level: Level of the title. :type: int :returns: Character used for the given title level in rst files. :rtype: str """ chars = (u'=', u'-', u'`', u"'", u'.', u'~', u'*', u'+', u'^') if...
5,310,487
async def test_switch_change_light_state(hass, utcnow): """Test that we can turn a HomeKit light on and off again.""" helper = await setup_test_component(hass, create_lightbulb_service_with_hs) await hass.services.async_call( "light", "turn_on", {"entity_id": "light.testdevice", "br...
5,310,488
def python_to_ir(f, imports=None): """Compile a piece of python code to an ir module. Args: f (file-like-object): a file like object containing the python code imports: Dictionary with symbols that are present. Returns: A :class:`ppci.ir.Module` module .. doctest:: >>...
5,310,489
def get_endpoint_url(env, endpoint='public'): """Gets the Endpoint to use.""" endpoint_type = env.input('Endpoint (public|private|custom)', default=endpoint) endpoint_type = endpoint_type.lower() if endpoint_type == 'public': endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT elif endpoint_type ...
5,310,490
def compute_temperature_high_altitude(altitude: pint.Quantity) -> pint.Quantity: """Compute temperature in high-altitude region. Parameters ---------- altitude: quantity Altitude. Returns ------- quantity Temperature. """ r0 = R0 a = -76.3232 # K b = -19.94...
5,310,491
def load(config): """Load a CFNgin configuration by modifying syspath, loading lookups, etc. Args: config (:class:`Config`): The CFNgin config to load. Returns: :class:`Config`: The CFNgin config provided above. """ if config.sys_path: LOGGER.debug("appending to sys.path: ...
5,310,492
def merge_block_set(block_set: t.Iterable[Block], header: Header): """Merge a block set from a related collection of snapshots. The snapshots should belong to a single simulation. Otherwise, the routine could break, or data consistency is not guaranteed. :param block_set: The first block data to combi...
5,310,493
def _get_individual_lists(ws, ind_numbers = INDIVIDUAL_NUMBERS, behav_map = BEHAVIOR_MAPPING): """ returns {1 : [time, behav, start/stop] }""" start_row = _get_first_content_row(ws = ws) ret_dict = {} for j in range(start_row, ws.max_row + 1): if j % 100 == 0: print("****...
5,310,494
def generate_all(pkg_path, dest_path=os.getcwd()): """Generate a set of nsr and vnfrs based on a service package :param pkg_path: A string, a path to the package :param dest_path: A string, the target directory for the set of files :returns: a tuple with two elements. [0] is a bool with the result, ...
5,310,495
def normalize_prob_dictionary(prob_dict): """ Given a dictionary that describes probabilities of parameter values, normalize the probabilities so that they sum up to 1 :param dict: :return: """ sum = np.sum(list(prob_dict.values())) if sum > 0: for key in prob_dict.keys(): ...
5,310,496
def stsci_extraction_ranges(x1d, seg=''): """ Parameters ---------- x1d seg Returns ------- ysignal, yback """ cos, stis = _iscos(x1d), _isstis(x1d) xh, xd = x1d[1].header, x1d[1].data # below these will all be divided by 2 (except bk off). initially they specify the f...
5,310,497
def ending_at(row_key: str) -> pbt_C.RowRange: """Create a row range ending at given row (inclusive). Args: row_key (str): The ending row key of the range (inclusive). Returns: RowRange: The row range which ends at `row_key` (inclusive). """ return pbt_C.ending_at_row_range(row_key)
5,310,498
def test_get_contact_by_business_identifier_no_contact(session): # pylint:disable=unused-argument """Assert that a contact cannot be retrieved from an entity with no contact.""" entity_model = factory_entity_model(business_identifier='CP1234567') entity = EntityService(entity_model) contact = entity.ge...
5,310,499