content
stringlengths
22
815k
id
int64
0
4.91M
def test_clean_existing_slug(): """ If an album has a slug, cleaning it should not change the slug. """ slug = "my-slug" album = models.Album(slug=slug, title="Random Title") album.clean() assert album.slug == slug
5,309,700
def noise(nblock=None, state=None, color='white', ntaps=None): """Generate white noise with standard Gaussian distribution. :param nblock: Amount of samples per block. :param state: State of PRNG. :type state: :class:`np.random.RandomState` :returns: When `nblock=None`, individual samples are gener...
5,309,701
def euler2SO3_left(pitch, yaw, roll): """ Convert euler angles in degrees to a rotation matrix using XYZ order (valid)""" cos_pitch = np.cos(pitch*np.pi/180) sin_pitch = np.sin(pitch*np.pi/180) cos_yaw = np.cos(yaw*np.pi/180) sin_yaw = np.sin(yaw*np.pi/180) cos_roll = np.cos(roll*np.pi/180) ...
5,309,702
def clear_cache(query=None): """ clears cache in redis by query string :param query: :return: """ def search_key(q): def wrapper(key): if query in key: return 1 return 0 return wrapper is_low_cache_mem = False is_redise = False ...
5,309,703
def docker_push_dev_image(ctx, base_image=""): # type: ignore """ (ONLY CI/CD) Push the "dev" image to ECR. """ _report_task() docker_login(ctx) # image_dev = get_image("dev", base_image) cmd = f"docker push {image_dev}" _run(ctx, cmd, pty=True)
5,309,704
def get_pc_topk_shift(tensor, sparsity): """Input tensor must be batch of vectors. Returns a vector per batch sample of the shift required to make Hopfield converge. Assumes knowledge of Hopfield fixed sparsity.""" # Intuition: The output distribution must straddle the zero point to make hopfield work. # The...
5,309,705
def remove_from_watchlist(media): """Remove a :class:`TVShow` from your watchlist. :param media: Supports both the PyTrakt :class:`Movie`, :class:`TVShow`, etc. But also supports passing custom json structures. """ from trakt.tv import TVEpisode, TVSeason, TVShow from trakt.movies import Mov...
5,309,706
def debclean(name, partial, clean_opts, visibility = None): """Clean out some of the large, host-dependent, or unnecessary files from a debian installation.""" cmds = [ "ORIG=\"$$PWD\"", "BTEMP=\"$$(mktemp -d)\"", "tar -xzf '$<' -C \"$${BTEMP}\"", "cd \"$${BTEMP}\"", ] f...
5,309,707
def monthly_network_triplets_per_mno_indices(): """Index metadata for monthly_network_triplets_per_mno partitions.""" return [ IndexMetadatum(idx_cols=cols, is_unique=is_uniq, partial_sql=partial) for cols, is_uniq, partial in [ (['triplet_hash'], True, None), (['imei_nor...
5,309,708
def test_find_2018_cais_name_table26(): """ test function to dynamically look up names vs. expected result from separate file :return: True or False """ test_file = "School_Directory_2018-2019-converted.xlsx" results_file = "cais_name_counts_manual_2018-2019.xlsx" table_num = 26 found_i...
5,309,709
def print_table(input_dict, title='', header=('Key', 'Value'), style=('', '-')): """Print the dict in a table form""" assert input_dict.__class__ is dict, "Only accept class='dict'" if input_dict is None: return None max_string = 110 key_list = list(input_dict.keys()) val_list = list(ma...
5,309,710
def check_mesh_area_exist(x, mesh_area_coord): """Check the area coordinate is available in the xarray object.""" coords = list(x.coords.keys()) if not isinstance(mesh_area_coord, str): raise TypeError("'area_coord' must be a string specifying the area coordinate.") if mesh_area_coord not in coo...
5,309,711
def policy_compare(sen_a, sen_b, voting_dict): """ Input: last names of sen_a and sen_b, and a voting dictionary mapping senator names to lists representing their voting records. Output: the dot-product (as a number) representing the degree of similarity between two senators' voting p...
5,309,712
def _py2java(sc, obj): """ Convert Python object into Java """ if isinstance(obj, RDD): obj = _to_java_object_rdd(obj) elif isinstance(obj, DataFrame): obj = obj._jdf elif isinstance(obj, SparkContext): obj = obj._jsc elif isinstance(obj, (list, tuple)): obj = ListCon...
5,309,713
def kill_running_recordings(pids=None): """ kill list of pids """ if os.path.exists(KILLSCRIPT): run_command('sh %s' % KILLSCRIPT) os.remove(KILLSCRIPT) if os.path.exists(TESTSCRIPT): os.remove(TESTSCRIPT) if pids: _cmd = 'kill -9' for pid in pids: _cm...
5,309,714
def test_names(uqcsbot: MockUQCSBot): """ Test !pokemash with name arguments. """ uqcsbot.post_message(TEST_CHANNEL_ID, '!pokemash mr. mime scyther') messages = uqcsbot.test_messages.get(TEST_CHANNEL_ID, []) assert len(messages) == 2 assert messages[-1]['text'] == ("_Mr.ther_\n" ...
5,309,715
def docopt_attr(doc, argv=None, help=True, version=None, options_first=False): """docopt with options in attributes rather than dictionary elements args['--verbose'] => args.verbose args['<file>'] => arg.file All else remains the same. Attributes are single values or lists ...
5,309,716
def __main(): """Parse one or more XML files and render the corresponding UI.""" import argparse parser = argparse.ArgumentParser() parser.add_argument("filenames", nargs="+") args = parser.parse_args() master = tk.Tk() TkUI.from_file(master, args.filenames[0]).build() for filena...
5,309,717
def get_notebooks_run_in__jobs_update(): """ """ #| - get_notebooks_run_in__jobs_update #| - Read file lines # Jobs update method in bash_methods path_i = os.path.join( os.environ["PROJ_irox_oer"], "scripts/bash_methods.sh") with open(path_i, "r") as f: lines__bash_m...
5,309,718
def must_be_known(in_limit, out_limit): """ Logical combinatino of limits enforcing a known state The logic determines that we know that the device is fully inserted or removed, alerting the MPS if the device is stuck in an unknown state or broken Parameters ---------- in_limit : ``boo...
5,309,719
def delete_item(category_id, item_id): """ Deletes Item :param category_id: :param item_id: :return: render_template """ if 'username' not in login_session: return redirect('/login') category = session.query(Category).filter_by(id=category_id).one() item = session.query(Item).f...
5,309,720
def download_floras(): """Get the floras from the main page.""" url = SITE path = FAMILY_DIR / 'home_page.html' urllib.request.urlretrieve(url, path) with open(path) as in_file: page = in_file.read() floras = {} soup = BeautifulSoup(page, features='lxml') link_re = regex.compi...
5,309,721
def main(): """Transform k8s results to OSCAL.""" ytoo = YamlToOscal() # output ofolder = 'oscal' opath = pathlib.Path(ofolder) opath.mkdir(parents=True, exist_ok=True) # input ifolder = 'wg-policy-prototypes/policy-report/samples/' source_folder = SourceFolder(ifolder) # create ...
5,309,722
def scale(x): """Scales values to [-1, 1]. **Parameters** :x: array-like, shape = arbitrary; unscaled data **Returns** :x_scaled: array-like, shape = x.shape; scaled data """ minimum = x.min() return 2.0 * (x - minimum) / (x.max() - minimum) - 1.0
5,309,723
def group_data_by_columns(datasets, columns): """ :param datasets: [CxNxSxF] :param columns: F :return: CxNxFxS """ new_dataset = [] for i in range(len(datasets)): datalist = [] for row in range(len(datasets[i][0][0])): row_data = [] for column_idx in ...
5,309,724
def create_er_html(relations): """This function create entity-relationship html. Args: relations (list): List of (:class:`FieldPath` :class:`FieldPath`) Returns: Html str. A way might be used is >>> print create_structure_ers_from_relations([(FieldPath('db', 'ac', 'id'), FieldPath...
5,309,725
def plotlimit(ul, alpha=0.05, CLs=True, ax=None): """ plot pvalue scan for different values of a parameter of interest (observed, expected and +/- sigma bands) Args: ul: UpperLimit instance alpha (float, default=0.05): significance level CLs (bool, optional): if `True` uses pvalues ...
5,309,726
def test_generate_project() -> None: """ Test project generation :return: None """ # Clean if TESTS_ROOT.exists(): shutil.rmtree(TESTS_ROOT) TESTS_ROOT.mkdir() # Get path output_dir = TESTS_ROOT.resolve() # Launch project generation main.cookiecutter( str(R...
5,309,727
def output_results( output_path: pathlib.Path, data: typing.List, field_names: typing.List ): """ Outputs data to csv file. :param output_path: path to write to :param data: data to write :param field_names: field names to write """ with open(output_path, "w") as f: writer = csv...
5,309,728
async def spawn_carla( cuda_device: int, carla_world_port: int, log_file: BinaryIO ) -> asyncio.subprocess.Process: """Spawns CARLA simulator in the background. Returns the process handle.""" environ = os.environ.copy() environ["DISPLAY"] = "" environ["SDL_HINT_CUDA_DEVICE"] = f"{cuda_device}" ...
5,309,729
def rand_dm(N, density=0.75, pure=False, dims=None): """Creates a random NxN density matrix. Parameters ---------- N : int, ndarray, list If int, then shape of output operator. If list/ndarray then eigenvalues of generated density matrix. density : float Density between [0,1...
5,309,730
def GetStaticPipelineOptions(options_list): """ Takes the dictionary loaded from the yaml configuration file and returns it in a form consistent with the others in GenerateAllPipelineOptions: a list of (pipeline_option_name, pipeline_option_value) tuples. The options in the options_list are a dict: Key i...
5,309,731
def gen_signed_cert(domain, ca_crt="ca.crt", ca_key="ca.key", key_path="cert.key"): """ This function takes a domain name as a parameter and then creates a certificate and key with the domain name(replacing dots by underscores), finally signing the certificate using specified CA and returns the path of ...
5,309,732
def _nb_dir_file_profiler(path, _f, report=False): """Get the profile for a single file on a specified path.""" f = os.path.join(path, _f) if f.endswith('.ipynb'): if report: print(f'Profiling {f}') return process_notebook_file(f) return pd.DataFrame()
5,309,733
def main(connection, info, args, world) : """Ends a vote and returns the results""" votes = shelve.open("votes.db", writeback=True) if votes["networks"][connection.networkname][int(args[1]) - 1]["started"] : connection.msg(info["channel"], _("The vote on '%(topic)s' has ended. Here are the stats:")...
5,309,734
async def test_service_adjust_time_sequence_zone( hass: ha.HomeAssistant, skip_start, skip_dependencies, skip_history ): """Test adjust_time service call on a sequence zone.""" full_path = test_config_dir + "service_adjust_time_sequence_zone.yaml" config = CONFIG_SCHEMA(load_yaml_config_file(full_path)...
5,309,735
def validate_schema(response, expected_schema): """Please specify the parameters in the following order => (expected, actual)""" validate(instance=response, schema=expected_schema), "schema validation failed"
5,309,736
def ExtractNLargestBlobsn(binaryImage, numberToExtract=1): """Extract N largest blobs from binary image. Arguments: binaryImage: boolean numpy array one or several contours. numberToExtract: number of blobs to extract (integer). Returns: binaryImage: boolean numpy are containing on...
5,309,737
def network( site, vo, oidc_client_id, oidc_client_secret, oidc_refresh_token, oidc_access_token, oidc_url, oidc_agent_account, network_specs, network_output, ): """ Select suitable network according to network specifications on the given site/VO """ access_token ...
5,309,738
def awx_manage_check_license_data_datasource(broker): """ This datasource provides the not-sensitive information collected from ``/usr/bin/awx-manage check_license --data``. Typical content of ``/usr/bin/awx-manage check_license --data`` file is:: {"contact_email": "test@redhat.com", "company_...
5,309,739
def create_addresses(account_id): """ Create an Address on an Account This endpoint will add an address to an account """ app.logger.info("Request to add an address to an account") check_content_type("application/json") account = Account.find_or_404(account_id) address = Address() a...
5,309,740
def anderson( f, x0, m=5, max_iter=50, tol=1e-4, stop_mode='rel', lam=1e-4, beta=1.0, **kwargs ): """ Anderson acceleration for fixed point iteration. Args: f (`Callable` or `nn.Module`): Function to be minimized. x0 (`torch.Tensor`): A batch of vectors for the i...
5,309,741
def open_hdf5(fp, mode="r", *args, **kwargs): """ Context manager like ``h5py.File`` but accepts already open HDF5 file handles which do not get closed on teardown. Parameters ---------- fp : str or ``h5py.File`` object If an open file object is provided, it passes through unchanged, ...
5,309,742
def upload_story(source_file, dest_file): """ """ # When someone records a new story: # store the story on google cloud storage upload_blob(BUCKET_NAME, soure_file, dest_file) # write the url to reactive csv file # http://{BUCKET_NAME}.storage.googleapis.com/{FILE_NAME} # {BUCKET_N...
5,309,743
def flip_axis(x, axis): """flip tensor中的对应轴 # Args x: nd array axis: int, axis of x """ x = np.asarray(x) x = np.flip(x, axis=axis) return x
5,309,744
def beginning_of_day_utc(day_offset: int) -> datetime: """Return Local Midnight time of today +/- day_offset days in UTC time.""" return _apply_day_offset( datetime.now().replace(hour=0, minute=0, second=0, microsecond=0), day_offset ).astimezone(timezone.utc)
5,309,745
def test_exp_ts_stop( globals, urls, client, status, mock_test_responses, context_fixture): """Time series Experiment status fails if stopped during pending, running, and fail status, remains if in done status. The prediction following will fail if Time series Experiment fails. """ async def...
5,309,746
def test_my_word_to_vec_transformer(): """ Tests whether the monkey patching of ('example_pipelines.healthcare.healthcare_utils', 'MyW2VTransformer') works """ test_code = cleandoc(""" import pandas as pd from example_pipelines.healthcare.healthcare_utils import MyW2VTran...
5,309,747
def fit_austourists_with_R_params(model, results_R, set_state=False): """ Fit the model with params as found by R's forecast package """ params = get_params_from_R(results_R) with model.fix_params(dict(zip(model.param_names, params))): fit = model.fit(disp=False) if set_state: s...
5,309,748
def generate_environment_yml(): """Generate 'environment.yml' file.""" # needed for ordered dict, see https://stackoverflow.com/a/52621703 yaml.add_representer( OrderedDict, lambda self, data: yaml.representer.SafeRepresenter.represent_dict(self, data.items()), Dumper=yaml.SafeDumpe...
5,309,749
def draw_show_close(sorted_ret, target_count, show_cnt): """ 通过多少个交易日参数target_count,计算出make_kl_df的参数n_folds, 使用ABuScalerUtil.scaler_std将show_cnt个最相似的股票价格序列进行 标准化在一个数量值范围内可视化 :param sorted_ret: 可迭代序列,元素形如('usTSLA', 1.0), ('usSINA', 0.45565379371028253)..... :param target_count: 需要请求多少个交易日数据,int ...
5,309,750
async def execute( schema: "GraphQLSchema", document: "DocumentNode", response_builder: Callable, root_value: Optional[Any], context: Optional[Any], variables: Optional[Dict[str, Any]], operation_name: Optional[str], ) -> Dict[str, Any]: """ Runs the execution of the executable opera...
5,309,751
def print_dataframe_exploration_info(df): """ Prints some exploration information of the dataframe. :param df: Data Frame Object """ # Shape print('Data frame shape: {0}'.format(df.shape)) # Header print('\n---Data frame header ---\n{0}'.format(df.head())) print('---') # Descript...
5,309,752
def validate_ip_addr(addr, version): """ Validates that an IP address is valid. Returns true if valid, false if not. Version can be "4", "6", None for "IPv4", "IPv6", or "either" respectively. """ try: ip = netaddr.IPAddress(addr, version=version) return True except (netaddr....
5,309,753
def orchestrator(): """ Function to: Create new MySQL DB Orchestrate setting up multiprocessing processes in groups """ start = datetime.now() logger.info('Module starting') create_tables() procs = [] hostnames = open(cwd + '/switchlist1.txt').readlines() for group in ge...
5,309,754
def create_localized_datetime(*args, timezone='UTC', **kwargs): """ Creates an aware time in the given timezone. The intuitive way of doing this will give you the wrong answer: https://stackoverflow.com/questions/24856643/unexpected-results-converting-timezones-in-python So, this method does it co...
5,309,755
def resnet18(resnet_cls, **kwargs): """Construct a ResNet-18 model.""" return resnet_cls(block=BasicBlock, layers=[2, 2, 2, 2], **kwargs)
5,309,756
def beautify_declaration_markup(markup : str) -> str: """Format our function and class declarations in NOMNOML to be a consistent size""" # We do not want to break before separators or before the end of a word # A 'word' in this case may include a trailing colon # Also catch function annotations with -...
5,309,757
def calibration_run(param_set_dirpath: str) -> str: """ Allows a user to select what model run they want, given an app Returns the directory name selected. """ # Read model runs from filesystem model_run_dirs = os.listdir(param_set_dirpath) # Parse model run folder names model_runs = [...
5,309,758
def post(host, path, data): """Sends POST request using HttpClient and the data from GUI form. :param host: host ip addr :param path: resource endpoint path :param data: data to be sent as body of the POST request :return: HTTP response body """ cover = open(data, 'rb').read() print('Sen...
5,309,759
def round_trip_pathlib(writer, reader, path: Optional[str] = None): """ Write an object to file specified by a pathlib.Path and read it back Parameters ---------- writer : callable bound to pandas object IO writing function (e.g. DataFrame.to_csv ) reader : callable IO reading f...
5,309,760
def conv_junc_to_exon(): """ Converting sorted junctions to exons here """ def overlap(start, end, start2, end2): return not (start > end2 or end < start2) cons_exons = [] overlaps = 0 prev_astart, prev_aend = juncs[0][-2], juncs[0][-1] prev_jstart, prev_jend = juncs[0][2], juncs[0][3] ...
5,309,761
def check_temperature (device, root_dir): """Check the temperature status and generates files with the tests result. Required EOS command: show system environment temperature | json Test failure conditions: A sensor test fails if a sensor HW status is not OK or if a sensor alert count is > 0 or if a sensor...
5,309,762
def save_samples( samples: Iterable[TextWithActions], converter: ActionStringConverter, text_file: str, actions_file: str ) -> None: """ Saves samples of sentences with corresponding actions to files. Sentences and actions are saved to different files, which corresponds to the input required by Open...
5,309,763
def create_folder_hierarchy(item, user, folder): """ Create a folder hierarchy that matches the original if the original is under a project folder. :param item: the item that will be moved or copied. :param user: the user that will own the created folders. :param folder: the destination project...
5,309,764
def compute_eval_metrics(gt_mask, pred_mask): """ Evaluate a mask w.r.t a GT mask :param gt_mask: m x n grid of 0s and 1s :param pred_mask: m x n grid of 0s and 1s :return: """ assert (gt_mask.size == pred_mask.size) tp = float(np.sum(np.logical_and(pred_mask == 1, gt_mask == 1))) fp...
5,309,765
def load_current_test_data(collection_name="current_test_data"): """loads the current test data and converts it back to normal Args: collection_name (str, optional): name of the collection. Defaults to "current_test_data". Returns: List of DataFrames: List of the current test DataFrames ...
5,309,766
def convolutional_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)): """A block that has a conv layer at shortcut. Arguments: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters...
5,309,767
def check_type_data(data, data_type=np.ndarray, dim=2): """ Some basic type checking on data """ # Code assumes that we have a matrix, so force it for single samples if len(data.shape)==1: data = data.reshape((data.size,1)) if type(data) != data_type: raise TypeError('d...
5,309,768
def available_model(): """ List available speaker change deep models. """ from malaya_speech.utils import describe_availability return describe_availability( _availability, text='last accuracy during training session before early stopping.', )
5,309,769
def is_date_field(field, field_schema): """ Helper method that determines if field_schema is """ return determine_if_is_date_field(field, field_schema)
5,309,770
def generate_script_pick_and_place_block(tcp, frames, ur_ip, ur_port, velocity = 0.05, radius = 0, vacuum_on=2, vacuum_off=5): """Generate multiple linear movements and Airpick on/off commands. Parameters ---------- tcp : sequence of float Tool center point in a form of list. tcp = [x, ...
5,309,771
def classify_stop(data): """ classifies stops for stop light or errands using speed data :param data: the speed data """ # classifies errands for index, point in enumerate(data): if point.speed == 0: # if car not moving if index == len(data) - 1: # if last point, classify a...
5,309,772
def serialize_features(susp, src, features, outdir): """ Serialze a feature list into a xml file. The xml is structured as described in the readme file of the PAN plagiarism corpus 2012. The filename will follow the naming scheme {susp}-{src}.xml and is located in the current directory. Existing fi...
5,309,773
def make_splici_txome( genome_path, gtf_path, read_length, output_dir, flank_trim_length=5, filename_prefix="splici", extra_spliced=None, extra_unspliced=None, dedup_seqs=False, no_bt=False, bt_path="bedtools", no_flanking_merge=False, ): """ Construct the splici ...
5,309,774
def ThrowError(msg, *args): """Log an error to the node daemon and the raise an exception. @type msg: string @param msg: the text of the exception @raise errors.BlockDeviceError """ if args: msg = msg % args logging.error(msg) raise errors.BlockDeviceError(msg)
5,309,775
def get_ds003_downsampled(data_dir=None, url=None, resume=True, verbose=1): """Download and load the BIDS-fied ds003_downsampled :param str data_dir: path of the data directory. Used to force data storage in a non-standard location. :param str url: download URL of the dataset. Overwrite the defaul...
5,309,776
def open_clean_bands(band_path, valid_range=None,): """Open/mask single landsat band using a valid reflectance value range. Parameters ----------- band_path : string A path to the array to be opened valid_range : tuple (optional) A tuple of min and max values of...
5,309,777
def test_duplicate_names(): """Check that there are no duplicate names in the fully_qualified except for differnt variants""" for lang in all_languages(): check_duplicate_names(lang)
5,309,778
def test_tablemodel(test_program_dao): """Get a data manager instance for each test class.""" # Create the device under test (dut) and connect to the database. dut = RAMSTKRequirementTable() dut.do_connect(test_program_dao) dut.do_select_all(attributes={"revision_id": 1}) yield dut # Unsub...
5,309,779
def calculate_new_case_data_by_region( region_timeseries: OneRegionTimeseriesDataset, t0: datetime, include_testing_correction: bool = False, testing_correction_smoothing_tau: float = 5, ) -> Tuple[np.array, np.array]: """ Calculate new cases from combined data. Args: region_timeser...
5,309,780
def apply(post_body): """ 导入 post_body 对应的 trait 数据 :return: """ response = requests.post(ENDPOINT + '/traits', data=post_body) response_json = response.json() if response_json.get('code') != 200: logger.error('import trait to appmanager failed, response=%s' % response.text) ...
5,309,781
def _field_object_metadata(field_object): """Return mapping of field metadata key to value. Args: field_object (arcpy.Field): ArcPy field object. Returns: dict. """ meta = {"object": field_object} key_attribute_name = { "alias_name": "aliasName", "base_name": "b...
5,309,782
def test_get_state_summary_none(subject: RunStore) -> None: """It should return None if no state data stored.""" subject.insert( run_id="run-id", protocol_id=None, created_at=datetime(year=2021, month=1, day=1, tzinfo=timezone.utc), ) result = subject.get_state_summary(run_id="ru...
5,309,783
def _cohn_kanade(datadir, im_shape, na_val=-1): """Creates dataset (pair of X and y) from Cohn-Kanade image data (CK+)""" images = [] labels = [] for name in os.listdir(os.path.join(datadir, 'faces')): impath = os.path.join(datadir, 'faces', name) labelpath = os.path.join(datadir, 'l...
5,309,784
def test_creation_exception_empty(): """Verify that an exception is thrown when the inputs are missing.""" with pytest.raises(TypeError): ComplesTypeStub()
5,309,785
def svn_utf_initialize2(*args): """svn_utf_initialize2(svn_boolean_t assume_native_utf8, apr_pool_t pool)""" return _core.svn_utf_initialize2(*args)
5,309,786
def init_console(parser): """Initialises the console""" font = pygame.font.SysFont("Courier", 12) text = Text(font, size=(200, 40), position=(0, 0)) error_text = init_error_message(parser) return Console(parser, text, error_text)
5,309,787
def _xinf_ND(xdot,x0,args=(),xddot=None,xtol=1.49012e-8): """Private function for wrapping the fsolving for x_infinity for a variable x in N dimensions""" try: result = fsolve(xdot,x0,args,fprime=xddot,xtol=xtol,full_output=1) except (ValueError, TypeError, OverflowError): xinf_val = NaN...
5,309,788
def read_targets(targets): """Reads generic key-value pairs from input files""" results = {} for target, regexer in regexer_for_targets(targets): with open(target) as fh: results.update(extract_keypairs(fh.readlines(), regexer)) _LOG.debug("found the following key-value pairs in sour...
5,309,789
async def refresh_pool_ledger(handle: int) -> None: """ Refreshes a local copy of a pool ledger and updates pool nodes connections. :param handle: pool handle returned by indy_open_pool_ledger :return: Error code """ logger = logging.getLogger(__name__) logger.debug("refresh_pool_ledger: >...
5,309,790
def schema_validation_space(): """Create a space with schema validation.""" schema = ( '{"definitions":{},"$schema":"http://json-schema.org/draft-07/schema#",' '"$id":"http://example.com/root.json","type":"object",' '"title":"TheRootSchema","required":["geometry","type","properties"]}' ...
5,309,791
async def test_async_update(monkeypatch): """Test async_update().""" _mock = TeslaMock(monkeypatch) _controller = Controller(None) _data = _mock.data_request_vehicle() _sensor = ChargingSensor(_data, _controller) await _sensor.async_update() assert not _sensor is None assert _sensor....
5,309,792
def seconds_function(context, string=None): """ The date:seconds function returns the number of seconds specified by the argument string. If no argument is given, then the current local date/time, as returned by date:date-time is used as a default argument. Implements version 1. """ if stri...
5,309,793
def hyper_param_search(config, num_tries=10, gpus_per_trial=1, cpus_per_trial=4): """Hyper parameter sweep. Automatically manages resources so all GPUs are used. Includes early stopping. Args: config: num_tries: Number of combinations to try gpus_per_trial (fl...
5,309,794
def mean_of_cluster(list_of_points): """Calculates the center of the list of points """ number_of_points = float(len(list_of_points)) vector_total = [float(0), float(0)] for point in list_of_points: for index, component in enumerate(point): vector_total[index] += component re...
5,309,795
async def test_ignored_url(async_client, caplog, monkeypatch): """ Test that a URL specified in IGNORE_URLS is ignored in the async view :param async_client: Django async client :param caplog: Caplog fixture :param monkeypatch: Monkeypatch for django settings """ mocked_settings = deepcopy(d...
5,309,796
def add_linear_layer_mip(network, layer_no, model, var_dict, var_input_key, var_output_key): """ Method to add the variables and constraints to handle a linear layer """ fc_layer = network.fcs[layer_no] fc_weight = utils.as_numpy(fc_layer.weight) if fc_layer.bias is not Non...
5,309,797
def symlog(values, threshold): """ Convert values to log with linear threshold near zero """ return np.sign(values) * np.log10(1 + np.abs(values) / threshold)
5,309,798
def report_result(name, target_latency, final_result, result_list, result_dict, check_acc=False): """Record a result in the final_result dict and write it to stdout.""" result = {} # the percentiles we want to record percentiles = [50., 80., 90., 95., 99., 99.9] buckets = np.percentile(result_list, ...
5,309,799