content
stringlengths
22
815k
id
int64
0
4.91M
def test_parse_module(walk_mock, n_classes, n_functions): """Parses a module and creates a ModuleStructure""" module_node = create_module_node() class_nodes = [create_class_node() for _ in range(n_classes)] function_nodes = [create_function_node() for _ in range(n_functions)] nodes = [module_node] +...
26,500
def print_matrix(matrix, fmt="g"): """Pretty prints a 2d matrix Parameters: matrix: `np.array` a 2D numpy array """ col_maxes = [max([len(("{:"+fmt+"}").format(x)) for x in col]) for col in matrix.T] for x in matrix: for i, y in enumerate(x): print(("{:"+str(c...
26,501
def project_from_id(request): """ Given a request returns a project instance or throws APIUnauthorized. """ try: pm = ProjectMember.objects.get( user=request.user, project=request.GET['project_id'], ) except ProjectMember.DoesNotExist: raise APIUna...
26,502
def addRotatingFileHandler(logger: Union[logging.Logger, str], fName: Optional[str] = None, dirPath: Optional[str] = None, fmt: Optional[logging.Formatter] = None, level: int = logging.DEBUG, ...
26,503
def make_beampipe_from_end(pipe_aperture, pipe_length, loc=(0, 0, 0), rotation_angles=(0, 0, 0)): """Takes an aperture and creates a pipe. The centre of the face of aperture1 will be at loc and rotations will happen about that point. Assumes the aperture is initially centred on (0,0,0) Args: ...
26,504
def add_srcDexToShellDex(srcDex, shellDex): """ 将原DEX添加到壳DEX尾部,保存到本目录下为classes.dex :param srcDex: 源dxe路径 :param shellDex: 壳dxe路径 :return: """ liShellDt = [] liSrcDexDt = [] liAllDt = [] # 将原始DEX和壳DEX数据放在一个列表中 with open(shellDex, "rb") as f: shellData = f...
26,505
def encode_string(value): """Replace and encode all special characters in the passed string. Single quotation marks need to be doubled. Therefore, if the string contains a single quotation mark, it is going to be replaced by a pair of such quotation marks. """ value = value.replace('\'', '\'\'') ...
26,506
async def make_json_photo(): """Photo from web camera in base64. """ img, _ = get_png_photo() if img: result = {"image": png_img_to_base64(img)} else: result = {"error": "Camera not available"} return result
26,507
def near_field_point_matching(source, position, size, k, lmax, sampling): """Decompose a source into VSHs using the point matching method in the near field Returns p_src[2,rmax] Arguments: source source object position position around which to decompose ...
26,508
def scan_enm(pdb_filepath, output_dir, flag_combination="-ca -het -c 8.00"): """ Executes Shell script with essential DDPT routines. For inputs see scan_enm.sh """ # Usage: scan_enm.sh <pdb-filepath> <results-filepath> <cutoff> subprocess.call(['bash', 'src/simulation/scan_enm.sh', pdb_filepath...
26,509
def Option( default: Any = MISSING, *, name: str = MISSING, description: str = MISSING, required: bool = MISSING, choices: Union[List[Union[str, int, float]], Dict[str, Union[str, int, float]]] = MISSING, min: int = MISSING, max: int = MISSING, type: Type[Any] = MISSING, cls: Typ...
26,510
def inverse(f, a, b, num_iters=64): """ For a function f that is monotonically increasing on the interval (a, b), returns the function f^{-1} """ if a >= b: raise ValueError(f"Invalid interval ({a}, {b})") def g(y): if y > f(b) or y < f(a): raise ValueError(f"Invalid...
26,511
def gmof(x, sigma): """ Geman-McClure error function """ x_squared = x ** 2 sigma_squared = sigma ** 2 return (sigma_squared * x_squared) / (sigma_squared + x_squared)
26,512
def download_data(vars): """ function to download data from the ACS website :param: geo_level (geoLevel object): which geophical granularity to obtain for the data vars (string): a file name that holds 3-tuples of the variables, (in the format returned by censusdata.search()), ...
26,513
def generate_setup_template_modify(outputfile='./tdose_setup_template_modify.txt',clobber=False,verbose=True): """ Generate setup text file template for modifying data cubes --- INPUT --- outputfile The name of the output which will contain the TDOSE setup template clobber Overwrite fi...
26,514
def update_cfg_with_env_overrides(cfg: dict) -> None: """Update solitude configuration with overrides from environment variables. Configuration overrides can be specified by setting environment variables with name "SOL_{config_name}", where config_name is the name of the configuration option wi...
26,515
def oddify(n): """Ensure number is odd by incrementing if even """ return n if n % 2 else n + 1
26,516
def method_matching(pattern: str) -> List[str]: """Find all methods matching the given regular expression.""" _assert_loaded() regex = re.compile(pattern) return sorted(filter(lambda name: re.search(regex, name), __index.keys()))
26,517
def update_binwise_positions(cnarr, segments=None, variants=None): """Convert start/end positions from genomic to bin-wise coordinates. Instead of chromosomal basepairs, the positions indicate enumerated bins. Revise the start and end values for all GenomicArray instances at once, where the `cnarr` bi...
26,518
async def respond_wrong_author( ctx: InteractionContext, author_must_be: Member | SnakeBotUser, hidden: bool = True ) -> bool: """Respond to the given context""" if not ctx.responded: await ctx.send( ephemeral=hidden, embeds=embed_message( "Error", ...
26,519
def ParseFloatingIPTable(output): """Returns a list of dicts with floating IPs.""" keys = ('id', 'ip', 'instance_id', 'fixed_ip', 'pool',) floating_ip_list = ParseNovaTable(output, FIVE_COLUMNS_PATTERN, keys) for floating_ip in floating_ip_list: if floating_ip['instance_id'] == '-': floating_ip['insta...
26,520
def build_entity_bucket(config, server): """プロジェクト構成ファイルからエンティティバケットを構築するファクトリ関数 Args: config (str): ファイル名 server (str): サーバ名 Returns: (Server, EntityBucket): サーバとエンティティバケットを返す """ server_, entity_bucket = Parser().parse(config, server, context=os.environ) return server...
26,521
def test_logging_to_progress_bar_with_reserved_key(tmpdir): """ Test that logging a metric with a reserved name to the progress bar raises a warning. """ class TestModel(BoringModel): def training_step(self, *args, **kwargs): output = super().training_step(*args, **kwargs) self....
26,522
def cdf_inverse(m, alpha, capacity, f, subint): """ This function computes the inverse value of a specific probability for a given distribution. Args: m (mesh): The initial mesh. alpha (float): The probability for which the inverse value is computed. capacity (float): The capaci...
26,523
def create_virtualenv(force=False): """ Bootstrap the environment. """ with hide('running', 'stdout'): exists = run('if [ -d "{virtualenv_dir}" ]; then echo 1; fi'.format(**env)) if exists: if not force: puts('Assuming virtualenv {virtualenv_dir} has already been created ...
26,524
def concatenation(clean_list): """ Concatenation example. Takes the processed list for your emails and concatenates any elements that are currently separate that you may wish to have as one element, such as dates. E.g. ['19', 'Feb', '2018'] becomes ['19 Feb 2018] Works best if the lists are simi...
26,525
def main(): """ Create z neural net to train and test GD-BP """ while(1): mode = get_input() if mode == TRAIN: print 'Train' X, Y = readData(mode) print 'Output labels:', numY print 'number of features:', numFeatures # spl...
26,526
def add_pattern_bd(x, distance=2, pixel_value=1): """ Augments a matrix by setting a checkboard-like pattern of values some `distance` away from the bottom-right edge to 1. Works for single images or a batch of images. :param x: N X W X H matrix or W X H matrix. will apply to last 2 :type x: `np.nda...
26,527
def _apply_dep_overrides(mmd, params): """ Apply the dependency override parameters (if specified) on the input modulemd. :param Modulemd.ModuleStream mmd: the modulemd to apply the overrides on :param dict params: the API parameters passed in by the user :raises ValidationError: if one of the over...
26,528
def calc_md5_sign(secret, parameters): """ 根据app_secret和参数串计算md5 sign,参数支持dict(建议)和str :param secret: str :param parameters: :return: """ if hasattr(parameters, "items"): keys = list(parameters.keys()) keys.sort() parameters_str = "%s%s%s" % (secret, ...
26,529
def tokenize(string): """ Scans the entire message to find all Content-Types and boundaries. """ tokens = deque() for m in _RE_TOKENIZER.finditer(string): if m.group(_CTYPE): name, token = parsing.parse_header(m.group(_CTYPE)) elif m.group(_BOUNDARY): token = ...
26,530
def query(obj,desc=None): """create a response to 'describe' cmd from k8s pod desc and optional custom properties desc """ # this is a simplified version compared to what the k8s servo has (single container only); if we change it to multiple containers, they will be the app's components (here the app is a singl...
26,531
def fastq(args): """ %prog fastq fastafile Generate fastqfile by combining fastafile and fastafile.qual. Also check --qv option to use a default qv score. """ from jcvi.formats.fastq import FastqLite p = OptionParser(fastq.__doc__) p.add_option("--qv", type="int", help="Use generic qv ...
26,532
def binary_cross_entropy(preds, targets, name=None): """Computes binary cross entropy given `preds`. For brevity, let `x = `, `z = targets`. The logistic loss is loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i])) Args: preds: A `Tensor` of type `float32` or `float64`. ...
26,533
def test_user_password_with_double_quote(data_dir, function_scope_messages_aggregator): """Test that a password containing " is accepted. Probably what caused https://github.com/rotki/rotki/issues/805 to be reported""" username = 'foo' password = 'pass"word' _user_creation_and_login( userna...
26,534
def permutation_generator(n): """ Generate all permutations of n elements as lists. The number of generated lists is n!, so be careful to use big n. For example, permutationGenerator(3) generates the following lists: [0, 1, 2] [0, 2, 1] [1, 0, 2] [1, 2, 0] [...
26,535
def upload_and_rec_beauty(request): """ upload and recognize image :param request: :return: """ from django.core.files.uploadedfile import InMemoryUploadedFile, TemporaryUploadedFile image_dir = 'cv/static/FaceUpload' if not os.path.exists(image_dir): os.makedirs(image_dir) ...
26,536
def weld_standard_deviation(array, weld_type): """Returns the *sample* standard deviation of the array. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject ...
26,537
def dev_to_abs_pos(dev_pos): """ When device position is 30000000, absolute position from home is 25mm factor = 30000000/25 """ global CONVFACTOR abs_pos = dev_pos*(1/CONVFACTOR) return abs_pos
26,538
def model_predict(model, test_loader, device): """ Predict data in dataloader using model """ # Set model to eval mode model.eval() # Predict without computing gradients with torch.no_grad(): y_preds = [] y_true = [] for inputs, labels in test_loader: inp...
26,539
def calc_precision_recall(frame_results): """Calculates precision and recall from the set of frames by summing the true positives, false positives, and false negatives for each frame. Args: frame_results (dict): dictionary formatted like: { 'frame1': {'true_pos': int, '...
26,540
def patch_fixture( scope="function", services=None, autouse=False, docker_client=None, region_name=constants.DEFAULT_AWS_REGION, kinesis_error_probability=0.0, dynamodb_error_probability=0.0, container_log_level=logging.DEBUG, localstack_verison="latest", auto_remove=True, pu...
26,541
def test_to_directed_adjacency_matrix(): """ antco.ntools.toDirAdjMatrix() testing unit """ expected = [ np.array([ [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0]], dtype=np.int8), np.array([ ...
26,542
def euler_to_quat(e, order='zyx'): """ Converts from an euler representation to a quaternion representation :param e: euler tensor :param order: order of euler rotations :return: quaternion tensor """ axis = { 'x': np.asarray([1, 0, 0], dtype=np.float32), 'y': np.asarray([0, ...
26,543
def test_api_user_create_bad(data, message, status_code): """ Test create role with bad data """ user = helper.api.user.current url = helper.api.role.create.url response = requests.post( url=url, headers={"Authorization": user["token"]}, json=data ) assert_api_error(response, message...
26,544
def setnumber(update,context): """ Bot '/setnumber' command: starter of the conversation to set the emergency number """ update.message.reply_text('Please insert the number of a person you trust. It can be your life saver!') return EMERGENCY
26,545
def mean_ale(covmats, tol=10e-7, maxiter=50, sample_weight=None): """Return the mean covariance matrix according using the AJD-based log-Euclidean Mean (ALE). See [1]. :param covmats: Covariance matrices set, (n_trials, n_channels, n_channels) :param tol: the tolerance to stop the gradient descent ...
26,546
def test_entities__Entity__removeField__1(entities, entity_with_field, field): """It removes a field from an entity.""" assert field in entities.values() entity_with_field.removeField(field) assert field not in entities.values()
26,547
def get_affiliate_code_from_qstring(request): """ Gets the affiliate code from the querystring if one exists Args: request (django.http.request.HttpRequest): A request Returns: Optional[str]: The affiliate code (or None) """ if request.method != "GET": return None a...
26,548
def get_gifti_labels(gifti): """Returns labels from gifti object (*.label.gii) Args: gifti (gifti image): Nibabel Gifti image Returns: labels (list): labels from gifti object """ # labels = img.labeltable.get_labels_as_dict().values() label_dict = gifti...
26,549
def get_temporal_info(data): """Generates the temporal information related power consumption :param data: a list of temporal information :type data: list(DatetimeIndex) :return: Temporal contextual information of the energy data :rtype: np.array """ out_info =[] for d in ...
26,550
def html_url(url: str, name: str = None, theme: str = "") -> str: """Create a HTML string for the URL and return it. :param url: URL to set :param name: Name of the URL, if None, use same as URL. :param theme: "dark" or other theme. :return: String with the correct formatting for URL """ i...
26,551
def animate( image_path: str = typer.Argument(..., help="Input file (png, jpg, etc)"), frames: int = typer.Option(30, "--frames", "-f", help="Number of frames in output gif"), duration: int = typer.Option(100, "--duration", "-d", help="Duration of each frame in output gif (ms)"), splits: int = typer.Opt...
26,552
def get_logger_messages(loggers=[], after=0): """ Returns messages for the specified loggers. If given, limits the messages to those that occured after the given timestamp""" if not isinstance(loggers, list): loggers = [loggers] return logger.get_logs(loggers, after)
26,553
def __dir__(): """IPython tab completion seems to respect this.""" return __all__
26,554
def run_iterations(histogram_for_random_words, histogram_for_text, iterations): """Helper function for test_stochastic_sample (below). Store the results of running the stochastic_sample function for 10,000 iterations in a histogram. Param: histogram_for_ran...
26,555
def generate_data_cli( fitting_function_name: Optional[str], polynomial_degree: Optional[int], a: Optional[str], random_x_min: float, random_x_max: float, min_coeff: float, max_coeff: float, x_sigma: float, y_sigma: float, output_dir: Union[str, Path], output_format: str, ): ...
26,556
def test_search_names_with_tag(): """Test search query.""" query = { "select": "df.free", "output": { "format": "csv" }, "where": { "team": "Stretch" }, } queryurl = "http://{0}:{1}/api/search".format(HOST, HTTPPORT) response = urlopen(queryurl, json.dumps(query)) expec...
26,557
def GetFootSensors(): """Get the foot sensor values""" # Get The Left Foot Force Sensor Values LFsrFL = memoryProxy.getData("Device/SubDeviceList/LFoot/FSR/FrontLeft/Sensor/Value") LFsrFR = memoryProxy.getData("Device/SubDeviceList/LFoot/FSR/FrontRight/Sensor/Value") LFsrBL = memoryProxy.getDat...
26,558
async def test_service_person(hass, aioclient_mock): """Set up component, test person services.""" aioclient_mock.get( ENDPOINT_URL.format("persongroups"), text=load_fixture("microsoft_face_persongroups.json"), ) aioclient_mock.get( ENDPOINT_URL.format("persongroups/test_group1/p...
26,559
def norm(x, y): """ Calculate the Euclidean Distance :param x: :param y: :return: """ return tf.sqrt(tf.reduce_sum((x - y) ** 2))
26,560
def expand_key(keylist, value): """ Recursive method for converting into a nested dict Splits keys containing '.', and converts into a nested dict """ if len(keylist) == 0: return expand_value(value) elif len(keylist) == 1: key = '.'.join(keylist) base = dict() ...
26,561
def _linear_sum_assignment(a, b): """ Given 1D arrays a and b, return the indices which specify the permutation of b for which the element-wise distance between the two arrays is minimized. Args: a (array_like): 1D array. b (array_like): 1D array. Returns: array_like: Indi...
26,562
def get_ingredients_for_slice_at_pos(pos, frame, pizza, constraints): """ Get the slice of pizza with its ingredients :param pos: :param frame: :param pizza: :param constraints: :return: """ def _get_ingredients_for_slice_at_pos(_pos, _frame, _pizza, _max_rows, _max_cols): if...
26,563
def merge_data_includes(tweets_data, tweets_include): """ Merges tweet object with other objects, i.e. media, places, users etc """ df_tweets_tmp = pd.DataFrame(tweets_data) # Add key-values of a nested dictionary in df_tweets_tmp as new columns df_tweets = flat_dict(df_tweets_tmp) for ...
26,564
def test_project_detail_catch_count_summary_table(client, project): """The project detail page should inlcude a table with the total catch and bio-smple catch by by species. If the biosamples count is 0, the speceis name should just be text, if there are samples, there should be a link to the detail pa...
26,565
def time_ordered( data, freq_sel=None, prod_sel=None, time_sel=None, part_sel=None, **kwargs ): """Plots data vs time for different frequencies and corr-pords.""" pass
26,566
def tag_length_validator(form, field): """ Make sure tags do not exceed the maximum tag length. """ tags = convert_to_tag_list_of_dicts(field.data) too_long_tags = [ tag['name'] for tag in tags if len(tag['name']) > mg_globals.app_config['tags_max_length']] if too_long_tags: ...
26,567
def ensure_dir(path): """ Make sure a given directory exists """ if not os.path.exists(path): os.makedirs(path)
26,568
def stringify(context, mapping, thing): """Turn values into bytes by converting into text and concatenating them""" if isinstance(thing, bytes): return thing # retain localstr to be round-tripped return b''.join(flatten(context, mapping, thing))
26,569
def main(output_dir_path: str, start_date: datetime.date, end_date: datetime.date): """Download data from the website and put it to /data/raw""" FILENAME = "posts_{}.csv" logger.info("downloading data...") for cur_date in daterange(start_date, end_date): #try: co...
26,570
def proc_file (p): """process simple file""" print (f"{p} is simple file") obj_add ('file', p)
26,571
def extract_from_json(json_str, verbose=False): """A helper function to extract data from KPTimes dataset in json format :param: json_str: the json string :param: verbose: bool, if logging the process of data processing :returns: the articles and keywords for each article :rtype: src (list of string...
26,572
def split_data(data, split_ratio, data_type=DATA_TYPE_1): """ split data by type """ data_type_1 = data[data['LABEL'] == data_type] data_type_2 = data[data['LABEL'] != data_type] train_set = data.sample(frac=split_ratio, replace=False) test_set = data[~data.index.isin(train_set.index)] ...
26,573
def _get_mtimes(arg: str) -> Set[float]: """ Get the modification times of any converted notebooks. Parameters ---------- arg Notebook to run 3rd party tool on. Returns ------- Set Modification times of any converted notebooks. """ return {os.path.getmtime(arg)}
26,574
def sparse_amplitude_prox(a_model, indices_target, counts_target, frame_dimensions, eps=0.5, lam=6e-1): """ Smooth truncated amplitude loss from Chang et al., Overlapping Domain Decomposition Methods for Ptychographic Imaging, (2020) :param a_model: K x M1 x M2 :param indices_target: K...
26,575
def p_repeat_statement(p): """repeat_statement : REPEAT statement_sequence UNTIL boolean_expression"""
26,576
def file_reader(path, format_name='all', filter_name='all', block_size=4096): """Read an archive from a file. """ with new_archive_read(format_name, filter_name) as archive_p: try: block_size = stat(path).st_blksize except (OSError, AttributeError): # pragma: no cover ...
26,577
def schema_as_fieldlist(content_schema: Dict[str, Any], path: str = "") -> List[Any]: """Return a list of OpenAPI schema property descriptions.""" fields = [] if "properties" in content_schema: required_fields = content_schema.get("required", ()) for prop, options in content_schema["proper...
26,578
def shrink(filename): """ :param filename: str, the location of the picture :return: img, the shrink picture """ img = SimpleImage(filename) new_img = SimpleImage.blank((img.width+1) // 2, (img.height+1) // 2) for x in range(0, img.width, 2): for y in range(0, img.height, 2):...
26,579
def test_invoice_str_representation(some_invoice: Invoice) -> None: """Properties for string representations are defined.""" invoice = some_invoice representations = [ invoice.items_str, invoice.company_and_client_str, invoice.invoice_str, ] assert all([isinstance(representat...
26,580
def eh_menor_que_essa_quantidade_de_caracters(palavra: str, quantidade: int) -> bool: """ Função para verificar se a string é menor que a quantidade de caracters informados @param palavra: A palavra a ser verificada @param quantidade: A quantidade de caracters que deseja verificar @return: Retorna T...
26,581
def buffer_sampler(ds,geom,buffer,val='median',ret_gdf=False): """ sample values from raster at the given ICESat-2 points using a buffer distance, and return median/mean or a full gdf ( if return gdf=True) Inputs = rasterio dataset, Geodataframe containing points, buffer distance, output value = median/...
26,582
def extract_int(str, start, end): """ Returns the integer between start and end. """ val = extract_string(str, start, end) if not val is None and re.match('^[0-9]{1,}$', val): return int(val) return None
26,583
def get_pg_ann(diff, vol_num): """Extract pedurma page and put page annotation. Args: diff (str): diff text vol_num (int): volume number Returns: str: page annotation """ pg_no_pattern = fr"{vol_num}\S*?(\d+)" pg_pat = re.search(pg_no_pattern, diff) try: pg_...
26,584
def train(args): """usage: {program} train [--config <config>] [--patch <patch>] [--fallback-to-cpu] [--tune] [--disable-comet] [--save-every-epoch] [--allow-unks] [--device=<device>] [--output-path=<path>] [--rewrite-output] Trains a language model according to the given config. Options: -C, --fall...
26,585
def check_diamond(structure): """ Utility function to check if the structure is fcc, bcc, hcp or diamond Args: structure (pyiron_atomistics.structure.atoms.Atoms): Atomistic Structure object to check Returns: bool: true if diamond else false """ cna_dict = structure.analyse.pys...
26,586
def compute_correlation( df: DataFrame, x: Optional[str] = None, y: Optional[str] = None, *, cfg: Union[Config, Dict[str, Any], None] = None, display: Optional[List[str]] = None, value_range: Optional[Tuple[float, float]] = None, k: Optional[int] = None, ) -> Intermediate: # pylint: ...
26,587
def radix_sort(arr): """Sort list of numberes with radix sort.""" if len(arr) > 1: buckets = [[] for x in range(10)] lst = arr output = [] t = 0 m = len(str(max(arr))) while m > t: for num in lst: if len(str(num)) >= t + 1: ...
26,588
def du(path, *args, **kwargs): """ pathに含まれるファイルのバイト数を取得する。 :param str path: パス :rtype: int :return: """ # 変数を初期化します。 _debug = kwargs.get("debug") logger = kwargs.get("logger") if not logger: logger = logging.getLogger(__file__) byte = 0 for root, _dir...
26,589
def resampling(w, rs): """ Stratified resampling with "nograd_primitive" to ensure autograd takes no derivatives through it. """ N = w.shape[0] bins = np.cumsum(w) ind = np.arange(N) u = (ind + rs.rand(N))/N return np.digitize(u, bins)
26,590
def integrated_bn(fms, bn): """iBN (integrated Batch Normalization) layer of SEPC.""" sizes = [p.shape[2:] for p in fms] n, c = fms[0].shape[0], fms[0].shape[1] fm = torch.cat([p.view(n, c, 1, -1) for p in fms], dim=-1) fm = bn(fm) fm = torch.split(fm, [s[0] * s[1] for s in sizes], dim=-1) r...
26,591
def get_RF_calculations(model, criteria, calculation=None, clus="whole", too_large=None, sgonly=False, regionalonly=False): """ BREAK DOWN DATA FROM CALCULATION! or really just go pickle """ print(f'{utils.time_now()} - Criteria: {criteria}, calculation: {calculation}, clus: {clus}, sgonly: {sgonly}...
26,592
def preprocessing_fn(inputs): """tf.transform's callback function for preprocessing inputs. Args: inputs: map from feature keys to raw not-yet-transformed features. Returns: Map from string feature key to transformed feature operations. """ outputs = {} # tf.io.decode_png function cannot be appli...
26,593
def test_move_attribs(attrib): """ Test moves over various conditions for each type of move tracking including modified sizes. 7 files: 1,2,3,C,D,4,5 all have different mtimes and are moved - 1,2 are unique content and size - 3,C are unique content but same size - D,4 are the sam...
26,594
def get_modules(pkg, recursive: bool = False): """get all modules in a package""" from plugin.helpers import log_plugin_error if not recursive: return [importlib.import_module(name) for finder, name, ispkg in iter_namespace(pkg)] context = {} for loader, name, ispkg in pkgutil.walk_package...
26,595
def TransformOperationHttpStatus(r, undefined=''): """Returns the HTTP response code of an operation. Args: r: JSON-serializable object. undefined: Returns this value if there is no response code. Returns: The HTTP response code of the operation in r. """ if resource_transform.GetKeyValue(r, 'st...
26,596
def split_record_fields(items, content_field, itemwise=False): """ This functionality has been moved to :func:`split_records()`, and this is just a temporary alias for that other function. You should use it instead of this. """ warnings.warn( "`split_record_fields()` has been renamed `split_...
26,597
def flask_formats() -> Response: """Invoke formats() from flask. Returns: Flask HTTP response """ envs = cast(Dict[str, str], os.environ) return _as_response(formats(envs, _as_request(flash_request), envs.get("FLASK_ENV", "prod")))
26,598
def prony(signal): """Estimates amplitudes and phases of a sparse signal using Prony's method. Single-ancilla quantum phase estimation returns a signal g(k)=sum (aj*exp(i*k*phij)), where aj and phij are the amplitudes and corresponding eigenvalues of the unitary whose phases we wish to estimate. Wh...
26,599