content
stringlengths
22
815k
id
int64
0
4.91M
def _b64urldec(input: str) -> bytes: """ Deocde data from base64 urlsafe with stripped padding (as specified in the JWS RFC7515). """ # The input is stripped of padding '='. These are redundant when decoding (only relevant # for concatenated sequences of base64 encoded data) but the decoder checks f...
5,340,700
def get_sns_topic_arn(aws_creds, ec2_region): """ Retrieves the sns topic arn for the account """ rgt_client = ResourceGroupsTaggingClient(aws_creds, ec2_region, logger) sns_topic_arn = rgt_client.get_sns_topic_arn(SNS_TOPIC_TAG_KEY, SNS_TOPIC_TAG_VALUE) if not sns_topic_arn: raise SnsTo...
5,340,701
def worker_task(instance_no, total_instances, bin_data_source_blob, logger=None): """ get the task for the worker arguments contains the various parameters that will be used by the machines to process the data like file numbers instance_no belongs to [0, total_instances - 1] """ if logger: ...
5,340,702
def get_universe_regions_region_id(*, language, region_id, accept_language='en-us', if_none_match=None): """ :param accept_language: ['de', 'en-us', 'fr', 'ja', 'ru', 'zh']...
5,340,703
def p_cmdexpr_uniq(p): """cmdexpr : UNIQ"""
5,340,704
def create_bspline_basis(knots, spline_order, dt=0.02): """Create B-spline basis.""" # The repeated boundary knots are appended as it is required for Cox de Boor # recursive algorithm. See https://math.stackexchange.com/questions/2817170/ # what-is-the-purpose-of-having-repeated-knots-in-a-b-spline and the link...
5,340,705
def execute( device, commands, creds=None, incremental=None, with_errors=False, timeout=settings.DEFAULT_TIMEOUT, command_interval=0, force_cli=False ): """ Connect to a ``device`` and sequentially execute all the commands in the iterab...
5,340,706
def _attempt_get_hash_function(hash_name, hashlib_used=hashlib, sys_used=sys): """Wrapper used to try to initialize a hash function given. If successful, returns the name of the hash function back to the user. Otherwise returns None. """ try: _fetch_hash = getattr(hashlib_used, hash_name, ...
5,340,707
def get_proxy(usage: str): """ 通过WEB API接口获取代理 :param usage: 目标站点,对应WEB_AVAILABLE_PROXIES的key :return: 可用代理或None """ url = API_SERVER + "/proxy?usage={}".format(usage) res = requests.get(url, timeout=5) try: if res.status_code == 200: return res.json().get("resource"...
5,340,708
def test_esnli_preprocessor(): """tests esnli preprocessor""" raw_data = {} for field in dataclasses.fields(RawESNLIExample): key = field.name raw_data[key] = [getattr(example, key) for example in RAW_EXAMPLES_1] dataset = datasets.Dataset.from_dict(raw_data) dataset = ESNLIBuilder.p...
5,340,709
def _load_blocks_txt(): """Load block name from Blocks.txt.""" with open_unicode_data_file("Blocks.txt") as blocks_txt: block_ranges = _parse_code_ranges(blocks_txt.read()) for first, last, block_name in block_ranges: _block_names.append(block_name) _block_range[block_name] = (first...
5,340,710
def test_wktext(): """Test +wktext parameter is preserved.""" proj4 = ('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 ' '+x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext ' '+no_defs') assert 'wktext' in crs.from_string(proj4)
5,340,711
def column_names_get(subject: str) -> tuple: """ Returns column names. """ if subject == c.SUBJECT.PLANETS: return c.HEADERS.PLANETS elif subject == c.SUBJECT.STARSHIPS: return c.HEADERS.STARSHIPS elif subject == c.SUBJECT.VEHICLES: return c.HEADERS.VEHICLES elif subject == c...
5,340,712
def is_morepath_template_auto_reload(): """ Returns True if auto reloading should be enabled. """ auto_reload = os.environ.get("MOREPATH_TEMPLATE_AUTO_RELOAD", "") return auto_reload.lower() in {"1", "yes", "true", "on"}
5,340,713
def handle_get_actor_report(self, handle, connection, match, data, hdr): """ GET /actor/{actor-id}/report Some actor store statistics on inputs and outputs, this reports these. Not always present. Response status code: OK or NOT_FOUND Response: Depends on actor """ self._actor_report(handle,...
5,340,714
def relabel_prometheus(job_config): """Get some prometheus configuration labels.""" relabel = { 'path': '__metrics_path__', 'scheme': '__scheme__', } labels = { relabel[key]: value for key, value in job_config.items() if key in relabel.keys() } # parse _...
5,340,715
def q_geography_capital(): """Ask what the capital of a given country is.""" question = QuestionGenerator() question.set_type('geography') # select country all_countries = facts.get_geography_countries_list() country = random.choice(all_countries) # formulate question question.ask(f"Wa...
5,340,716
def binary_stabilizer_to_pauli_stabilizer(stabilizer_tableau): """ Convert a stabilizer tableau to a list of PauliTerms :param stabilizer_tableau: Stabilizer tableau to turn into pauli terms :return: a list of PauliTerms representing the tableau :rytpe: List of PauliTerms """ stabilizer_li...
5,340,717
def move_and_replace(src, dst): """ Helper function used to move files from one place to another, creating os replacing them if needed :param src: source directory :param dst: destination directory """ print('move %s to %s' % (src, dst)) src = os.path.abspath(src) dst = os.path.abs...
5,340,718
def checkGroup(self, group, colls): """ Args: group: colls: Returns: """ cut = [] for elem in group: if elem in colls: cut.append(elem) if len(cut) == len(group): return cut else: return []
5,340,719
def get_node_shapes(input_graph_def, target_nodes): """Get shapes of target nodes from input_graph_def, shapes may be partial""" node_shapes = [] for target in target_nodes: for node in input_graph_def.node: if node.name == target: if not 'shape' in node.attr: print("Warning: Fail to g...
5,340,720
def calculate_cost(A3, Y): """ 计算损失函数cost值 Args: A3: 正向传播的输出,尺寸大小为(输出尺寸, 样本数量) Y: 真实标签向量,尺寸大小和a3相同 Return: cost: 损失函数cost值 """ m = Y.shape[1] logprobs = np.multiply(-np.log(A3), Y) + np.multiply( -np.log(1 - A3), 1 - Y) cost = 1. / m * np.nansum(logprobs)...
5,340,721
def _replace_sysarg(match): """Return the substitution for the $<n> syntax, .e.g. $1 for the first command line parameter. """ return sys.argv[int(match.group(1))]
5,340,722
def qsammobilenetv2(**kwargs): """Constructs a QSAMMobileNetv2 model. """ model = QSAMMobileNetV2(**kwargs) return model
5,340,723
def get_frame_labels_fields( sample_collection, frame_labels_field=None, frame_labels_prefix=None, frame_labels_dict=None, dataset_exporter=None, required=False, force_dict=False, ): """Gets the frame label field(s) of the sample collection matching the specified arguments. Prov...
5,340,724
def _rpc_code_to_error_code(rpc_code): """Maps an RPC code to a platform error code.""" return _RPC_CODE_TO_ERROR_CODE.get(rpc_code, exceptions.UNKNOWN)
5,340,725
def peak_values(dataframe_x, dataframe_y, param): """Outputs x (potentials) and y (currents) values from data indices given by peak_detection function. Parameters ---------- DataFrame_x : pd.DataFrame should be in the form of a pandas DataFrame column. For ex...
5,340,726
def _infer_geometry(value): """Helper method that tries to infer the $geometry shape for a given value""" if isinstance(value, dict): if "$geometry" in value: return value elif 'coordinates' in value and 'type' in value: return {"$geometry": value} raise InvalidQu...
5,340,727
def random_rotation_operator_tensor (operand_space_shape:typing.Tuple[int,...]) -> np.ndarray: """NOTE: Not a uniform distribution.""" if vorpy.tensor.dimension_of_shape(operand_space_shape) == 0: raise Exception(f'invalid dimension for vector space having rotation') A = random_antisymmetric_operat...
5,340,728
def get_system_details(backends=True): """Return a dictionary with information about the system """ buildno, builddate = platform.python_build() if sys.maxunicode == 65535: # UCS2 build (standard) unitype = 'UCS2' else: # UCS4 build (most recent Linux distros) unitype...
5,340,729
def train(data_path, hidden_layer_sizes=[784, 800, 10], im_size=(28, 28), dropout_fraction=0.2, random_seed=1, epochs=25, val_fraction=0.15, model_name='digit.keras'): """ Trains feedforward neural network. Stores model. :param data_path: Path to training data. :param h...
5,340,730
def get_early_stopping(callback_config:dict): """ Get tf keras EarlyStopping callback. Args: callback_config: config info to build callback """ return keras.callbacks.EarlyStopping(**callback_config)
5,340,731
def test_daterange(): """Asser daterange generator.""" # case invalid range start = date(2021, 2, 1) end = date(2021, 1, 1) dates = [x for x in drifactorial.daterange(start, end)] assert len(dates) == 0 # case include end end = date(2021, 2, 28) dates = [x for x in drifactorial.dater...
5,340,732
def test_zernike_zero(): """Make sure same result is obtained for integer and float""" n, m = choose_random_nm() r = 0.5 theta = np.random.rand() * 2 * np.pi - np.pi assert_true( np.isfinite(zernike(r, theta, n, m)).all(), "r, theta, n, m = {}, {}, {}, {}".format(r, theta, n, m), ...
5,340,733
def decode(rdf, hint=[]): """Decode ReDIF document.""" def decode(encoding): rslt = rdf.decode(encoding) if rslt.lower().find("template-type") == -1: raise RuntimeError("Decoding Error") return rslt encodings = hint + ["windows-1252", "utf-8", "utf-16", "latin-1"] i...
5,340,734
def pad_square(x): """ Pad image to meet square dimensions """ r,c = x.shape d = (c-r)/2 pl,pr,pt,pb = 0,0,0,0 if d>0: pt,pd = int(np.floor( d)),int(np.ceil( d)) else: pl,pr = int(np.floor(-d)),int(np.ceil(-d)) return np.pad(x, ((pt,pb),(pl,pr)), 'minimum')
5,340,735
def get_env_properties( env: Union[gym.Env, VecEnv], network: Union[str, Any] = "mlp" ) -> (Tuple[int]): """ Finds important properties of environment :param env: Environment that the agent is interacting with :type env: Gym Environment :param network: Type of network architectu...
5,340,736
def gen_abc_json(abc_gt_dir, abc_json_path, image_dir): """ 根据abcnet的gt标注生成coco格式的json标注 :param abc_gt_dir: :param abc_json_path: :param image_dir: :return: """ # Desktop Latin_embed. cV2 = [' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2...
5,340,737
def mahalanobis(data, produce=None): """ Calculate mahalanobis distance on a matrix of column vectors. Assumes that rows are observations and columns are features. Parameters ---------- data : numpy array or pandas dataframe The data to calculate distances on (columns are variables...
5,340,738
def text(el): """ Helper to get the text content of a BeautifulSoup item """ return el.get_text().strip()
5,340,739
def stage(): """Run the stage group""" pass
5,340,740
def collect_DAC_pow(dig, IF_freq): """TODO: Desciption what I, the function, do""" return external_ATS9870_CS_VNA.collect_amp(dig, IF_freq)
5,340,741
def com_google_fonts_check_render_own_name(ttFont): """Check font can render its own name.""" from fontbakery.utils import can_shape menu_name = ttFont["name"].getName( NameID.FONT_FAMILY_NAME, PlatformID.WINDOWS, WindowsEncodingID.UNICODE_BMP, WindowsLanguageID.ENGLISH_USA ...
5,340,742
def psrpipe(eventfile,flags): """ Running psrpipe on the observation, to make more cuts! I decided not to put in pre-determined options for fully flexibility. Though standard flags would be ['--emin','0.3','--emax','12.0','--shrinkelvcut'], though there are others. Check out "psrpipe.py -h"! Also ma...
5,340,743
def get_sha512_manifest(zfile): """ Get MANIFEST.MF from a bar file. :param zfile: Open (!!!) ZipFile instance. :type zfile: zipfile.ZipFile """ names = zfile.namelist() manifest = None for name in names: if name.endswith("MANIFEST.MF"): manifest = name b...
5,340,744
def test__combine_lists__add(operand: List[object]) -> None: """Test that `+` operator works for result of `combine_lists()`.""" # Just make sure addition works assert (combine_lists('a', 'b') + operand) is not None assert (operand + combine_lists('a', 'b')) is not None
5,340,745
def plot_heatmap(filename, xdata, ydata, binx, biny, title = None, xlabel = None, ylabel = None, dpi = 150, figsize = (10,10), tfont = 17, lfont = 14): """ Present variables as a 2D heatmap to correlate magnitude and direction. """ def get_bin_id(mybins, vv): for ibin in range(len(mybins)-1)...
5,340,746
def infer_motifs( adata: AnnData, dataset: str, cluster: Optional[str] = "louvain", n_top_genes: Optional[int] = 1000, max_cell_types: Optional[int] = 50, pfm: Optional[str] = None, min_annotated: Optional[int] = 50, num_enhancers: Optional[int] = 10000, maelstrom: Optional[bool] = F...
5,340,747
def cmake_var_string(cmake_vars): """Converts a dictionary to an input suitable for expand_cmake_vars. Ideally we would jist stringify in the expand_cmake_vars() rule, but select() interacts badly with genrules. TODO(phawkins): replace the genrule() with native rule and delete this rule. Args: cmake_va...
5,340,748
def scattering_transform1d(n_classes, sequence_length): """ Scattering transform """ log_eps = 1e-6 x_in = layers.Input(shape=(sequence_length)) x = Scattering1D(8, 12)(x_in) x = layers.Lambda(lambda x: x[..., 1:, :])(x) x = layers.Lambda(lambda x: tf.math.log(tf.abs(x) + log_eps))(x) x = layers.GlobalAveragePo...
5,340,749
def main(): """Runs the program.""" # Parse command-line args parser = argparse.ArgumentParser(prog='preprocess_data.py', description='Preprocess Clockify API data from files in an opinionated fashion.', epilog='Have fun preprocessing! ...
5,340,750
def addFileContent(session, filepath, source_file_name, content_hash, encoding): """ Add the necessary file contents. If the file is already stored in the database then its ID returns. If content_hash in None then this function calculates the content hash. Or if is available at the ca...
5,340,751
def test_simple_push_pull(): """ Test the 'happy path' push/pull interaction 1. Push a file to remote, pull (initially) to make sure we get it 2. Modify file & push to remote, pull to make sure we get update 3. Add new file to remote, pull to make sure we get it 4. Delete new file to remote, pu...
5,340,752
def model_fn_builder(num_labels, learning_rate, num_train_steps, num_warmup_steps): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" input_ids = featur...
5,340,753
def test_cmd_run_has_list_input_save_dev_null(): """List input to run complex dict save all output to /dev/null.""" cmd1 = get_cmd('echo one', r'tests\testfiles\cmds\echo.bat one') cmd2 = get_cmd('echo two three', r'tests\testfiles\cmds\echo.bat "two three"') cont...
5,340,754
def to_numeric_df(kdf): """ Takes a dataframe and turns it into a dataframe containing a single numerical vector of doubles. This dataframe has a single field called '_1'. TODO: index is not preserved currently :param df: :return: a pair of dataframe, list of strings (the name of the columns ...
5,340,755
def FancyAnalyzer(expression=r"\s+", stoplist=STOP_WORDS, minsize=2, maxsize=None, gaps=True, splitwords=True, splitnums=True, mergewords=False, mergenums=False): """Composes a RegexTokenizer with an IntraWordFilter, LowercaseFilter, and StopFilter. >>> ana = F...
5,340,756
def find_res_shift(x_min, x_max, y_min, y_max, z_min, z_max, target_id, my_sites, res_two_three_dict, my_mols, color_list, button_list): """Function to find the relavant residue shifts""" print "FINDING MAX SHIFTS" max_shift = [] # Get the delta value delta = 5.0 # Filter residues to the ones wi...
5,340,757
def lookup(*getters): """Find data by provided parameters and group by type respectively""" getters = list(reversed(getters)) def wrap(struct): while getters: _type, getter = getters.pop() if _type == G_TYPE_KEY: struct = getter(struct) contin...
5,340,758
def test_toggle_off(basic_app): """Check if title is correctly displayed if the toggle is turned off""" basic_app.settings = {"time_in_menu_bar": False} update_title_bar(basic_app) assert basic_app.title is None
5,340,759
def compute_one(t, lhs, rhs, **kwargs): """ Join two pandas data frames on arbitrary columns The approach taken here could probably be improved. To join on two columns we force each column to be the index of the dataframe, perform the join, and then reset the index back to the left side's original...
5,340,760
def simulate(mat, det, e0=20.0, dose=defaultDose, withPoisson=True, nTraj=defaultNumTraj, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams=defaultXtraParams): """simulate(mat,det,[e0=20.0],[withPoisson=True],[nTraj=defaultNumTraj],[dose=defaultDose],[sf=defaultCharFluor],[bf=defaultBremFluor],[xtraParams=defaul...
5,340,761
def link_match_family(link, family_name): """Checks whether the a link can be used in a given family. When this function is used with built-in family names, it tests whether the link name can be used with the given built-in family. If the family name is not known, we return True because the user is wor...
5,340,762
def test_naked_domain(create_user): """Test user against naked domain pattern (e.g google.com) """ emails = ["harold@bar.com"] patterns = ["bar.com"] assert create_user.preprocess_pattern(emails, patterns) == True fail_emails = ["harold@help.bar.com"] assert create_user.preprocess_pattern(fail_e...
5,340,763
def store_abu_result_tuple(abu_result_tuple, n_folds=None, store_type=EStoreAbu.E_STORE_NORMAL, custom_name=None): """ 保存abu.run_loop_back的回测结果AbuResultTuple对象,根据n_folds,store_type参数 来定义存储的文件名称,透传参数使用ABuStore.store_abu_result_tuple执行操作 :param abu_result_tuple: AbuResultTuple对...
5,340,764
def auc(test_set, user_factors, subreddit_factors, subreddits, users): """ Returns the auc score on a test data set """ num_users = len(test_set) total = 0 # treat the signal as 1 as per the implicit bpr paper for subreddit, user, signal in tqdm.tqdm_notebook(test_set): # outer su...
5,340,765
def insert_internal_bgp_peering(peering, service_node): """ Creates/updates the relationship and nodes needed to express the internal peerings. """ pass
5,340,766
def convert_AST_to_expr(ast): """Creates expression from the AST.""" converter = ASTToInstrBlockConverter() instrs = converter.my_visit(ast) return instrs[0]
5,340,767
def then_app_running_stage(context): """Check that the app is deployed and running on stage.""" result = context.result result | should.equal('Success').desc("Application is reachable in the Stage stage.")
5,340,768
def testAgentSpecValidation_whenDefinitionIsCorrect_noRaise(): """Unit test to check the validity of the Agent json-schema. Case where the Agent definition is valid. """ valid_yaml_data = """ kind: Agent name: "agent" version : 1.1.0 description: "Agent1 Description shou...
5,340,769
def linting(session): """Launch linting locally.""" session = base_install(session) session.run("pre-commit", "run", "-a")
5,340,770
def add_data_from_api(service, repo, variable_type, keys): """Retrieves Github API data. Utilizes the function from github_api/github.py to do so. This function adds the retrieved variables directly to the data dictionary. Args: service (Service): Service object with API connection and metadata var...
5,340,771
def heads(context, directory='migrations', verbose=False, resolve_dependencies=False): """Show current available heads in the script directory""" if alembic_version >= (0, 7, 0): config = _get_config(directory) command.heads(config, verbose=verbose, resolve_dependencies=res...
5,340,772
def part1(data): """ >>> part1(read_input()) 0 """ return data
5,340,773
def get_rectanguloid_mask(y, fat=1): """Get a rectanguloid mask of the data""" M = y.nonzero().max(0)[0].tolist() m = y.nonzero().min(0)[0].tolist() M = [min(M[i] + fat, y.shape[i] - 1) for i in range(3)] m = [max(v - fat, 0) for v in m] mask = torch.zeros_like(y) mask[m[0] : M[0], m[1] : M[...
5,340,774
def create_schema(engine=None): """Create schema from models, without a migration.""" base = models.BASE if engine is None: engine = get_engine() base.metadata.create_all(engine)
5,340,775
def colorize_output(output): """Add HTML colors to the output.""" # Task status color_output = re.sub(r'(ok: [-\w\d\[\]]+)', r'<font color="green">\g<1></font>', output) color_output = re.sub(r'(changed: [-\w\d\[\]]+)', r'<font color="oran...
5,340,776
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the weenect device_trackers.""" platform = entity_platform.async_get_current_platform() coordinator = hass.data[DOMAIN][entry.entry_id] @callback def asy...
5,340,777
def parse_args(): """Parse command-line arguments""" parser = argparse.ArgumentParser( description='Stop a subjective evaluation without ' + 'destroying resources') parser.add_argument('--aws_api_key', help='The public API key for AWS') parser.add_argument( '--aws_api...
5,340,778
def parse_user_date(usr_date: str) -> date: """ Parses a user's date input, prompts the user to input useful date data if user's date was invalid Args: usr_date : str, user input of date info. Should be in <yyyy/mm/dd> format Returns: valid datetime.date() object """ expected_len = len("yyyy/mm/dd") if usr...
5,340,779
def up_sampling_block(x, n_filter, kernel_size, name, activation='relu', up_size=(2, 2)): """Xception block x => sepconv block -> sepconv block -> sepconv block-> add(Act(x)) => """ x = layers.UpSampling2D(size=up_size, name=name+'up')(x) if activation: x = layers.Activ...
5,340,780
def connected_components(graph): """ Connected components. @attention: Indentification of connected components is meaningful only for non-directed graphs. @type graph: graph @param graph: Graph. @rtype: dictionary @return: Pairing that associates each node to its connected component. ...
5,340,781
def format_keyvals( entries: typing.Iterable[typing.Tuple[str, typing.Union[None, str, urwid.Widget]]], key_format: str = "key", value_format: str = "text", indent: int = 0 ) -> typing.List[urwid.Columns]: """ Format a list of (key, value) tuples. Args: entries: The ...
5,340,782
def get_item_workdays(scorecard): """ Gets the number of days in this period""" supplier = frappe.get_doc('Supplier', scorecard.supplier) total_item_days = frappe.db.sql(""" SELECT SUM(DATEDIFF( %(end_date)s, po_item.schedule_date) * (po_item.qty)) FROM `tabPurchase Order Item` po_item, `tabPurchas...
5,340,783
def load_data(ticker='SNAP', barSizeSetting='3 mins', what='TRADES'): """ loads historical tick data """ if what == 'TRADES': folder = '/home/nate/Dropbox/data/ib_full_adj/data/' elif what == 'ADJUSTED_LAST': folder = '/home/nate/Dropbox/data/ib_split_adj_only/data/' bss = barSi...
5,340,784
def time_human(x): """ Gets time as human readable """ # Round time x = round(x, 2) for number, unit in [(60, "s"), (60, "min"), (24, "h"), (365, "days")]: if abs(x) < number: return f"{x:.2f} {unit}" x /= number return f"{x:.2f} years"
5,340,785
def transaction_json_to_binary_codec_form( dictionary: Dict[str, XRPL_VALUE_TYPE] ) -> Dict[str, XRPL_VALUE_TYPE]: """ Returns a new dictionary in which the keys have been formatted as CamelCase and standardized to be serialized by the binary codec. Args: dictionary: The dictionary to be re...
5,340,786
def test_eval_frac(): """ Test procedure for the function eval_frac """ print('Testing eval_frac') # Start with a good test result = frac.eval_frac('2/10') introcs.assert_floats_equal(0.2, result) # Now a lot of error tests # Slash in bad places result = frac.eval_frac(...
5,340,787
def conv3x3(in_planes, out_planes, stride=1, groups=1): """3x3 convolution with padding""" return nn.Conv1d(in_planes, out_planes, kernel_size=7, stride=stride, padding=3, bias=False, groups=groups)
5,340,788
def limit_sub_bbox(bbox, sub_bbox): """ >>> limit_sub_bbox((0, 1, 10, 11), (-1, -1, 9, 8)) (0, 1, 9, 8) >>> limit_sub_bbox((0, 0, 10, 10), (5, 2, 18, 18)) (5, 2, 10, 10) """ minx = max(bbox[0], sub_bbox[0]) miny = max(bbox[1], sub_bbox[1]) maxx = min(bbox[2], sub_bbox[2]) maxy = ...
5,340,789
def _load_taxa_incorp_list(inFile, config): """Loading list of taxa that incorporate isotope. Parameters ---------- inFile : str File name of taxon list config : config object Returns ------- {library:[taxon1, ...]} """ taxa = {} with open(inFile, 'rb') as inFH: ...
5,340,790
def get_subsections(config: Config) -> t.List[t.Tuple[str, t.Dict]]: """Collect parameter subsections from main configuration. If the `parameters` section contains subsections (e.g. '[parameters.1]', '[parameters.2]'), collect the subsection key-value pairs. Otherwise, return an empty dictionary (i.e. ...
5,340,791
def team_m2m_changed(sender, instance, action, reverse, model, pk_set, **kwargs): """Called when a Team's members list is changed""" teams = None users = None # If actions is pre_clear or post_clear, pk_set will be None. If # this is the case, just set pk_set to the empty list....
5,340,792
def print_as_table(data: dict, *, capitalize: bool = False): """ Prints the data of a dictionary as a simple table. """ # Get the largest key size = 0 for key in data.keys(): if len(key) > size: size = len(key) # Now, time to start printing for key, value in data.ite...
5,340,793
def calc_psi(B, rev=False): """Calc Flux function (only valid in 2d) Parameters: B (VectorField): magnetic field, should only have two spatial dimensions so we can infer the symmetry dimension rev (bool): since this integration doesn't like going through undefined region...
5,340,794
def batch(iterable, batch_size=5): """Wraps around an iterable or generator and yields results in batches. Example: gen = (letter for letter in string.ascii_uppercase) for n in batch(gen, 8): print(''.join(n)) Will produce: ABCDEFGH IJKLMNOP QRSTUVWX ...
5,340,795
def log_uncertain_unfollowed_pool(login, unfollowed, logger, logfolder): """Prints and logs the uncertain unfollowed to a seperate file""" try: with open('{0}{1}_uncertain_unfollowedPool.csv'.format(logfolder, login), 'a+') as followPool: with interruption_handler(): foll...
5,340,796
def test_ap_hs20_deauth_req_from_radius(dev, apdev): """Hotspot 2.0 connection and deauthentication request from RADIUS""" bssid = apdev[0]['bssid'] params = hs20_ap_params() params['nai_realm'] = [ "0,example.com,21[2:4]" ] params['hs20_deauth_req_timeout'] = "2" hostapd.add_ap(apdev[0]['ifname...
5,340,797
def infer_printed_type(t): """Infer the types that should be printed. The algorithm is as follows: 1. Replace all constant types with None. 2. Apply type-inference on the resulting type. 3. For the first internal type variable that appears, find a constant whose type contains that variab...
5,340,798
def bias_variable(shape): """ 返回指定形状的偏置量 :param shape: :return: """ b = tf.Variable(tf.constant(0.0, shape=shape)) return b
5,340,799