content
stringlengths
22
815k
id
int64
0
4.91M
def is_special_identifier_char(c): """ Returns `True` iff character `c` should be escaped in an identifier (i.e. it is a special character). """ return c in ( ESCAPEMENT_SYM, OLD_COMMENT_SYM, FILE_INCLUSION_SYM, UNIT_START_SYM, UNIT_END_SYM, ALIAS_SYM, SLOT_SYM, INTENT_SYM, C...
5,318,700
def delete_board(request): """ Removes the saved game board from user's profile. User must be authenticated, i.e. must have the matching token. Game board in the user's profile identified by game_id must exist. user_id: unique user identifier (same as username). token: authentication token that ...
5,318,701
def map_2d(all_scores: np.ndarray, thresholds: np.ndarray, epochs: np.ndarray, model_name: str, output_dir: str, if_save: bool=False) -> None: """ Plot all scores heatmap Args: all_scores: array of mAP scores thresholds: array of thresholds epochs : array of epochs mode...
5,318,702
def role_name_with_more_than_128_characters(self, ldap_server, ldap_user): """Check that we can map a role that contains more than 128 characters.""" uid = getuid() role_name = f"role_{uid}_{'r'*128}" map_role(role_name=role_name, ldap_server=ldap_server, ldap_user=ldap_user)
5,318,703
def showPlot(surface, save = True, folderName = '', fileName = '', file_format = 'PNG', showImage = True): """ Display the diagram and save it to the local. Args: surface: skia.Surface. fileName: str-the name for the generated file: either the input filename or temp.pn...
5,318,704
def test_module(client: Client) -> str: """Tests API connectivity and authentication' Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Raises exceptions if something goes wrong. :type client: ``Client`` :param Client: RubrikPo...
5,318,705
def cnn_v0(state, num_actions, scope, channels=32, activation_fn=None, is_training=True, reuse=False, use_timestep=True): """CNN architecture for discrete-output DQN. Args: state: 2-Tuple of image and timestep tensors: (image, timeste...
5,318,706
def get_collections(expand=False, as_dataframe=False): """Get available collections. Collections are folders on the local disk that contain downloaded or created data along with associated metadata. Args: expand (bool, Optional, Default=False): include collection details and format...
5,318,707
def jsonable_safe(obj): """Convert to JSON-able, if possible. Based on fastapi.encoders.jsonable_encoder. """ try: return jsonable_encoder(obj, exclude_none=True) except: return obj
5,318,708
def classify_segment(data: list, no_of_outliers: int, acceptable_outlier_percent: float = .34) -> object: """ :param data: A list of Datapoints-current window :param no_of_outliers: The number of datapoints in the current window assigned as outliers :param acceptable_outlier_percent: The acceptable out...
5,318,709
def nearest_neighbor(v, candidates, k=1): """ Input: - v, the vector you are going find the nearest neighbor for - candidates: a set of vectors where we will find the neighbors - k: top k nearest neighbors to find Output: - k_idx: the indices of the top k closest vectors in sorted fo...
5,318,710
def reverse(x): """ :type x: int :rtype: int """ new_str = str(x) i = 1 rev_str = new_str[::-1] if rev_str[-1] == "-": rev_str = rev_str.strip("-") i = -1 if (int(rev_str)>=2**31): return 0 return (int(rev_str)) * i
5,318,711
def create_request( service: str, request: str, settings: list = None, ovrds: list = None, append: dict = None, **kwargs, ) -> blpapi.request.Request: """ Create request for query Args: service: service name request: request name setti...
5,318,712
async def simulate_time(hass, mock_lj, delta): """Test to simulate time.""" _LOGGER.info( "*** simulate time change by %s: %s", delta, mock_lj.start_time + delta ) mock_lj.last_delta = delta with mock.patch( "homeassistant.helpers.condition.dt_util.utcnow", return_value=mock_...
5,318,713
def delete_byID(iid): """ Delete an item by ID """ global conn, curs try: sql = "DELETE FROM tbl_inc_exp WHERE id={}".format(iid) curs.execute(sql) conn.commit() return True except: return False
5,318,714
def test_incompatible_modules(): """Verifies that chosen modules are not mutually-exclusive.""" helpers.log_status(cast(FrameType, currentframe()).f_code.co_name) result = helpers.execute_command( ["-v", "provision", "--module", "ldap", "--module", "test"] ) assert result.exit_code == 2 ...
5,318,715
def _get_required_checks_and_statuses(pr, cfg): """return a list of required statuses and checks""" ignored_statuses = cfg.get( 'bot', {}).get( 'automerge_options', {}).get( 'ignored_statuses', []) required = ["linter"] with tempfile.TemporaryDirectory() as tmpdir: ...
5,318,716
def get_props(adapter=None, device=None, service=None, characteristic=None, descriptor=None): """ Get properties for the specified object :param adapter: Adapter Address :param device: Device Address :param service: GATT Service UUID :par...
5,318,717
def table_entry_pretty_print(entry, indent, line_wrap=-1): ############################################################################### """Create and return a pretty print string of the contents of <entry>""" output = "" outline = "<{}".format(entry.tag) for name in entry.attrib: outline += "...
5,318,718
def part_1(input_data: list[int]) -> int: """Count the number of times a depth measurement increases from the previous measurement. Args: input_data (str): depths Returns: int: number of depth increases """ inc_count = 0 for i, depth in enumerate(input_data): if i != 0 a...
5,318,719
def find_base_split_commit(split_dir, base_commit) -> Optional[str]: """ Return the hash of the base commit in the specified split repository derived from the specified monorepo base commit. """ mono_base_commit = git_output('rev-list', '--first-parent', '-n', '1', '--grep', ...
5,318,720
def evaluate(roughness, eta, wo, wi, dist): # return brdf value (didn't multiply cos) """Evaluate BRDF and PDFs for Walter BxDF.""" # eta is assumed > 1, and it is the refractive index of the side of the # surface facing away from the normal. rGain = 1.0 boostReflect = 1.0 tAlbedo = np.arr...
5,318,721
def round_floats(number): """A function which converts float values of comparison scores into floats with no more than two decimal figures. No precision is lost this way - the point is to convert numbers like 1.7499999999 into 1.75. Arguments: number (float): the value of a comparison sco...
5,318,722
def hyp_ewc(args, avg_runs_exp): """ Grid search for EWC: Learning rate and Lambda """ ls, lambdas = (0.1, 0.05, 0.01, 0.001), (1, 10, 100) best_hyp, best_acc = 0, 0 for l in ls: args.lr =l for b in lambdas: args.lambd = b print(l, b) args.seed = 0 acc = avg_runs_exp(args.runs, validate=True) i...
5,318,723
async def async_create_entities(hass, config): """Create the template binary sensors.""" sensors = [] for device, device_config in config[CONF_SENSORS].items(): value_template = device_config[CONF_VALUE_TEMPLATE] icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_t...
5,318,724
def update_data(context): """Start scraping for update file""" scraping.start_scraping()
5,318,725
async def fetch_user(bearer: str) -> dict: """Fetch information about a user from their bearer token.""" headers = {"Authorization": f"Bearer {bearer}"} async with aiohttp.ClientSession(headers=headers, raise_for_status=True) as sess: resp = await sess.get(f"{API_BASE}/users/@me") return awa...
5,318,726
def agriZone_Ep_Sa_beta_Fvar(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP - Outgoing fluxes are determined based on (value in previous timestep + inflow) and if this leads to negative storage, the outgoing f...
5,318,727
def select_model(model_path): """ select model """ model_str = os.path.basename(model_path) model_str = model_str.split('.py')[0] import_root = ".".join((model_path.split(os.path.sep))[:-1]) exec("from %s import %s as model" % (import_root, model_str)) model.EXP_NAME = model_str return mod...
5,318,728
def single_varint(data, index=0): """ The single_varint function processes a Varint and returns the length of that Varint. :param data: The data containing the Varint (maximum of 9 bytes in length as that is the maximum size of a Varint). :param index: The current index within the data. :ret...
5,318,729
def ReadUCDLines(in_file, want_ranges=True, want_other=False, want_comments=False, want_missing=False): """Parses lines from a semicolon-delimited UCD text file. Strips comments, ignores empty and all-comment lines. Returns a tuple (type, line, ...). """ for line in in_file: line = line.s...
5,318,730
def dict_from_corpus(corpus): """ Scan corpus for all word ids that appear in it, then construct and return a mapping which maps each `wordId -> str(wordId)`. This function is used whenever *words* need to be displayed (as opposed to just their ids) but no wordId->word mapping was provided. The res...
5,318,731
def read_fastspecfit(fastfitfile, fastphot=False, rows=None, columns=None): """Read the fitting results. """ if os.path.isfile(fastfitfile): if fastphot: ext = 'FASTPHOT' else: ext = 'FASTSPEC' hdr = fitsio.read_header(fastfitfile, ext='METADATA'...
5,318,732
def mat2dict(matobj): """ A recursive function that constructs nested dictionaries from matobjects """ dictionary = {} for strg in matobj._fieldnames: elem = matobj.__dict__[strg] if isinstance(elem, scio.matlab.mio5_params.mat_struct): dictionary[strg] = mat2dict(elem) ...
5,318,733
def build_stop_sign(): """ This function creates a stop sign with GLabel :return: object, sign """ random_x = random.randint(0, 640) random_y = random.randint(30, 500) sign = GLabel('Stop Clicking !!! ', x=random_x, y=random_y) sign.color = 'firebrick' sign.font = 'Times New...
5,318,734
def name_atom(atom): """->symbol Return the atom symbol for a depiction. Carbons atoms in general are not returned""" symbol = "%s"%(atom.symbol,) weight = atom.weight charge = atom.charge hcount = atom.hcount explicit_hcount = atom.explicit_hcount out_symbol = symbol # pyrole ...
5,318,735
def test_non_iterable_error(): """ Test the error message we give if a user accidentally passes a generator function without evaluating it. This is only to give a friendlier error message for a fairly common error. I still do it sometimes so this helps me as much as anyone. """ def gen(): ...
5,318,736
def preview_convert(file_in, command, size, gm_or_im): """ preview generation file_in - fullname image file dir_temp - fullname temporary directory command - additional command for imagemagick or space -- return: fullname preview file and size """ try: image_size = magick.get...
5,318,737
def rot3D(x, r): """perform 3D rotation Args: x (np.array): input data r (float): rotation angle Returns: np.array: data after rotation """ Rx = np.array([[1, 0, 0], [0, math.cos(r[0]), -math.sin(r[0])], [0, math.sin(r[0]), math.cos(r[0])]]) Ry = np.array([[math.cos(r[1])...
5,318,738
def install(args): """Install a cloud native vulnerability. Install a vulnerable cloud native gadget with one vulnerability specified by args.cnv. Args: args.cnv: Name of the specified cloud native vulnerability. args.verbose: Verbose or not. args.http_proxy: HTTP proxy. ...
5,318,739
def perform_move(move: Move, attacking_creature: BattleCreature, defending_creature: BattleCreature, static_game_data: StaticGameData): """ Performs the move by the attacking creature on the defending_creature. This can change both the attacking creature, the defending creature and cause me...
5,318,740
def _shake_shake_layer(x, output_filters, num_blocks, stride, is_training): """Builds many sub layers into one full layer.""" for block_num in range(num_blocks): curr_stride = stride if (block_num == 0) else 1 x =...
5,318,741
def filter_nan_values(data: DataFrame, used_cols: Optional[list[str]] = None): """ Filter NaNs in columns that are used for futher calculations :param data: Dataframe with full dataset :type data: DataFrame :param used_cols: Columns to check, None checks all, defaults to None :t...
5,318,742
def dropout(inputs, is_training, scope, keep_prob=0.5, noise_shape=None): """ Dropout layer. Args: inputs: tensor is_training: boolean tf.Variable scope: string keep_prob: float in [0,fv_noise] noise_shape: list of ints Returns:...
5,318,743
def test_trained_model(test_data, clf_name, model_dir_path = '', iteration_number = 0, is_abnormal = False, threshold_value = 0): """ Test any model. :param test_data: :param clf_name: ...
5,318,744
def tumor_list(version): """ version: cross validation version and train or val """ path_list = [] for i in version: paths = sorted(glob.glob(f'./data/tumor_-150_150/{i}/label_*/*.npy')) path_list.extend(paths) return path_list
5,318,745
def test_create_fail_on_dimensions_content(): """ Fail to create unit with bad dimensions expr. """ a = Symbol("a") with pytest.raises(UnitParseError): Unit("a", base_value=1, dimensions=a)
5,318,746
def roles_allowed(roles): """Takes a list of roles allowed to access decorated endpoint. Aborts with 403 status if user with unauthorized role tries to access this endpoint. :param list roles: List of roles that should have access to the endpoint. """ def roles_allowed_decorator(fn): @...
5,318,747
def get_offsets( text: str, tokens: List[str], start: Optional[int] = 0) -> List[int]: """Calculate char offsets of each tokens. Args: text (str): The string before tokenized. tokens (List[str]): The list of the string. Each string corresponds token. ...
5,318,748
def print_adv(file, close=True): """ Print the advertisement (qpage footer) :param file : The file that should adv to it. :param close : Close file after add :type file:_io.TextIOWrapper :type close:bool :return: None """ file.write(BREAK_LINE) file.write( '<center>' + "...
5,318,749
def diff_num_centered(S): """ numerical flux with a centered scheme for the dissipative part """ # Ui = [rhoe, rhoe ee] at the interfaces Ui = .5*(S.sol_glob[1:,:] + S.sol_glob[:-1,:]) # dUidx = [grad Te, grad pe] at the interfaces dUidx = np.stack(( (S.P.gamma-1.)/S.dx * np.diff(S....
5,318,750
def get_content_ref_if_exists_and_not_remote(check): """ Given an OVAL check element, examine the ``xccdf_ns:check-content-ref`` If it exists and it isn't remote, pass it as the return value. Otherwise, return None. ..see-also:: is_content_href_remote """ checkcontentref = check.find("./{%...
5,318,751
def plot_corner(samples, lc, meta, freenames, fitter): """Plot a corner plot. (Figs 5501) Parameters ---------- samples: ndarray The samples produced by the sampling algorithm lc: eureka.S5_lightcurve_fitting.lightcurve.LightCurve The lightcurve data object freenames: iterable ...
5,318,752
def sat_pass(sats, t_arr, index_epoch, location=None): """Find when a satellite passes above the horizon at a gps location. Calculate the :samp:`Altitude` & :samp:`Azimuth` of a :class:`~skyfield.sgp4lib.EarthSatellite` object from :func:`~embers.sat_utils.sat_ephemeris.load_tle` at every instant o...
5,318,753
def get_logit_model(x_train: pd.DataFrame, y_train: pd.Series) -> LogisticRegression: """ Train and return a logistic regression model """ lr = LogisticRegression(penalty='l2', solver='lbfgs', fit_intercept=False, interc...
5,318,754
def makearglists(args: Dict[str, Any]) -> Tuple[str, str]: """ Returns the python code for argument declaration and argument passing to the function that does the work Parameters ---------- args: dict Arg info for function returned by Wash Leg website Returns ------- arg_de...
5,318,755
def task1(): """Task1 function of API3 Returns: [str]: [Return string] """ logger.info("In API3 task1 function") return "task1 success!"
5,318,756
def _METIS_PartGraphKway(nvtxs, ncon, xadj, adjncy, vwgt, vsize, adjwgt, nparts, tpwgts, ubvec, options, objval, part): """ Called by `part_graph` """ return _METIS_PartGraphKway.call( nvtxs, ncon, xadj, adjncy, vwgt, vsize, adjwgt, nparts, tpwgts, ubvec, options...
5,318,757
def _compute_norm_factor(array, nfft, dim, dx, tapering, sym=True): """Compute the normalization factor for Power Spectrum and Power Spectrum Density """ try: ps_factor = array.attrs['ps_factor'] except KeyError: ps_factor = 1. try: psd_factor = array.attrs['psd_factor'] except KeyError: psd_factor = 1. ...
5,318,758
def parse_ocr_result(ocr_result, drms): """ Parses and extract data from the OCR document result string by using a DRM (Document Regexp Model) that matches this OCR string. Args: ocr_result (str): OCR result string; drms (dict): list of all DRMs dicts found in the DRM directory folder. ...
5,318,759
def payment_insert(conn, payment_info): """ Inserts a row in 'payment' table with the values passed in 'payment_info' Parameters: conn: Connection object payment_info: a tuple of values to insert """ try: sql = " INSERT into payment(payment_id, user_id, payment_method, paymen...
5,318,760
def plot_pareto_frontier( frontier: ParetoFrontierResults, CI_level: float = DEFAULT_CI_LEVEL, show_parameterization_on_hover: bool = True, ) -> AxPlotConfig: """Plot a Pareto frontier from a ParetoFrontierResults object. Args: frontier (ParetoFrontierResults): The results of the Pareto fro...
5,318,761
def test_validate() -> None: """Test validate method.""" connect = Connect(connect_url="http://localhost:8083") connect_config = InfluxConfig( name="influxdb-sink", connect_influx_url="http://localhost:8086", connect_influx_db="mydb", tasks_max=1, connect_influx_usern...
5,318,762
def filenames( directory, file_stem, file_ext=DEFAULT_FILE_EXT, stamp_regex=DEFAULT_STAMP_REGEX ): """Generate all filenames with matching stem Parameters ---------- directory : pathlib.Path Path to directory holding file file_stem : str File stem, filename without timestamp and...
5,318,763
def initialize(args=None, **kwargs): """ Initialize the plugin system. You may use the following arguments to configure the plugin system: ============== ============== ============ Argument Default Description ============== ============== ============ discover ``...
5,318,764
def add_vqsr_eval_jobs( b: hb.Batch, dataproc_cluster: dataproc.DataprocCluster, combined_mt_path: str, rf_annotations_ht_path: str, info_split_ht_path: str, final_gathered_vcf_path: str, rf_result_ht_path: Optional[str], fam_stats_ht_path: Optional[str], freq_ht_path: str, work_...
5,318,765
def is_readable(path): """ This function checks to see if a file or a directory can be read. This is tested by performing an operation that requires read access on the file or the directory. """ if os.path.isdir(path): try: os.listdir(path) except (OSError, IOError): ...
5,318,766
def interpolate(r, g, b): """ Interpolate missing values in the bayer pattern by using bilinear interpolation Args: red, green, blue color channels as numpy array (H,W) Returns: Interpolated image as numpy array (H,W,3) """ # # You code here # ''' rb各四分之一 ...
5,318,767
def test_molchoose_nofile(): """Tests that the FileNotFoundError works as expected""" #tests that an error is raised if a non-existent file is passed to it with pytest.raises(FileNotFoundError): combine.MolChoose('C', 'c', DataSource ='data/no_such_file.csv')
5,318,768
def heatmap(pois, sample_size=-1, kwd=None, tiles='OpenStreetMap', width='100%', height='100%', radius=10): """Generates a heatmap of the input POIs. Args: pois (GeoDataFrame): A POIs GeoDataFrame. sample_size (int): Sample size (default: -1; show all). kwd (string): A keyword to filter...
5,318,769
def _color_int_to_rgb(integer: int) -> Tuple[int, int, int]: """Convert an 24 bit integer into a RGB color tuple with the value range (0-255). Parameters ---------- integer : int The value that should be converted Returns ------- Tuple[int, int, int]: The resulting RGB tupl...
5,318,770
def get_geometry_origin_mesh(obj): """ Get the mesh which is most suitable for origin of visual mesh. obj: Object(ID) """ # TODO: Use better way than this in finding relative inertial mesh inertia_meshes = [c for c in obj.parent.children if c.phobostype == 'inertial' and 'inertial_' + ...
5,318,771
def train_neural_network(x): """Function to train neural network.. Args: x (tensor): input data """ prediction = neural_network_model(x) # cost Function cost = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) cost = tf.reduce_mean(cost) # optimizing optim...
5,318,772
def read_fchk(in_name): """ Read a Gaussian .fchk. Returns the total energy, gradients and ground state energy. Parameters ---------- in_name : str Name of the file to read Returns ------- energy : float Gaussian total calculated energy in Hartree grad : list of...
5,318,773
def main(qhp_file): """TODO: Docstring for main. :returns: TODO """ src_file = open(qhp_file) dst_file = open(os.path.dirname(src_file.name) + os.path.sep + 'index-fix.qhp', 'w') soup = BeautifulSoup(src_file, 'xml') keywords = soup.findAll('keyword') for keyword in keywords: kid = keyword['id'] ...
5,318,774
def miles(kilometers=0, meters=0, feet=0, nautical=0): """ Convert distance to miles. """ ret = 0. if nautical: kilometers += nautical / nm(1.) if feet: kilometers += feet / ft(1.) if meters: kilometers += meters / 1000. ret += kilometers / 1.609344 return ret
5,318,775
def test_get_defaults(): """Tests Boids Setup Parameters get defaults method""" # Arrange num_boids = 50 x_limits = -450, 50 y_limits = 300, 600 x_velocity_limits = 0, 10 y_velocity_limits = -20, 20 # Act parameters = BoidsSetupParameters.get_defaults() # Assert assert par...
5,318,776
def test_lfc_basic(): """Test LFC calculation.""" levels = np.array([959., 779.2, 751.3, 724.3, 700., 269.]) * units.mbar temperatures = np.array([22.2, 14.6, 12., 9.4, 7., -49.]) * units.celsius dewpoints = np.array([19., -11.2, -10.8, -10.4, -10., -53.2]) * units.celsius l = lfc(levels, temperatur...
5,318,777
def LookupScope(scope): """Helper to produce a more readable scope line. Args: scope: String url that reflects the authorized scope of access. Returns: Line of text with more readable explanation of the scope with the scope. """ readable_scope = _SCOPE_MAP.get(scope.rstrip('/')) if readable_scope:...
5,318,778
def label2binary(y, label): """ Map label val to +1 and the other labels to -1. Paramters: ---------- y : `numpy.ndarray` (nData,) The labels of two classes. val : `int` The label to map to +1. Returns: -------- y : `numpy.ndarray` (nData,) Maps ...
5,318,779
def detect_corners(R: np.array, threshold: float = 0.1) -> Tuple[np.array, np.array]: """Computes key-points from a Harris response image. Key points are all points where the harris response is significant and greater than its neighbors. Args: R: A float image with the harris response thre...
5,318,780
def cli_filter_bcs(min_bc_size, end, fastq_in, fastq_out): """Filter barcoded reads.""" for read_cloud in iterReadCloud(fastq_in): if min_bc_size and (not read_cloud.barcode or len(read_cloud) < min_bc_size): continue for read_pair in read_cloud: if end == 1: ...
5,318,781
def allocate_transects(mmt, transect_type='Q', checked=False): """Method to load transect data. Changed from Matlab approach by Greg to allow possibility of multi-thread approach. Parameters ---------- mmt: MMT_TRDI Object of MMT_TRDI transect_type: str Type of transect (Q: disc...
5,318,782
def add_file_replica_records( files: Union[Iterable[File], QuerySet], compute_resource: Union[str, ComputeResource], set_as_default=False, ) -> int: """ Adds a new laxy+sftp:// file location to every files in a job, given a ComputeResource. If set_as_default=True, the new replica location become...
5,318,783
def generate_config(imgs_dir: str, cursor_sizes: List[Num], hotspots: any) -> str: """ Generate helpers files. hotspots is JSON data for each cursor having xhot & yhot parameters.Provide `None` value set hotspots to middle of cursor. """ helpers.generate_static_cursor( imgs_dir, siz...
5,318,784
def index_returns_directory(): """ Prior to compiling a master, it is useful to get the order of projects by their file name, as the compile.run() function traverses the directory top to bottom to build the master. We can then use this to compare with the order or projects (columns) in the old maste...
5,318,785
def example_rem_id() -> Generator[str, None, None]: """Generate a Rem, yield its Id for use in other tests, and delete it.""" rem_id = remnote.create_rem( REM_KEY, REM_USER, text="Testing:: create [[Rem]]", is_document=True, source="http://example.com/", ) ...
5,318,786
def enrich_offense_timestamps_and_closing_reason( client: QRadarClient, offense, type_dict=None, closing_reason_dict=None, ): """ Convert epoch to iso and closing_reason_id to closing reason name """ enrich_offense_times(offense) if "offense_type" in offense: offense["offense_type"] = cl...
5,318,787
def in_suit3(list, list0): """ test 2 suits of street numbers if they have crossed numbers For example: "22-27" in "21-24"retruns True :param a: Int of number :param b: String List of number :return: boolean """ text = list.replace("-", "") text0 = list0.replace("-", "") if (...
5,318,788
def test_transact_opcode_oog(deploy_client: JSONRPCClient) -> None: """ The receipt status field of a transaction that did NOT throw is 0x0. """ contract_proxy, _ = deploy_rpc_test_contract(deploy_client, "RpcTest") address = contract_proxy.address assert len(deploy_client.web3.eth.getCode(address)) > ...
5,318,789
def mp_wfs_110_nometadata(monkeypatch): """Monkeypatch the call to the remote GetCapabilities request of WFS version 1.1.0, not containing MetadataURLs. Parameters ---------- monkeypatch : pytest.fixture PyTest monkeypatch fixture. """ def read(*args, **kwargs): with open('...
5,318,790
def extract_power(eeg, D=3, dt=0.2, start=0): """ extract power vaules for image Parameters ---------- seizure : EEG | dict eeg data D : int, optional epoch duration, by default 3 dt : float, optional time step (seconds), by default 0.2 start : int, optional ...
5,318,791
def extract_HOG(generator, category='species', image_size=256, train=True, verbose=True): """ Extract HOG features for specified dataset (train/test). Args: generator (Generator class object): Generator class object. train (bool): Am I working with train or test data? verbose (bool)...
5,318,792
def plot_regression_results(ax, y_true, y_pred, title, scores, elapsed_time): """Scatter plot of the predicted vs true targets.""" ax.plot( [y_true.min(), y_true.max()], [y_true.min(), y_true.max()], "--r", linewidth=2 ) ax.scatter(y_true, y_pred, alpha=0.2) ax.spines["top"].set_visible(Fal...
5,318,793
def print_banner(package: typing.Optional[str], allow_color: bool, force_color: bool) -> None: """Print a banner of choice to `sys.stdout`. Inspired by Spring Boot, we display an ASCII logo on startup. This is styled to grab the user's attention, and contains info such as the library version, the Pytho...
5,318,794
def maybe_convert_platform(values): """ try to do platform conversion, allow ndarray or list here """ if isinstance(values, (list, tuple, range)): values = construct_1d_object_array_from_listlike(values) if getattr(values, "dtype", None) == np.object_: if hasattr(values, "_values"): ...
5,318,795
def lazy_overwrite (old, new): """Overwrite old with new if different, or nonexistant. Remove the write permission on the result to avoid accidental edition of generated files.""" verbose = os.getenv(key='BUILDFARM') is None if not os.path.isfile (old): shutil.move (new, old) if verbose: print "...
5,318,796
def build_training_response(mongodb_result, hug_timer, remaining_count): """ For reducing the duplicate lines in the 'get_single_training_movie' function. """ return {'movie_result': list(mongodb_result)[0], 'remaining': remaining_count, 'success': True, 'valid_key': True, 'took': float(hug_timer)}
5,318,797
def calc_fm_perp_for_fm_loc(k_loc_i, fm_loc): """Calculate perpendicular component of fm to scattering vector.""" k_1, k_2, k_3 = k_loc_i[0], k_loc_i[1], k_loc_i[2] mag_1, mag_2, mag_3 = fm_loc[0], fm_loc[1], fm_loc[2] mag_p_1 = (k_3*mag_1 - k_1*mag_3)*k_3 - (k_1*mag_2 - k_2*mag_1)*k_2 mag_p_2 = (k_...
5,318,798
def generate( song_name, raw_data_name, base_path=utils.BASE_PATH, chunk_size=100, context_size=7, drop_diffs=[], log=False): """ Generate an SMDataset from SM/wav files. Only creates datasets with no step predictions. """ sm = SMData.SMFile(s...
5,318,799