content
stringlengths
22
815k
id
int64
0
4.91M
def poll_apple_subscription(): """Poll Apple API to update AppleSubscription""" # todo: only near the end of the subscription for apple_sub in AppleSubscription.query.all(): user = apple_sub.user verify_receipt(apple_sub.receipt_data, user, APPLE_API_SECRET) verify_receipt(apple_sub....
5,700
def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Faster R-CNN demo') parser.add_argument('im', help="Input image", default= '000456.jpg') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) ...
5,701
def login(): """The screen to log the user into the system.""" # call create_all to create database tables if this is the first run db.create_all() # If there are no users, create a default admin and non-admin if len(User.query.all()) == 0: create_default_users() # Redirect the user if a...
5,702
def freight_sep_2014(): """Find the number of freight of the month""" for i in fetch_data_2014(): if i[1] == "Freight" and i[4] == "September": num_0 = i[6] return int(num_0)
5,703
def convexhull( input_path: Union[str, "os.PathLike[Any]"], output_path: Union[str, "os.PathLike[Any]"], input_layer: Optional[str] = None, output_layer: Optional[str] = None, columns: Optional[List[str]] = None, explodecollections: bool = False, nb_parallel: int = -1, batchsize: int = -...
5,704
def piotroski_f(df_cy,df_py,df_py2): """function to calculate f score of each stock and output information as dataframe""" f_score = {} tickers = df_cy.columns for ticker in tickers: ROA_FS = int(df_cy.loc["NetIncome",ticker]/((df_cy.loc["TotAssets",ticker]+df_py.loc["TotAssets",ticker])/2) > 0)...
5,705
def evaluate_circuit( instances: Dict[str, SType], connections: Dict[str, str], ports: Dict[str, str], ) -> SDict: """evaluate a circuit for the given sdicts.""" # it's actually easier working w reverse: reversed_ports = {v: k for k, v in ports.items()} block_diag = {} for name, S in i...
5,706
def main(): """The function main() does the following: 1. Creates a grid 2. Test connectivity between the start and end points 3. If there is connectivity it finds and plots the found path """ grid = create_grid(DIMENSION, ALPHA) grid_orig = [] grid_orig = copy.deepcopy(grid)...
5,707
def canonical_smiles_from_smiles(smiles, sanitize = True): """ Apply canonicalisation with rdkit Parameters ------------ smiles : str sanitize : bool Wether to apply rdkit sanitisation, default yes. Returns --------- canonical_smiles : str Returns None if canonicali...
5,708
def get_ref(struct, ref, leaf=False): """ Figure out if a reference (e.g., "#/foo/bar") exists within a given structure and return it. """ if not isinstance(struct, dict): return None parts = ref_parts(ref) result = {} result_current = result struct_current = struct ...
5,709
def delete_files(dpath: str, label: str='') -> str: """ Delete all files except the files that have names matched with label If the directory path doesn't exist return 'The path doesn't exist' else return the string with the count of all files in the directory and the count of deleted files....
5,710
def start(): """This function initializes and saves the needed variables""" start.nameList = [] # List to save the different names of the locators (their numbers) start.locList = [] # List to save a reference to the locators themselves start.locPosList = [] # List to s...
5,711
def edit_maker_app( operator, app_maker_code, app_name="", app_url="", developer="", app_tag="", introduction="", add_user="", company_code="", ): """ @summary: 修改 maker app @param operator:操作者英文id @param app_maker_code: maker app编码 @param app_name:app名称,可选参数,为空则不...
5,712
def fifo(): """ Returns a callable instance of the first-in-first-out (FIFO) prioritization algorithm that sorts ASDPs by timestamp Returns ------- prioritize: callable a function that takes an ASDP type name and a dict of per-type ASDPDB metadata, as returned by `asdpdb.load_as...
5,713
def super(d, t): """Pressure p and internal energy u of supercritical water/steam as a function of density d and temperature t (deg C).""" tk = t + tc_k tau = tstar3 / tk delta = d / dstar3 taupow = power_array(tau, tc3) delpow = power_array(delta, dc3) phidelta = nr3[0] * delpow[-1] +...
5,714
def ls(query=None, quiet=False): """List and count files matching the query and compute total file size. Parameters ---------- query : dict, optional (default: None) quiet : bool, optional Whether to suppress console output. """ tty.screen.status('Searching ...', mode='stati...
5,715
def test_count_with_skip(service): """Check getting $count with $skip""" # pylint: disable=redefined-outer-name responses.add( responses.GET, f"{service.url}/Employees/$count?$skip=12", json=11, status=200) request = service.entity_sets.Employees.get_entities().skip(12...
5,716
def _create_full_gp_model(): """ GP Regression """ full_gp_model = gpflow.models.GPR( (Datum.X, Datum.Y), kernel=gpflow.kernels.SquaredExponential(), mean_function=gpflow.mean_functions.Constant(), ) opt = gpflow.optimizers.Scipy() opt.minimize( full_gp_model...
5,717
def prime_factors(n, multiplicities=False): """ Generates the distinct prime factors of a positive integer n in an ordered sequence. If the 'multiplicities' option is True then it generates pairs of prime factors of n and their multiplicities (largest exponent e such that p^e divides...
5,718
def read_file_header(fd, endian): """Read mat 5 file header of the file fd. Returns a dict with header values. """ fields = [ ('description', 's', 116), ('subsystem_offset', 's', 8), ('version', 'H', 2), ('endian_test', 's', 2) ] hdict = {} for name, fmt, num_...
5,719
def shape_padleft(t, n_ones=1): """Reshape `t` by left-padding the shape with `n_ones` 1s. See Also -------- shape_padaxis shape_padright Dimshuffle """ _t = aet.as_tensor_variable(t) pattern = ["x"] * n_ones + [i for i in range(_t.type.ndim)] return _t.dimshuffle(pattern)
5,720
def zad1(x): """ Функция выбирает все элементы, идущие за нулём. Если таких нет, возвращает None. Если такие есть, то возвращает их максимум. """ zeros = (x[:-1] == 0) if np.sum(zeros): elements_to_compare = x[1:][zeros] return np.max(elements_to_compare) return None
5,721
def skopt_space(hyper_to_opt): """Create space of hyperparameters for the gaussian processes optimizer. This function creates the space of hyperparameter following skopt syntax. Parameters: hyper_to_opt (dict): dictionary containing the configuration of the hyperparameters to optimize....
5,722
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train a R2CNN network') parser.add_argument('--img_dir', dest='img_dir', help='images path', default='/mnt/USBB/gx/DOTA/DOTA_clip/val/images/', type=str) ...
5,723
def process_text_embedding(text_match, text_diff): """ Process text embedding based on embedding type during training and evaluation Args: text_match (List[str]/Tensor): For matching caption, list of captions for USE embedding and Tensor for glove/fasttext embeddings text_di...
5,724
def compress_image(filename): """ Function to resize(compress) image to a given size :param filename: Image to resize :return: None """ from PIL import Image # library for compressing images # open file to be compressed img = Image.open(filename) # compress the image accord...
5,725
def x5u_vulnerability(jwt=None, url=None, crt=None, pem=None, file=None): """ Check jku Vulnerability. Parameters ---------- jwt: str your jwt. url: str your url. crt: str crt path file pem: str pem file name file: str jwks file name Retur...
5,726
def test_failing_build_cmd(env: LlvmEnv, tmpdir): """Test that reset() raises an error if build command fails.""" (Path(tmpdir) / "program.c").touch() benchmark = env.make_benchmark(Path(tmpdir) / "program.c") benchmark.proto.dynamic_config.build_cmd.argument.extend( ["$CC", "$IN", "-invalid-c...
5,727
def from_kitti( data_dir: str, data_type: str, ) -> List[Frame]: """Function converting kitti data to Scalabel format.""" if data_type == "detection": return from_kitti_det(data_dir, data_type) frames = [] img_dir = osp.join(data_dir, "image_02") label_dir = osp.join(data_dir, "lab...
5,728
def get_all_interactions(L, index_1=False): """ Returns a list of all epistatic interactions for a given sequence length. This sets of the order used for beta coefficients throughout the code. If index_1=True, then returns epistatic interactions corresponding to 1-indexing. """ if index_1: ...
5,729
def convertSVG(streamOrPath, name, defaultFont): """ Loads an SVG and converts it to a DeepSea vector image FlatBuffer format. streamOrPath: the stream or path for the SVG file. name: the name of the vector image used to decorate material names. defaultFont: the default font to use. The binary data is returned. ...
5,730
def to_accumulo(df, config: dict, meta: dict, compute=True, scheduler=None): """ Paralell write of Dask DataFrame to Accumulo Table Parameters ---------- df : Dataframe The dask.Dataframe to write to Accumulo config : dict Accumulo configuration to use to connect to accumulo ...
5,731
def compute_euclidean_distance(x, y): """ Computes the euclidean distance between two tensorflow variables """ d = tf.reduce_sum(tf.square(x-y),axis=1,keep_dims=True) return d
5,732
def vpn_ping(address, port, timeout=0.05, session_id=None): """Sends a vpn negotiation packet and returns the server session. Returns False on a failure. Basic packet structure is below. Client packet (14 bytes):: 0 1 8 9 13 +-+--------+-----+ |x| cli_id |?????| +-+--------+-----+ ...
5,733
def setup_logging( default_path='logging.json', level = None, env_key='LOG_CFG' ): """ Setup logging configuration """ path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with ...
5,734
def is_admin(): """Checks if author is a server administrator, or has the correct permission tags.""" async def predicate(ctx): return ( # User is a server administrator. ctx.message.channel.permissions_for(ctx.message.author).administrator # User is a developer. ...
5,735
def send_message(chat_id): """Send a message to a chat If a media file is found, send_media is called, else a simple text message is sent """ files = request.files if files: res = send_media(chat_id, request) else: message = request.form.get("message", default="Empty Message"...
5,736
def get_neighbours(sudoku, row, col): """Funkcja zwraca 3 listy sasiadow danego pola, czyli np. wiersz tego pola, ale bez samego pola""" row_neighbours = [sudoku[row][y] for y in range(9) if y != col] col_neighbours = [sudoku[x][col] for x in range(9) if x != row] sqr_neighbours = [sudoku[x][y] for x in...
5,737
def to_ndarray(image): """ Convert torch.Tensor or PIL.Image.Image to ndarray. :param image: (torch.Tensor or PIL.Image.Image) image to convert to ndarray :rtype (ndarray): image as ndarray """ if isinstance(image, torch.Tensor): return image.numpy() if isinstance(image, PIL.Image....
5,738
def make_map_exposure_true_energy(pointing, livetime, aeff, ref_geom, offset_max): """Compute exposure WcsNDMap in true energy (i.e. not convolved by Edisp). Parameters ---------- pointing : `~astropy.coordinates.SkyCoord` Pointing direction livetime : `~astropy.units.Quantity` Live...
5,739
def test_b64_reference() -> None: """Test b64() with test cases from the base64 RFC.""" test_cases = [ (b"", b""), (b"f", b"Zg"), (b"fo", b"Zm8"), (b"foo", b"Zm9v"), (b"foob", b"Zm9vYg"), (b"fooba", b"Zm9vYmE"), (b"foobar", b"Zm9vYmFy"), ] for te...
5,740
def calc_random_piv_error(particle_image_diameter): """ Caclulate the random error amplitude which is proportional to the diameter of the displacement correlation peak. (Westerweel et al., 2009) """ c = 0.1 error = c*np.sqrt(2)*particle_image_diameter/np.sqrt(2) return error
5,741
def resolve(name, module=None): """Resolve ``name`` to a Python object via imports / attribute lookups. If ``module`` is None, ``name`` must be "absolute" (no leading dots). If ``module`` is not None, and ``name`` is "relative" (has leading dots), the object will be found by navigating relative to ``mod...
5,742
def fibonacci(n:int) -> int: """Return the `n` th Fibonacci number, for positive `n`.""" if 0 <= n <= 1: return n n_minus1, n_minus2 = 1,0 result = None for f in range(n - 1): result = n_minus2 + n_minus1 n_minus2 = n_minus1 n_minus1 = result return result
5,743
def change_level(new_level=''): """ Change the level of the console handler """ log = logging.getLogger('') for hndl in log.handlers: if isinstance(hndl, logging.StreamHandler): if new_level: hndl.setLevel(ll[new_level.upper()]) return
5,744
def event_social_link(transaction): """ GET /social-links/1/event :param transaction: :return: """ with stash['app'].app_context(): social_link = SocialLinkFactory() db.session.add(social_link) db.session.commit()
5,745
def get_budget(product_name, sdate): """ Budget for a product, limited to data available at the database :param product_name: :param sdate: starting date :return: pandas series """ db = DB('forecast') table = db.table('budget') sql = select([table.c.budget]).where(table.c.product_na...
5,746
def p_function_call(p): """FunctionCall : FunctionName '(' Arguments ')' """ p[0] = ast.FunctionCall(p[1], *p[3])
5,747
def stop(remove): """ Stop (and optionally remove, --remove) all containers running in background. """ if remove: cmd='docker-compose down' else: cmd='docker-compose stop' project_root=get_project_root() os.chdir(project_root) bash_command("Stopping containers", cmd)
5,748
def test_cli_size_opt(runner): """Test the CLI with size opt.""" resp = runner.invoke(cli.app, ['--size', '125', 'tests/data/sample image.png']) # noqa: E501 assert resp.exit_code == 0 assert resp.output.rstrip() == 'https://nsa40.casimages.com/img/2020/02/17/200217113356178313.png'
5,749
def _residual_block_basic(filters, kernel_size=3, strides=1, use_bias=False, name='res_basic', kernel_initializer='he_normal', kernel_regularizer=regulizers.l2(1e-4)): """ Return a basic residual layer block. :param filters: Number of filters. :param kernel_size...
5,750
def main(bibtex_path: str): """ Entrypoint for migrate.py :params bibtex_path: The PATH to the BibTex (.bib) file on the local machine. """ # Load BibTex file and parse it bibtex_db = load_bibtex_file( file_path=bibtex_path) # Obtain every entry key name bibtex_keys = bibtex_db.e...
5,751
def time_count(start, end): """ Definition: Simple function that prints how many seconds it took to run from the 'start' variable to the 'end' variable. Args: start: Required. Usually a time.time() variable at the beginning of a cell. end: Required. Usually a time.time() variable at the end of a cell. ...
5,752
def console_script(tmpdir): """Python script to use in tests.""" script = tmpdir.join('script.py') script.write('#!/usr/bin/env python\nprint("foo")') return script
5,753
def parse_tpl_file(tpl_file): """ parse a PEST-style template file to get the parameter names Args: tpl_file (`str`): path and name of a template file Returns: [`str`] : list of parameter names found in `tpl_file` Example:: par_names = pyemu.pst_utils.parse_tpl_file("my.tpl") ...
5,754
def test_setup_slack(db, mocker): """ Check that the correct operations are applied to create a channel. """ study = StudyFactory() channel_name = study.kf_id.lower().replace("_", "-") mock_client = mocker.patch("creator.slack.WebClient") mock_client().conversations_create.return_value = { ...
5,755
def es_append_cve_by_query(es_index, q, cve): """Appends cve to all IPs in es_index by query""" es = get_es_object() es.update_by_query(index=es_index, body={"script": {"inline": "if (ctx._source.cves == null) {ctx._source.cves = params.cvesparam }" ...
5,756
def _save_downscaled( item: Item, image: Image, ext: str, target_type: str, target_width: int, target_height: int, ) -> Media: """Common downscale function.""" if ext != 'jpg': image = image.convert('RGB') # TODO - these parameters are only for jpg ...
5,757
def get_single_image_results(pred_boxes, gt_boxes, iou_thr): """Calculates number of true_pos, false_pos, false_neg from single batch of boxes. Args: gt_boxes (list of list of floats): list of locations of ground truth objects as [xmin, ymin, xmax, ymax] pred_boxes (d...
5,758
def get_list(caller_id): """ @cmview_user @response{list(dict)} PublicIP.dict property for each caller's PublicIP """ user = User.get(caller_id) ips = PublicIP.objects.filter(user=user).all() return [ip.dict for ip in ips]
5,759
def matrix_zeros(m, n, **options): """"Get a zeros matrix for a given format.""" format = options.get('format', 'sympy') dtype = options.get('dtype', 'float64') spmatrix = options.get('spmatrix', 'csr') if format == 'sympy': return zeros(m, n) elif format == 'numpy': return _nump...
5,760
def make_password(password, salt=None): """ Turn a plain-text password into a hash for database storage Same as encode() but generate a new random salt. If password is None then return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string, which disallows logins. Additional random string ...
5,761
def get_dialect( filename: str, filehandle: Optional[TextIO] = None ) -> Type[csv.Dialect]: """Try to guess dialect based on file name or contents.""" dialect: Type[csv.Dialect] = csv.excel_tab file_path = Path(filename) if file_path.suffix == ".txt": pass elif file_path.suffix == ".csv...
5,762
def load_object(primary_path: str, file_name: Optional[str] = None, module: Optional[str] = "pickle") -> Any: """ This is a generic function to load any given object using different `module`s, e.g. pickle, dill, and yaml. Note: See `get_file_path()` for details on how how to set `primary_...
5,763
def compute_spectrogram( audio: Union[Path, Tuple[torch.Tensor, int]], n_fft: int, win_length: Optional[int], hop_length: int, n_mels: int, mel: bool, time_window: Optional[Tuple[int, int]], **kwargs, ) -> torch.Tensor: """ Get the spectrogram of an audio file. Args: ...
5,764
def decode_html_dir(new): """ konvertiert bestimmte Spalte in HTML-Entities """ def decode(key): return decode_html(unicode(new[key])) if new.has_key('title') and new['title'].find('&') >= 0: new['title'] = decode('title') if new.has_key('sub_title') and new['sub_title'].find('&') >= 0: new['sub_t...
5,765
def apply_hash(h, key): """ Apply a hash function to the key. This function is a wrapper for xxhash functions with initialized seeds. Currently assume h is a xxhash.x32 object with initialized seed If we change choice of hash function later, it will be easier to change how we apply the hash (either through a func...
5,766
def test_experiment_mnist_custom(experiment_files_fixture): """ Test of a MIA on the MNIST dataset with custom model for the MNIST model, custom mode for the MIA model and custom optimizer options """ experiment(academic_dataset = 'mnist', target_model_path = target_path.as_posix(), ...
5,767
def dmsp_enz_deg( c, t, alpha, vmax, vmax_32, kappa_32, k ): """ Function that computes dD32_dt and dD34_dt of DMSP Parameters ---------- c: float. Concentration of DMSP in nM. t: int Integration time in min. alpha: float. Alpha for cleavage by Ddd...
5,768
def debug(msg): """If program was run with -d argument, send parm string to stdout.""" if DEBUG_ENABLED: print("Debug: {}".format(msg))
5,769
def plot_holdings(returns, positions, legend_loc='best', ax=None, **kwargs): """Plots total amount of stocks with an active position, either short or long. Displays daily total, daily average per month, and all-time daily average. Parameters ---------- returns : pd.Series Daily ret...
5,770
def get_systemd_run_args(available_memory): """ Figure out if we're on system with cgroups v2, or not, and return appropriate systemd-run args. If we don't have v2, we'll need to be root, unfortunately. """ args = [ "systemd-run", "--uid", str(os.geteuid()), "--g...
5,771
def distribution_plot(x1, x2=None, x3=None, x4=None, label1='train', label2='back_test', label3=None, label4 = None, title=None, xlabel=None, ylabel=None, figsize=(12, 3)): """ :param x1: pd series or np array with shape (n1,) :param x2: pd series or np array...
5,772
def concatenation_sum(n: int) -> int: """ Algo: 1. Find length of num (n), i.e. number of digits 'd'. 2. Determine largest number with 'd - 1' digits => L = 10^(d - 1) - 1 3. Find diff => f = n - L 4. Now, the sum => s1 = f * d, gives us the number of digits in the string formed ...
5,773
def customize_compiler_gcc(self): """inject deep into distutils to customize how the dispatch to gcc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So ...
5,774
def make_join_conditional(key_columns: KeyColumns, left_alias: str, right_alias: str) -> Composed: """ Turn a pair of aliases and a list of key columns into a SQL safe string containing join conditionals ANDed together. s.id1 is not distinct from d.id1 and s.id2 is not distinct from d.id2 """ ...
5,775
def home(): """ Home interface """ return '''<!doctype html> <meta name="viewport" content="width=device-width, initial-scale=1" /> <body style="margin:0;font-family:sans-serif;color:white"> <form method="POST" action="analyse" enctype="multipart/form-data"> <label style="text-align:center;position:fixe...
5,776
def step_use_log_record_configuration(context): """ Define log record configuration parameters. .. code-block: gherkin Given I use the log record configuration: | property | value | | format | | | datefmt | | """ assert context.table, "REQ...
5,777
def _enable_mixed_precision_graph_rewrite_base(opt, loss_scale, use_v1_behavior): """Enables mixed precision. See `enable_mixed_precision_graph_rewrite`.""" opt = _wrap_optimizer(opt, loss_scale, use_v1_behavior=use_v1_behavior) config.set_optimizer_experimental_opti...
5,778
def get_args() -> ProgramArgs: """ utility method that handles the argument parsing via argparse :return: the result of using argparse to parse the command line arguments """ parser = argparse.ArgumentParser( description="simple assembler/compiler for making it easier to write SHENZHEN.IO pr...
5,779
def selection_criteria_1(users, label_of_interest): """ Formula for Retirement/Selection score: x = sum_i=1_to_n (r_i) — sum_j=1_to_m (r_j). Where first summation contains reliability scores of users who have labeled it as the same as the label of interest, second summation contains reliability scor...
5,780
def get_default_product_not_found(product_category_id: str) -> str: """Get default product. When invalid options are provided, the defualt product is returned. Which happens to be unflavoured whey at 2.2 lbs. This is PRODUCT_INFORMATION. """ response = requests.get(f'https://us.myprotein.com/{produ...
5,781
def tscheme_pendown(): """Lower the pen, so that the turtle starts drawing.""" _tscheme_prep() turtle.pendown()
5,782
def book_number_from_path(book_path: str) -> float: """ Parses the book number from a directory string. Novellas will have a floating point value like "1.1" which indicates that it was the first novella to be published between book 1 and book 2. :param book_path: path of the currently parsed book ...
5,783
def intervals_split_merge(list_lab_intervals): """ 对界限列表进行融合 e.g. 如['(2,5]', '(5,7]'], 融合后输出为 '(2,7]' Parameters: ---------- list_lab_intervals: list, 界限区间字符串列表 Returns: ------- label_merge: 合并后的区间 """ list_labels = [] # 遍历每个区间, 取得左值右值字符串组成列表 for lab in list_la...
5,784
def antique(bins, bin_method=BinMethod.category): """CARTOColors Antique qualitative scheme""" return scheme('Antique', bins, bin_method)
5,785
def RegisterApiCallRouters(): """Registers all API call routers.""" # keep-sorted start api_call_router_registry.RegisterApiCallRouter( "ApiCallRobotRouter", api_call_robot_router.ApiCallRobotRouter) api_call_router_registry.RegisterApiCallRouter( "ApiCallRouterStub", api_call_router.ApiCallRouterS...
5,786
def do_request(batch_no, req): """execute one request. tail the logs. wait for completion""" tmp_src = _s3_split_url(req['input']) cpy_dst = _s3_split_url(req['output']) new_req = { "src_bucket": tmp_src[0], "src_key": tmp_src[1], "dst_bucket": cpy_dst[0], "dst_key": cp...
5,787
def bigwig_tss_targets(wig_file, tss_list, seq_coords, pool_width=1): """ Read gene target values from a bigwig Args: wig_file: Bigwig filename tss_list: list of TSS instances seq_coords: list of (chrom,start,end) sequence coordinates pool_width: average pool adjacent nucleotides of this width R...
5,788
def _robot_barcode(event: Message) -> str: """Extracts a robot barcode from an event message. Args: event (Message): The event Returns: str: robot barcode """ return str( next( subject["friendly_name"] # type: ignore for subject in event.message["ev...
5,789
def build_dist(srcdir, destdir='.', build_type='bdist_egg'): """ Builds a distribution using the specified source directory and places it in the specified destination directory. srcdir: str Source directory for the distribution to be built. destdir: str Directory where ...
5,790
def check_thirteen_fd(fds: List[Union[BI, FakeBI]]) -> str: """识别十三段形态 :param fds: list 由远及近的十三段形态 :return: str """ v = Signals.Other.value if len(fds) != 13: return v direction = fds[-1].direction fd1, fd2, fd3, fd4, fd5, fd6, fd7, fd8, fd9, fd10, fd11, fd12, fd13 = fd...
5,791
def set_process_tracking(template: str, channels: List[str]) -> str: """This function replaces the template placeholder for the process tracking with the correct process tracking. Args: template: The template to be modified. channels: The list of channels to be used. Returns: The m...
5,792
def solve(instance: Instance) -> InstanceSolution: """Solves the P||Cmax problem by using a genetic algorithm. :param instance: valid problem instance :return: generated solution of a given problem instance """ generations = 512 population_size = 128 best_specimens_number = 32 generator ...
5,793
def cube_disp_data(self,vmin=None,vmax=None,cmap=pylab.cm.hot,var=False): """ Display the datacube as the stack of all its spectra @param vmin: low cut in the image for the display (if None, it is 'smartly' computed) @param vmax: high cut in the image for the display (if None, it is 'smartly' computed) ...
5,794
def payee_transaction(): """Last transaction for the given payee.""" entry = g.ledger.attributes.payee_transaction(request.args.get("payee")) return serialise(entry)
5,795
def datasheet_check(part): """Datasheet check""" if part.datasheet == "": return # Blank datasheet ok assert part.datasheet.startswith("http"), "'{}' is an invalid URL".format(part.datasheet) code = check_ds_link(part.datasheet) assert code in (200,301,302), "link '{}' BROKEN, error code '{}...
5,796
def represent(element: Element) -> str: """Represent the regular expression as a string pattern.""" return _Representer().visit(element)
5,797
def read_dynamo_table(gc, name, read_throughput=None, splits=None): """ Reads a Dynamo table as a Glue DynamicFrame. :param awsglue.context.GlueContext gc: The GlueContext :param str name: The name of the Dynamo table :param str read_throughput: Optional read throughput - supports values from "0.1"...
5,798
def convert_to_bytes(text): """ Converts `text` to bytes (if it's not already). Used when generating tfrecords. More specifically, in function call `tf.train.BytesList(value=[<bytes1>, <bytes2>, ...])` """ if six.PY2: return convert_to_str(text) # In python2, str is byte elif six.PY3: ...
5,799