content
stringlengths
22
815k
id
int64
0
4.91M
def get_path(dir_path: Path, dir_name: str = "movie", counting_format: str = "%03d", file_pattern: str = "") -> Tuple[Path, int, str, str]: """ Looks up all directories with matching dir_name and counting format in dir_path. Gets the highest number and returns a pa...
5,297,500
def _update_yaml_write_lines( lines: typing.List[str], configs: typing.Dict[str, typing.Any], block: YamlBlock, parent: YamlBlock, ) -> typing.List[str]: """ Replace the specified block within the YAML file lines object with the new configs. This is done by dumping that configs body and rep...
5,297,501
def get_manufacturerid() -> str: """ Get manufacturer id from MANUFACTURER_ID list :return: id """ return MANUFACTURER_ID["manufacturer_" + str(random.randint(0, N_MANUFACTURERS - 1))]
5,297,502
def _get_args_for_wrapping(wrapped, new_sig, func_name, doc, qualname, module_name, attrs): """ Internal method used by @wraps and create_wrapper :param wrapped: :param new_sig: :param func_name: :param doc: :param qualname: :param module_name: :param attrs: :return: """ ...
5,297,503
def generate_next_step(flat_model, model_curr_conf): """ Generate next conf to try """ todo_quants = [deepcopy(model_curr_conf) for _ in range(len(flat_model))] for index, conf in enumerate(todo_quants): conf[index] -=1 todo_quants = list(filter( lambda x: not 1 in x ,todo_quan...
5,297,504
def build_train_op(loss): """Sets up the training Ops. Args: loss: Loss tensor, from build_loss(). Returns: train_op, global_step, learning_rate. """ global_step = tf.Variable(0, name='global_step', trainable=False) learning_rate = tf.train.exponential_decay(INIT_LEARNING_RATE, glo...
5,297,505
def get_local_apps(category=CATEGORY_ALL): """Returns a list of apps that can be found in the apps folder""" apps = [App(folder_name) for folder_name in os.listdir("apps") if filesystem.is_dir("apps/" + folder_name)] return [app for app in apps if app.matches_category(category)]
5,297,506
def getRandom(): """ Download a random PDB and return the path name. Returns path name of downloaded file """ import os, random URL = "ftp://ftp.rcsb.org/pub/pdb/data/structures/all/pdb/" pdblines = os.popen("ncftpls %s" % URL).readlines() pdbline = pdblines.join() pdblin...
5,297,507
def logistic_sigmoid(x, a): """Computes so-called logistic curve, a sigmoidal function used in modelling population growth etc. In this implementation, the parameter a regulates the slope or 'growth rate' of the sigmoid's rising portion. When a=0, the function collapses to the identity function y=x. ...
5,297,508
async def on_ready(): """ Load state and update information since last run """ await load_state() await gompei.change_presence(activity=discord.Game(name="Underwater Hockey")) await update_guilds(gompei) print("Logged on as {0}".format(gompei.user))
5,297,509
def passes_blastn_filter(pair): """Returns bool: primer pair predicted to mis-amplify in genome.""" #TODO pass
5,297,510
def first_deriv_partials(dts, q, n_segments=1, n_simpson_intervals_per_segment=2, order=4): """ This method provides the Jacobian of a temporal first derivative A "segment" is defined as a portion of the quantity vector q with a constant delta t (or delta x, etc). This routine is designed to be use...
5,297,511
def test_boundary(shed): """check a few random properties of the returned geojson dict""" result = shed.boundary geojson_out = geojson.loads(json.dumps(result)) assert geojson_out.is_valid
5,297,512
def processed_file_path(source_path, asset_roots, target_directory, target_extension): """Take the path to an asset and convert it to target path. Args: source_path: Path to the source file. asset_roots: List of potential root directories each input file. target_directory: Path ...
5,297,513
def zoom(scale, center, group): """zoom(scale, center, group) -> float Change the zoom and pan of a group's display. The scale argument is the new zoom factor. If the scale is given, but not the center, the zoom is set to that factor and the view is positioned so the cursor is pointing at the same place it was bef...
5,297,514
def _border_type(player, tile, adj_tile): """ Used by map drawing routine. Checks if 'adj_tile' is connected to and can be seen from 'tile' :param text_game_maker.player.player.Player player: player object :param text_game_maker.tile.tile.Tile tile: first tile :param text_game_maker.tile.tile.T...
5,297,515
def parse_args(): """ Load command line args """ parser = argparse.ArgumentParser() parser.add_argument('--inf', metavar="<file>", help=('Credible set json'), type=str, required=True) parser.add_argument('--outf', metavar="<str>", help=("Output"), type=str, required=True) args = parser.parse_args() ...
5,297,516
def mobile_validator(value): """电话号验证""" if not re.match(r'1[3-9]\d{9}', value): raise serializers.ValidationError("手机号格式不正确")
5,297,517
def openFRED(context): """ The openFRED command line toolbox. Contains useful commands to work with openFRED related/supplied data. """ context.obj = {}
5,297,518
def _log_calculate(beta): # pragma: no cover """ TODO: Replace this with more efficient algorithm alpha in GF(p^m) and generates field beta in GF(p^m) gamma = log_primitive_element(beta), such that: alpha^gamma = beta """ # Naive algorithm result = 1 for i in range(0, ORDER - 1): ...
5,297,519
def partion(arr, start, end): """ 将元素以基准元素进行分区,基准元素左边都小于等于它,右边都大于等于他 :param arr: :param start: :param end: :return: """ key = arr[start] while start < end: while start < end and arr[end] >= key: end -= 1 swap(arr, start, end) while start < end ...
5,297,520
def main(): """Make a jazz noise here""" args = get_args() if args.outdir: if not os.path.isdir(args.outdir): os.mkdir(args.outdir) elif not args.silent: cont = input(f'Warning: The directory "{args.outdir}"' + ' already exists!' + ...
5,297,521
def map_fbs_flows(fbs, from_fba_source, v, **kwargs): """ Identifies the mapping file and applies mapping to fbs flows :param fbs: flow-by-sector dataframe :param from_fba_source: str Source name of fba list to look for mappings :param v: dictionary, The datasource parameters :param kwargs: incl...
5,297,522
def test_onehotencode_with_dummy_na(): """Basic binning test.""" df = _one_categ_df_with_nan() onehotencode = OneHotEncode("Born", dummy_na=True) res_df = onehotencode(df) assert "Born" not in res_df.columns assert "Born_nan" not in res_df.columns assert "Born_UK" in res_df.columns asser...
5,297,523
def _parse_collection_dir(directory: Path) -> list: """ Parse Ansible collection :param directory: Collection directory :return: List of parsed Ansible tasks that are prepared for scanning """ parsed_collection = [] for role in (list((directory / "roles").rglob("*"))): if role.is_dir...
5,297,524
def adda_hyperparams(lr_target=1e-5, lr_discriminator=1e-4, wd=5e-5, scheduler=False): """ Return a dictionary of hyperparameters for the ADDA algorithm. Default parameters are the best ones as found through a hyperparameter search. Arguments: ---------- lr_target: float Learning rate f...
5,297,525
def validate_file_path(path_variable): """Validates file path""" if os.path.isfile(path_variable) is False: exit_program("cannot find file '" + eval(path_variable) + "'" "\nplease specify a valid file path (including file " "extension) in variable '" + path_vari...
5,297,526
def test_request_closed(flask_app, app, db, dirbs_core): # pylint: disable=unused-argument """ unittest for de-registration request""" headers = {'Content-Type': 'multipart/form-data'} request_data = copy.deepcopy(REQUEST_DATA) request_data['file'] = 'dummy-file.txt' request = create_dummy_request(...
5,297,527
def get_system_library_path(): """return the path to the system Photos library as string""" """ only works on MacOS 10.15 """ """ on earlier versions, returns None """ _, major, _ = _get_os_version() if int(major) < 15: logging.debug( f"get_system_library_path not implemented for...
5,297,528
def testServerAPIAddCreator(serverURL): """ Create a creator and listen for a 200 response Note the UUID """ method = moduleName + '.' + 'testServerAPIAddCreator' Graph.logQ.put( [logType , logLevel.DEBUG , method , "entering"]) testResult = True serverStartupStatus...
5,297,529
def calicoupgrade(command, prompt_resp='yes'): """ Convenience function for abstracting away calling the calicoctl-upgrade command. :param command: The calicoctl-upgrade command line parms as a single string. :return: The output from the command with leading and trailing whitespace removed. ...
5,297,530
def get_topic_terms(model, topicid, topn, id2token): """ Return a list of `(word_id, probability)` 2-tuples for the most probable words in topic `topicid`. Only return 2-tuples for the topn most probable words (ignore the rest). """ topic = model.state.get_lambda()[topicid] topic = topic / t...
5,297,531
def gmv(cov): """ Returns the weights of the Global Minimum Vol portfolio given covariace matrix """ n = cov.shape[0] return msr(0, np.repeat(1, n), cov)
5,297,532
def placement_rest_api(): """Perform placement optimization after validating the request and fetching policies Make a call to the call-back URL with the output of the placement request. Note: Call to Conductor for placement optimization may have redirects, so account for them """ request_json = requ...
5,297,533
def ecef_to_teme(ecef: np.array, jd: float, t_tt: float, lod: float, xp: float, yp: float, eqeterms: int): """ Earth-Centered, Earth-Fixed (ECEF) to True Equator, Mean Equinox frame coordinate system conversion. TEME frame is used for the NORAD two-line elements. TODO: Vectorize Args: ecef (n...
5,297,534
def account(): """Account and update account route """ form = UpdateAccountForm() if form.validate_on_submit(): # if form.picture.data: # picture_file = save_picture(form.picture.data) # current_user.image_file = form.picture.data current_user.image_file = form.pictur...
5,297,535
def validate_udf_return_statement(func): """Validates two things concerning the return statement of a udf. 1) that there is one and 2) that it is of the simple `return name` form, as no expressions are allowd in udf return statements.""" tree = parse_func(func) statements = get_func_body_from_ast(tr...
5,297,536
def is_masked(x: List[int]): """ usage.scipy: 4 """ ...
5,297,537
def keep_corelated_data(data: DataFrameOrArrayGeneric, threshold: float = 0.5) -> DataFrameOrArrayGeneric: """Remove columns that are not corelated enough to predicted columns. Predicted column is supposed to be 0. Args: data (DataFrameOrArrayGeneric): Time series data. threshold (float, o...
5,297,538
def _run(prediction_file_name, top_example_dir_name, diff_colour_map_name, num_examples, allow_whitespace, plot_panel_names, add_titles, label_colour_bars, colour_bar_length, top_output_dir_name): """Plots one or more radar images and their upconvnet reconstructions. This is effectively the m...
5,297,539
def delete_user(UserName=None): """ Deletes the specified IAM user. The user must not belong to any groups or have any access keys, signing certificates, or attached policies. See also: AWS API Documentation Examples The following command removes the IAM user named Bob from the current account....
5,297,540
def max_pool_forward_naive(x, pool_param): """ A naive implementation of the forward pass for a max pooling layer. Inputs: - x: Input data, of shape (N, C, H, W) - pool_param: dictionary with the following keys: - 'pool_height': The height of each pooling region - 'pool_width': The width of each pool...
5,297,541
def _find_gd_env_buf(gd_address: int, gd_mem: bytes, new_gd_offset: int, arch): """ Search for `struct global_data.env_buf` in `gd_mem`. If found, the offset of this field into `gd_mem` is returned. Otherwise a `ValueError` is raised. """ search_offset = new_gd_offset + arch.word_size searc...
5,297,542
def test_get_log_list(c): """ get log list """ log = { "type":2, "domains":["test-sdk.sys-qa.com"], "startTime":"2019-03-04T00:00:00Z", "endTime":"2019-03-04T23:00:00Z", "pageNo":1, "pageSize":1000 } response = c.get_log_list(log) ...
5,297,543
def export_vote(vote, utilisation): """Enregistre un vote/les actions résolues dans le GSheet ad hoc. Écrit dans le GSheet ``LGREZ_DATA_SHEET_ID``. Peut être écrasé pour une autre implémentation. Args: vote (.bdd.Vote): le vote concerné, ou ``None`` pour une action. utilisation...
5,297,544
def migrate_notes(source, target): """Migrations notes from source connector to target connector""" notes = source.find_notes([]) count = 1 for timestamp, note in notes: print( "%s/%s - [%s] %s" % (count, len(notes), timestamp_to_datestring(times...
5,297,545
def give_recom_result(user_vec, item_vec, userid): """ user lfm model result give fix userid recom result :param user_vec: lfm model result :param item_vec: lfm model result :param userid: user :return: list :[(itemid,score),(itemid1,score1)] """ fix_num = 80 if userid not in user_...
5,297,546
def save_file(fileName): """Saves a file of a given name, and returns the json response.""" return requests.post(BASEURL+"documents",headers=HEADS,files={'requester.py': open('requester.py', 'rb')})
5,297,547
def load_label(label_path): """ Loads a label from a JSON file """ with open(label_path, 'r') as label_file: label = json.load(label_file) return label
5,297,548
def get2d23d(depth, camera_pose, K, pt1, pt2, znear, zfar, width=480, height=640): """ input: depth: image depth(in coordinate) camera_pose: orign camera_pose K: camera intrinsic pt1: orign 2d Point pt2: matchinfg 2d point znear,zfar: depth clip range retur...
5,297,549
def clip_image(image,roi=[],rotangle=0.0,cp=False): """ Clip an image given the roi Parameters: ----------- * roi is a list [c1,r1,c2,r2] = [x1,y1,x2,y2] Note take x as the horizontal image axis index (col index), and y as vertical axis index (row index). Therefore, in i...
5,297,550
def test_unregister_task_decl1(collector, task_decl): """Test unregistering a task. """ task_decl.register(collector, {}) task_decl.unregister(collector) assert not collector.contributions
5,297,551
def get_backend_name_by_class(backend) -> Optional[str]: """Gets the common name of a backend (e.g. "http" or "mqtt") given its class. """ from platypush.backend import Backend if isinstance(backend, Backend): backend = backend.__class__ class_name = backend.__name__ class_tokens = [ ...
5,297,552
def usage(): """usage A function that prints to the CLI a usgae statement for the script. """ print("fetch_dependencies.py working_dir package")
5,297,553
def run_one_epoch( epoch, loader, model, criterion, optimizer, meters, phase='train', ema=None, scheduler=None, eta=None, epoch_dict=None, single_sample=False): """run one epoch for train/val/test/cal""" t_start = time.time() assert phase in ['train', 'val', 'test', 'cal'], "phase not be in train/va...
5,297,554
def query_yes_no(question, default='yes'): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer ...
5,297,555
def load_signature_library(filename): """ Load a signature library from a .sig file. :param filename: input filename :return: instance of `TrieNode`, the root of the signature trie. """ with open(filename, 'rb') as f: buf = f.read() return SignatureLibraryReader().deserialize(buf)
5,297,556
def exo_1B0(): """Première solution avec re. Même topo.""" count = 0 for word in words: if re.search("([A-ZÂÄÀÉÈÊËÙÇa-zâäàéèêëùç].*\d|\d.*[A-ZÂÄÀÉÈÊËÙÇa-zâäàéèêëùç])", word): count += 1 print(f"Avec re. Nombre de mots qui ont au moins un chiffre et une lettre : {count}")
5,297,557
def insert_single_data(single): """ 插入文章数据 """ # 1 建立数据库连接 connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='mapei123', db='awesome', ...
5,297,558
def create_random_datetime(start, end): """ This function will return a random datetime between two datetime objects. Borrowed from: http://bit.ly/gM45o4 """ delta = end - start int_delta = (delta.days * 24 * 60 * 60) + delta.seconds random_second = randrange(int_delta) return (sta...
5,297,559
def get_task_config(task_name, is_remote): """Return powercycle task config.""" if is_remote: config_location = powercycle.abs_path( f"{powercycle_constants.REMOTE_DIR}/{POWERCYCLE_TASKS_CONFIG}") else: config_location = powercycle.abs_path(POWERCYCLE_TASKS_CONFIG) with ope...
5,297,560
def reset_health_meter(health_meter): """Reset the values of health_meter dict to the original ones""" health_meter['player'] = 40 health_meter['enemy'] = 30
5,297,561
def construct_data_reader(run_args): """ Construct Protobuf message for Python data reader. The Python data reader will import this Python file to access the sample access functions. """ module_file = os.path.abspath(run_args.data_module_file) os.environ["DATA_CONFIG"] = os.path.abspath(r...
5,297,562
def resize(anns, size, output_size): """ Parameters ---------- anns : List[Dict] Sequences of annotation of objects, containing `bbox` of [l, t, w, h]. size : Sequence[int] Size of the original image. output_size : Union[Number, Sequence[int]] Desired output size. If size...
5,297,563
def get_league_entries_by_summoner(summoner_ids): """ https://developer.riotgames.com/api/methods#!/985/3356 Args: summoner_ids (int | list<int>): the summoner ID(s) to get league entries for Returns: dict<str, list<League>>: the summoner(s)' league entries """ # Can only have ...
5,297,564
def link(link_pathname,target_pathname): """Create a link pointing to target_pathname at the given link_pathname. Target_pathname must be relative to link_pathname""" os.symlink(target_pathname,link_pathname)
5,297,565
def draw(): """ simple plotting routine """ plt.clf() plt.subplot(121, title=r'$Q_1$', xlabel=r'$t\;[day]$') plt.plot(np.array(T)/day, plot_dict_HF[0], 'o', label=r'Reference') plt.plot(np.array(T)/day, plot_dict_LF[0], label='Reduced') plt.legend(loc=0) plt.subplot(122, ...
5,297,566
def scheduler() -> BackgroundScheduler: """Retrieve the scheduler, intended mostly for unit testing purposes.""" if not _SCHEDULER: raise EngineError("Scheduler is not available") return _SCHEDULER
5,297,567
def test_time_sub_range(): """Unit test on AidaAccessorVDF.time_sub_range method.""" time_delta = timedelta(minutes=20) time_par = np.arange(datetime(2019, 1, 1), datetime(2019, 1, 2), time_delta).astype(datetime) start_time_sub = datetime(2019, 1, 1, 10) end_time_sub = date...
5,297,568
def toDiscrete(m): """ Args: - m (m,n) : np.array with the occupancy grid Returns: - discrete_m : thresholded m """ y_size, x_size = m.shape m_occupied = np.zeros(m.shape) m_free = np.zeros(m.shape) m_occluded = np.zeros(m.shape) #Handpicked occupied_value = 0.8...
5,297,569
def normalise_ward_penalties(hospital: Hospital) -> Hospital: """ Normalises the ward penaltied by the maximum possible penalty for the hospital. """ max_penalty = 0 for ward in hospital.wards: for restriction in ward.restrictions: max_penalty += sum(restriction.penalty for _...
5,297,570
def has_overlap(x0, xd, y0, yd): """Return True if the ranges overlap. Parameters ---------- x0, y0 : float The min values of the ranges xd, yd : float The widths of the ranges """ return x0 + xd >= y0 and y0 + yd >= x0
5,297,571
def _ecdf_vals(data, formal=False): """ Get x, y, values of an ECDF for plotting. Parameters ---------- data : ndarray One dimensional Numpay array with data. formal : bool, default False If True, generate x and y values for formal ECDF (staircase). If False, generate x ...
5,297,572
def test_get_item(items, sub, name, expected_item_index): """ GIVEN items in the database and sub and spec name WHEN get_item is called on Spec with the sub and spec name THEN the expected item is returned. """ for item in items: item.save() returned_item = models.Spec.get_item(sub=...
5,297,573
def add_classification(hw_data, index): """ Add a column at the end of the data to capture wind severity. 0 if wind speed is < 50 1 if wind speed is >= 50 """ sev_wind = hw_data[:, index] >= 50 sev_wind = sev_wind.astype(int) sev_wind = sev_wind.reshape(len(sev_wind), 1) hw_...
5,297,574
def check_airflow_versions_in_quick_start_guide() -> List[DocBuildError]: """Check that a airflow version is presented in example in the quick start guide for Docker.""" build_errors = [] build_error = assert_file_contains( file_path=f"{DOCS_DIR}/apache-airflow/start/docker.rst", pattern=re...
5,297,575
def test_common_publish_topics(mocker): """Test that `common_publish_topics` calls `_get_items_by_role` correctly.""" get_items_mock = mocker.patch( 'nodl_to_policy.common.profile._get_items_by_role', autospec=True) common_profile.common_publish_topics() assert get_items_mock.call_count ...
5,297,576
def make_pbtype_xml(file_name, ports, pb_name="PS7", blif_model="VPR_PS7"): """ Generates a leaf pb_type XML for the PS7 cell given its input ports definitions. """ pb_xml = """<pb_type name="{}" blif_model=".subckt {}" num_pb="1"> """.format(pb_name, blif_model) for name in sorted(ports.keys(...
5,297,577
def write_plugins_snapshot(manager: BuildManager) -> None: """Write snapshot of versions and hashes of currently active plugins.""" if not manager.metastore.write(PLUGIN_SNAPSHOT_FILE, json.dumps(manager.plugins_snapshot)): manager.errors.set_file(_cache_dir_prefix(manager), None) manager.errors...
5,297,578
def load(filename): """ Load nifti1 single or pair from `filename` Parameters ---------- filename : str filename of image to be loaded Returns ------- img : Nifti1Image or Nifti1Pair nifti1 single or pair image instance Raises ------ ImageFileError: if `filenam...
5,297,579
def test_input_spec_func_1b_except(use_validator): """ the function w/o annotated, but input_spec is used metadata checks raise an error """ @mark.task def testfunc(a): return a my_input_spec = SpecInfo( name="Input", fields=[ ( "a", ...
5,297,580
def corr1(xydata): """corr1(xydata) -> float Calculate an estimate of the Pearson's correlation coefficient with a single pass over iterable xydata. See also the function corr which may be more accurate but requires multiple passes over the data. >>> data = zip([0, 5, 4, 9, 8, 4], [1, 2, 4, 8, 6, ...
5,297,581
def test_mp3gen_with_non_empty_music_listing(): """test func.""" music_item = mock.Mock() with mock.patch('melissa.actions.play_music.sys') \ as m_sys, \ mock.patch('sys.stdout', new_callable=StringIO) \ as m_stdout, \ mock.patch('melissa.actions.play_music.os...
5,297,582
def train(model): """Train the model.""" # Training dataset. dataset_train = TissueDataset() dataset_train.load_tissue(args.dataset, "train") dataset_train.prepare() # Validation dataset dataset_val = TissueDataset() dataset_val.load_tissue(args.dataset, "valid") dataset_val.prepare...
5,297,583
def create_cluster(cluster_name): """ Create OCP cluster. Args: cluster_name (str): Cluster name. """ configs = config.ENV_DATA["configs"] cmd = ( f"podman run -e ADDON_IDS -e NUM_WORKER_NODES -e OCM_COMPUTE_MACHINE_TYPE" f" -e OCM_TOKEN -e CLUSTER_NAME -e CLUSTER_EXPIR...
5,297,584
def vehicle_capacity_is_respected(solution: Solution) -> Tuple[bool, str]: """ Verifies the vehicle capacities are respected by each tour of the solution. """ problem = Problem() for route in solution.routes: if any(stacks.used_capacity() > problem.capacity for stacks in rout...
5,297,585
def find_doctests(suffix, ignore_suffix=None): """Find doctests matching a certain suffix.""" doctest_files = [] # Match doctests against the suffix. if resource_exists('lazr.restfulclient', 'docs'): for name in resource_listdir('lazr.restfulclient', 'docs'): if ignore_suffix is not ...
5,297,586
def test_basic_export_get_records(et_code, rset_code, filter_code, basic_exporter_class, record_sets, new_exporter): """ For Basic Exporter classes that get data from Sierra, the `get_records` method should return the expected recordset. ...
5,297,587
def get_pwn_cutoff(ra,dec,rad_search=2., deathline = 1.e34): """ Set cutoff for PWN based on association with pulsars in ATNF catalog Only pulsars with Edot > 1.e34 erg/s are considered, because cutoffs at ~1 TeV should have already been detected :param ra: R.A. of PWN center, deg :param dec: De...
5,297,588
def _any(series, values): """ Returns the index of rows from series containing any of the given values. Parameters ---------- series : pandas.Series The data to be queried values : list-like The values to be tested Returns ------- index : pandas.index The i...
5,297,589
def test_compute_z(D_hat): """Test for valid values.""" with get_z_encoder_for(X=X, D_hat=D_hat, n_atoms=N_ATOMS, atom_support=N_TIMES_ATOM, n_jobs=2) as z_encoder: z_encoder.compute_z() ...
5,297,590
def parse_hhcc(self, data: str, source_mac: str, rssi: float): """HHCC parser""" if len(data) == 13: device_type = "HHCCJCY10" hhcc_mac = source_mac xvalue_1 = data[4:7] xvalue_2 = data[7:10] xvalue_3 = data[10:13] packet_id = data[4:13].hex() (moist, temp...
5,297,591
def test_chunk(): """ Does chunk() divide a string into chunks of the correct size without modifying it? """ string = "This must be Thursday. I never could get the hang of Thursdays." result = [] for chunk in encode.chunk(string, 4): assert len(chunk) <= 4 result.append(chunk...
5,297,592
def CIFAR10(train=True, path=None): """Thin wrapper around torchvision.datasets.CIFAR10 """ mean, std = [0.491, 0.482, 0.447], [0.247, 0.243, 0.262] normalize = transforms.Normalize(mean=mean, std=std) if train: preproc = [transforms.RandomHorizontalFlip(), transforms.RandomCrop(32, 4)] ...
5,297,593
def print_board(bd, rdl, bdl): """ |----|----|----|----|----|----|----|----| | 棋 | 棋 | 棋 | 棋 | 棋 | 棋 | 棋 | 棋 | |----|----|----|----|----|----|----|----| | 棋 | 棋 | 棋 | 棋 | 棋 | 棋 | 棋 | 棋 | |----|----|----|----|----|----|----|----| | 棋 | 棋 | 棋 | 棋 | 棋 | 棋 | 棋 | 棋 | |----|----|----|----|----...
5,297,594
def proxy(): """ 代理 :return: """ while True: url = 'https://www.sojson.com/ip/' ip_list = ['101.236.23.202:8866', '118.190.95.43:9001', '125.120.202.201:808'] proxy_support = urllib.request.ProxyHandler({'http': random.choice(ip_list)}) opener = urllib.reques...
5,297,595
def scrub(): """Perform cleaning of data file""" pass
5,297,596
def get_app_base_url(): """ Returns the QRadar app proxy prefix. """ return app_qpylib.get_app_base_url()
5,297,597
def create_plotgroup(template_plot_type='bitmap',**params): """ Create a new PlotGroup and add it to the plotgroups list. Convenience function to make it simpler to use the name of the PlotGroup as the key in the plotgroups list. template_plot_type: Whether the plots are bitmap images or curves ...
5,297,598
def create_file_map(directory_dict): """ Create a dictionary that maps the hash value of each unique file to a list of the full paths of each copy of that file, even if those files have different names. :param directory_dict: dictionary mapping directory -> list of files :return: dictionary map...
5,297,599