content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def header_pass(block): """ Check each block for potential header, if found, split (or extract) the given block into a header. Parameters ---------- block : Block A block to split or extract Returns ------- list A list of blocks and/or header """ # TODO: Add lo...
6d95b9d7cf5672c9b7ff0a58c39b26e580a85fd1
36,500
def ParseNetworks(value, project, version): """Build a list of PolicyNetworks or ResponsePolicyNetworks from command line args.""" if not value: return [] registry = api_util.GetRegistry(version) networks = [ registry.Parse( network_name, collection='compute.networks', pa...
c0d69dca0cee276d944585dec89190bb46bb089a
36,501
def do_something_bar(): """ bar! --- responses: 200: description: Success """ return do_something()
0d0e55c4a12652ad941e57f339f2a9cfb942b3d9
36,502
from datetime import datetime def login(): """用户登录接口 eg: { "username": "liuli", "password": "liuli" } Token Demo: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTYyNzc1MDQ1OCwianRpIjoiNzJjZjZkYzYtZDE5NS00NGRhLTg2NWUtNmNhZmY3MTdkMjMwIiwidHlwZSI6ImFjY2VzcyIsIn...
d54113e4d6b671f2f18117b1846d55d331dad36d
36,503
import re def fraction_to_word(aText, fractions): """Spell out fractions written with a '/'. """ aText = re.sub(r"1/2", fractions[0], aText) aText = re.sub(r"1/3", fractions[1], aText) aText = re.sub(r"2/3", fractions[2], aText) aText = re.sub(r"1/4", fractions[3], aText) aText = re.sub(r"3/4"...
15a99870f2161a354aa69fadc484435b9d37d477
36,504
def create_message_context_properties(message_type, message_id, source, identifier, is_cloud_event_format) -> dict: """Create message context properties dict from input param values.""" return { 'type': message_type, 'message_id': message_id, 'source': source, 'identifier': ident...
c5edd78abb5e584089456f4d50a656ce46a7666c
36,505
import threading import time def run_continuously(interval=1): """Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading.Event which can be set to cease continuous run. Please note that it is *intended behavior that...
b20790efae0a85b5bca9e3800a4025a6310c67ab
36,506
def remove_holes(mask): """ This method removes holes inside the the binary mask by assigning '1' to all regions that are not reachable from the mask corners :param mask: mask to process :return: mask with connected components without holes """ height, width = mask.shape postprocessed...
83a5eca955bde060542d7fbfcc32f64b17756b4a
36,507
def get_search_space(max_len, channel_range, search_space=[], now=0): """ Recursive. Get all configuration combinations :param max_len: max of the depth of model :param channel_range: list, the range of channel :param search_space: search space :param now: depth of model :return: ""...
eeffb0c9caee726edce71fd38aa9253080af6a0d
36,508
def create_gtf_file(input_file, output_file): """Create pseudo gtf file for all probes sequences `input_file`: A manifest csv file that contain probe information `output_file`: A pseudo gtf file that serve for annotation """ print colored("Stage 3: Creating custom gtf file from manifest file ...", "...
f53046c26608f1e72b8744da3bcf19309a1aea38
36,509
import os import json import sys def use_resultdb(): """Checks the luci context to determine if resultdb is configured.""" ctx_filename = os.environ.get("LUCI_CONTEXT") if ctx_filename: try: with open(ctx_filename) as ctx_file: ctx = json.load(ctx_file) rdb = ctx.get('resultdb', {}) ...
cc589171a8f07d7560a8987dffe6b56602fbdd3f
36,510
def remove_observations(acyclic_graph): """ Remove all observations from a symplectic acyclic_graph. """ result = acyclic_graph.copy() RemoveObservations().optimize_acyclic_graph(result) return result
a4cdcf1e00b72b33f974c761ea93b3ff3c56225a
36,511
def contours_by_Imax(data, minI_factor=8., cl_factor=1.2, num_contours=10): """Calculate the contours for the plot base on the maximum intensity.""" maxI = data.max() minI = maxI / minI_factor return [minI * cl_factor ** x for x in range(num_contours)]
c214c37ba0c924051d6b410f7237262a81c3087e
36,512
import msgpack def test_default_func_nested_str(): """ packb() default function nested str """ ref = Custom() def default(obj): return str(obj) assert ormsgpack.packb({"a": ref}, default=default) == msgpack.packb( {"a": str(ref)} )
2b09bd8fd5a767f0360f18bf19e9a1e18f2fe635
36,513
def getActivityRelations(URI): """Returns a list of activity flows that are *input of* and *output of* the specified activity. .. :quickref: Flows list query; Get list of flows related to a specified activity. **Example request**: .. sourcecode:: http GET /v1/activities/get_rel...
71e976e5c5d3e2a51ba021dcbe5f5e0f4062da4c
36,514
def make_wsgi_app(root_factory, includeme, registry=None, **settings): """Create and return a WSGI application.""" configurator_cls = pyramid_config.Configurator # Initialise a ``Configurator`` and apply the package configuration. if registry: config = configurator_cls(registry=registry) ...
fd1c648dbed1d3ab4e059e29744e3addb1c4b581
36,515
def wrench2msg(wrench): """ Converts a 6x1 wrench vector into a geometry_msgs/Twist message :type twist: numpy.array :param twist: 6x1 wrench matrix :rtype: geometry_msgs.msg.Wrench :return The ROS Wrench message """ wrench2=np.reshape(wrench, (6,)) return Wrench(Vector3(wrench2...
191101a0a223533aa98a2b15fd8b6049d580dd31
36,516
def get_fuzz_target_weights(): """Get a list of fuzz target weights based on the current fuzzer.""" # No work to do if this isn't fuzz task. Weights are only required if a # fuzzer has not yet been selected. task_name = environment.get_value('TASK_NAME') if task_name != 'fuzz': return None job_type = e...
47f6fae591d91e4a9d90d10971be24f509f62ac0
36,517
def measure_network_density(streets_for_networkd_prj, gross_city_blocks_prj): """ Adds network density (m/ha.) onto a gdf of gross urban blocks Requires a gdf of streets to overlay with the gross city blocks. Streets that are within a gross urban blocks (i.e. do not coincide with its perimeter) hav...
02ac06ef5fcb10576f30e16fd37acc1246b16535
36,518
def param_size(model, *args, **kwargs): """Return size of model parameters.""" val = 4 * param_count(model, format=False) return format_value(val, *args, binary=True, **kwargs) if format else val
76e747f292d9cead36c990f6c2e5e05787c88710
36,519
def resolve_source(ctx_file): """Resolve best URL from acquisition.""" # get settings # read in context with open(ctx_file) as f: ctx = json.load(f) ''' settings_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'settings.json') with open(settings_file) as f: ...
233a60c4044d396fade5dd98495682a21adbce52
36,520
import logging from datetime import datetime import pytz def now(update: Update , context : CallbackContext, lang) -> int: """ Thhis functions implements the quick search, after checking if the campus is in the preferences of the user call the end_state function, otherwise return to the initial_state ...
70bed261b912067ebdb8889420b161c960aa4e33
36,521
def __analyze_function(input_str: str) -> str: """ transfer the syntax from python to the math -- adding auto "*" sign between signed variables :param input_str: ~ :return: the modified input str """ var_element = [] # the variables and element which used in the input_str. it contains all the e...
d731f74c46ff1c5ad478f2f60c04a642c248ec20
36,522
import json def jsonNodeToAvroType(x): """Convert a Python-encoded Avro type into a titus.datatype.AvroType. :type x: dicts, lists, strings, numbers, ``True``, ``False``, ``None`` :param x: Avro type in Python form :rtype: titus.datatype.AvroType :return: AvroType object """ return schem...
1f99b9ddc583c6206fa48eef5f8f181629a51511
36,523
def wordfreq_viz( word_cnts: pd.Series, nrows: int, plot_width: int, plot_height: int, wordfreq: WordFrequency, ) -> Figure: """ Visualize the word frequency bar chart """ col = word_cnts.name df = word_cnts.to_frame() df["pct"] = df[col] / nrows * 100 tooltips = [ ...
d1ead2591bd07256f6ff05d55595aa2666dcfb9b
36,524
import json def scatter(): """Fake endpoint.""" if 'override' in request.args: with open('{}/examples/overrides.json'.format(cwd), 'r') as jsonfile: return jsonfile.read() return json.dumps({ "bar1": [1, 2, 30, 12, 100], "bar2": rr_list(max_range=40), "bar3": rr...
bd45a84977e6ec2888f2d71d8e416c3c613e1e60
36,525
def default_crop() -> Crop: """ Set Tea as the default crop. """ try: # Check whether Tea Object exists in Crop Model crop = Crop.objects.get(name="Tea") except Crop.DoesNotExist: crop_data = {} crop_data["name"] = "Tea" crop_data["initial_moisture"] = "69" ...
8ea868dbb82767d3207a3a8283166a14edec3019
36,526
def get_item(id: str): """ get any specific item """ item = item_service.get_item(id) if not item: raise HTTPException(status_code=404, detail="Item not found.") return item
0274904ff1f4033dd9652693152e82a4d16d951e
36,527
from functools import reduce import operator def get_nested_value(the_map, dot_separated_key): """Give a nested dictionary map, get the value specified by a dot-separated key where dots denote an additional depth. Taken from stack overflow (http://stackoverflow.com/a/12414913). """ keys = dot_separate...
082d199adc51376592bd215ab32a309807e6089e
36,528
from pathlib import Path import os from operator import sub def _transform_points(reg_dir: Path, points_file: Path, out_dir: Path) -> Path: """ Given a Lama output regisrtation directory and a points file, apply the concatenated transforms to the points and return the output points file. Parameters ...
5ad37113fa5ce140c3663255ccb49cbc453f4637
36,529
def cxSet(ind1, ind2): """Apply a crossover operation on input sets. The first child is the intersection of the two sets, the second child is the difference of the two sets. """ temp = set(ind1) # Used in order to keep type ind1 &= ind2 # Intersection (inplace) ind2 ^= temp # Symmetric Di...
8c64c6f9a219454288556109d1f99935937c40a3
36,530
def preprocess(self, im, allobj = None): """ Takes an image, return it as a numpy tensor that is readily to be fed into tfnet. If there is an accompanied annotation (allobj), meaning this preprocessing is serving the train process, then this image will be transformed with random noise to augment training data, us...
52972b7b4b75d74cc6d9730a5299cb9005fa4159
36,531
def get_module(obs_space: Space, action_space: Space, config: dict) -> nn.Module: """Retrieve and construct module of given name. Args: obs_space: Observation space action_space: Action space config: Configurations for module construction and initialization """ type_ = config.po...
1554ef3641a1b10468df770c4a0407800ff8547c
36,532
def safe_bcolz_open(fname, idx=None, debug=False): """Threadsafe way to read bcolz arrays. bcolz might have issues with multithreading and underlying blosc compression code. Lots of discussion out there, here are some starting points: http://www.pytables.org/latest/cookbook/threading.html ...
b9c3621b544fedd1d78e7728bea482a07c382ce5
36,533
def _replace_event_values_arr( timearr: NDArray[float], old_value: int, new_value: int ) -> NDArray[int]: """Replace the values 'old_value' with 'new_value' for the array.""" timearr[np.where(timearr == old_value)] = new_value return timearr
28a23d989798fa6b8dde55c64c0d52df1812f727
36,534
def validate_api_host_url(url): """ Validate SolveBio API host url. Valid urls must not be empty and must contain either HTTP or HTTPS scheme. """ if not url: raise SolveError('No SolveBio API host is set') # Default to https if no scheme is set if '://' not in url: url...
92f8bf36c8b39805c6cc76608f49c9a85efb2b6d
36,535
def search_permission_filter(): """Filter list of results.""" # Send empty query for admins if Permission(superuser_access).allows(g.identity): return Q() provides = get_user_provides() # Filter for public records public = Q('missing', field='_access.read') # Filter for restricted ...
9f7219b0cacbb3d27bffcd61e76f1e487f359692
36,536
def check_depth_submission(path): """Checks if all files required for the submission exist and are in the right format.""" ready_for_submission = True ready_for_submission = ready_for_submission and _check_frames(_get_test_frame_paths('depth', path, '.pfm')) return ready_for_submission
80e46c17d531f60976573db775a3cde70a3d01df
36,537
def qual2fastq(quals): """ Convert a list of quality scores to a single fastq line :param quals: A list of quality scores :type quals: list :return: A fastq quality string :rtype: str """ quality = [chr(q + 33) for q in quals] return "".join(quality)
e32f52da5a9ada3fdf8b1789c6e3982044f775f7
36,538
def generate_honeycomb_coordinates(n_x, n_y, scaling=1.0): """ Generate coordinates from a honeycomb mesh which can be used to set up a cell population. Parameters ---------- n_x: int number of columns n_y: int number of rows scaling: float distance between the c...
0207826e53714bcd780c28799d0879d53b5b0607
36,539
import pathlib def exists(path: str) -> bool: """Checks if path exists e.g j.sals.fs.exists("/home/rafy/testing_make_dir/test1") -> True j.sals.fs.exists("/home/rafy/testing_make_dir/fasdljd") -> False Args: path (str): path to check for existence Returns: bool: Tru...
a3b3717c947656042d3ddcf9e1107d3f6ec9c06d
36,540
def load_token(token): """ decrypt token and load User """ max_age = app.config['REMEMBER_COOKIE_DURATION'].total_seconds() data = login_serializer.loads(token, max_age=max_age) u = model.Users.query.filter_by(email=data[0]).first() if u and data[1] == u.password: return u retu...
afb1d1471c1d3d28e18fef575194fba6b4ede974
36,541
import this def heSHjuBBFVLp(): """Let notation.""" return Injector.let(bar=(this << 2).foo)
3ada0c74b4c3aa360ebaa15f00457abc4ed89e64
36,542
def _create_cql_update_query(key_space: str, table_name: str, set_columns_value_dict: dict, primary_key_values: dict) -> str: """ This function will create an update CQL query""" cql_update = "UPDATE " + key_space + "." + table_name + " SET " for key...
b133feef14daefe7f5cc82936c2399bad3139672
36,543
def apply_psd(signal_t, psd, sampling_rate=4096, apply_butter=True): """ Take a signal in the time domain, and a precalculated Power Spectral Density, and color the signal according to the given PSD. Args: signal_t: A signal in time domain (i.e. a 1D numpy array) psd: A Power Spectral D...
7289ff3135b94197dd9a97cfc44c07700eb553a4
36,544
def do_zoom_image_job(port_input_name: str, zoom_factor: float, do_interpolation: bool = True, port_output_name: str = None, level: PYRAMID_LEVEL = PYRAMID_LEVEL.LEVEL_0, wave_offset: int = 0, is_rgb: bool = False) -> str: """ Function for zoomin...
67d5475268a494459d4317799b07a5d969491eee
36,545
def update_raid_group_resync_speed(session, raid_id, minimum, maximum, return_type=None, **kwargs): """ Updates the speed at which a RAID group will rebuild using the minimum and maximum arguments. :type session: zadarapy.session.Session :param session: A valid za...
e40d387378e4a0499b2180980ff679b0df82dd46
36,546
import os import dill def write_lib_kde(kde, outname, libID): """Write a dict of KDE objects for one library. Parameters ---------- kde : {taxon:kde} outname : str output file name libID : int|str library ID Returns ------- str : file name of output. """ ...
99ac957d151ac5ad7f100a88c3c0a326e10b7e11
36,547
import os import yaml def loadToken(): """ get cookie and crumb from APPL page or disk. force = overwrite disk data """ refreshDays = 30 # refreh cookie every x days # set destinatioin file dataDir = os.path.expanduser('~')+'/twpData' dataFile = dataFile = os.path.join(dataDir,'...
8acaebfe9abcd57bd23b84cf9bf7fcca7b7ec430
36,548
def extract_file_number(file_name): """ Extract the file number from a file name """ file_name = str(file_name) dot_contents = file_name.split('.') hyp_contents = dot_contents[0].split('-') base_name = hyp_contents[len(hyp_contents) - 1] return int(base_name[:-1])
0b29ba7e75ddfcdc31832641d51f5f0a507021b0
36,549
from re import S def solve_rational_inequalities(eqs): """ Solve a system of rational inequalities with rational coefficients. Examples ======== >>> solve_rational_inequalities([[((Poly(-x + 1), Poly(1, x)), '>='), ... ((Poly(-x + 1), Poly(1, x)), '<=')]]) {...
5e471fc24fc272e33b7ba777694eae038c7874df
36,550
import torch def BHV_diffeo( ind_current_topo, dictionnary_topology_comparison, mask_topo_comparison, mask_topo, mask_segments, singular_template, singular_connections, n_leaves, template, template_connections, target, target_connections, ...
9f13b5a8405895ab66450989f2762029d050323b
36,551
def add_address(x, y): """Returns a string representation of the sum of the two parameters. x is a hex string address that can be converted to an int. y is an int. """ return "{0:08X}".format(int(x, 16) + y)
3e6fef3d5de0216c68c980b24d9f1ab05bc0a043
36,552
def inv_linear_DisPrinc_sparse( Tn=None, TTn=None, Tyn=None, R=None, yn=None, sol0=None, nchan=None, mu0=None, precond=None, verb=None, verb2head=None, # specific chi2n_tol=None, chi2n_obj=None, maxiter=None, tol=None, **kwdargs, ): """ Discrep...
64be8690491f89c43c945ec8963ef529371065b8
36,553
from pathlib import Path import sys def get_dist_name(): """Get the product name by reading distribution pom. """ global dist_name global dist_zip_name global product_version dist_pom_path = Path(workspace + "/" + product_id + "/" + DIST_POM_PATH[product_id]) if sys.platform.startswith('wi...
d6682676753e16cfd92a5b9ad409c58b1ba59f6b
36,554
import re def replaceRoadWithRd(a_string): """assumes a_string is a string returns a string, with "Rd." where a_string has "Road" """ pattern = "[Rr]oad" replacement = "Rd." result = re.sub(pattern, replacement, a_string) return result
08cafdc84c61fc4131f923bf65f271b1d08be0c9
36,555
def get(columns=None): """Get or create MetaData singleton.""" if columns is None: columns = _DEFAULT_COLUMNS global _METADATA if not _METADATA: _METADATA = MetaData(columns) return _METADATA
ef37b70a7f870543b5e19ed290e2fe3cbb26b015
36,556
def read_data(report_name: str): """Читает исходные данные по стоимости портфеля из файла""" data = pd.read_excel(REPORTS_DATA_PATH / f'{report_name}.xlsx', sheet_name=SHEET_NAME, header=0, index_col=0, converter...
714513b7c9538cbf7823fb1099420320dcd884a3
36,557
def extract_fcp_data(raw_data, status): """ extract data from smcli System_WWPN_Query output. Input: raw data returned from smcli Output: data extracted would be like: 'status:Free \n fcp_dev_no:1D2F\n physical_wwpn:C05076E9928051D1\n channel_path_id:8B\n npiv_wwp...
bbe9de1f075fa68a4130c44afea9d388b1a678d5
36,558
def prepare_design_symmetry(D: np.ndarray) -> np.ndarray: """Add to the design matrix strip simmetric to the one in the input Args ---- D: np.ndarray The design matrix as it comes from build_Design_Matrix Returns ------- New design matrix with appended the simmetric angles ...
2e5f1d9c01cf847f19985d51f04d0bf9e84821f7
36,559
def generate_output_html(htmlfile): """Load HTML template and add current date, return result""" try: with open(htmlfile) as f: html = f.read().format(date_string) return html except Exception as ex: logger.error('Exception occured while loading template {}. Details: ...
e7794d1d132858b45fba326d983b31d0e7c366e9
36,560
from typing import Union from typing import Dict def check_existence_and_date_s3(query_hash: Union[int, str]) -> Dict[str, str]: """Check if a query hash has corresponding result and query json on S3 Parameters ---------- query_hash : The query hash to check Returns ------- : ...
1d25d4869aa874b85a85dd376f8ff59e07712375
36,561
def verifying_key_from_hex(key: bytes): """Load the VerifyingKey from a compressed or uncompressed hex public key. """ id_byte = key[0] if not isinstance(id_byte, int): id_byte = ord(id_byte) if id_byte == 4: # Uncompressed public point # 1B ID + 32B x coord + 32B y coord = 6...
c87efcee39bd92a0988aeb85b3b055d8d6a951c7
36,562
def get_graph(): """Creates dictionary {node: {child1, child2, ..},..} for current TensorFlow graph. Result is compatible with networkx/toposort""" ops = tf.get_default_graph().get_operations() return {op: children(op) for op in ops}
a0b912395a550bf2f2b2bf929f7ab90b97a3ba98
36,563
def find_coord(find_coords, search_coords, tol=1.e-6): """ {TEST} Find the index for the coordinate in search_coords that matches the coordinate find_coords. :param find_coords: Coordinates for the point to find :type find_coords: tuple[ float ] :param search_coords: Coordinate lists ...
94fe9cee4ac639337f0a9b4649ac5893133b06f9
36,564
def nonOverlappingMinima(minDists, m, fromSeq=None): """ Returns the indices i such that (minDist[i] <= minDists[j] or fromSeq[i] != fromSeq[j]) for all j in [i, i + m - 1]. If fromSeq is not provided, the latter test always fails (i.e., both dists are assumed to be from the same sequence, and thus able to overlap...
5362dbdfa42b8d0aedb7b780720f793baae7ab4c
36,565
def draw_contour_(contour_img, contour, color, gradient_colors=("red", "blue"), min_size=10, filled=True, compute_mask=False): """ Draw a contour as optionally fill it with color. Differs from draw_contour() i...
73f4bc88699d9d090972a474f8826eb47e5a9cc8
36,566
import os def find_table_config_pairs(tag, paths): """ Args: str tag: part of filename to filter files to be used dict paths: hard-coded paths to output folders Out: dict path_pairs: keys "config" and "meet_table" """ aa = os.listdir(paths[ "configs"]) bb = os.listd...
6399890b43a9eccb6853246773a93ee2c66449a7
36,567
def list_to_include_array(data_list): """Convert python list to ble_gattc_include_array.""" data_array = _populate_array(data_list, driver.ble_gattc_include_array) return data_array
f84aea79d33d9de01047841891a67570ed161da7
36,568
def check_for_valid_numerical_encoding_of_labels(labels): """ Checks whether the labels are numerical labels satisfying the following requirements: 1. each label is an integer greater or equal to zero 2. the smallest label is zero The labels encoded by applying "sklearn.preprocessing.La...
a4e356b3d8680b330f6c6b9aff1082e95b39ec72
36,569
import torch def video_pack_sequences(in_batch): """ Pad the variable-length input sequences to fixed length :param in_batch: the original input batch of sequences generated by pytorch DataLoader :return: out_batch (list): the padded batch of sequences """ # Get the number of return va...
983b86cfb867268ca0759b4cdf29052153d97785
36,570
from operator import sub def generate_nologin_hash(public_string): """Generate hash for users who are not logged in""" hex_hash = sha256(settings.EMAIL_SECRET_KEY + public_string).hexdigest() # Decode the hex hash into base64, reducing the length of the code b64_hash = hex_hash.decode('hex').encode("...
7781848e151d1054d8338bef1728863c02a53b3c
36,571
def compute_v_dot_upper_bound(dV, mean, variance=None, beta=2.): """ Compute the safe set Parameters ---------- dV: np.array The derivatives of the Lyapunov function at grid points mean: np.array mean of the dynamics (including prior dynamics as mean) variance: np.array ...
927cec0dda57b55da9e30a1cd21e1c5ef8f7fa84
36,572
def success(pred_data, true_data): """TODO: Docstring for success. :input_data: TODO :input_data: List with a dict containing belief state, action, and response. :db: TODO :goals: TODO :booked_domains: TODO :returns: TODO """ jaccard = {"belief":[], "action":[]} for pred, t...
93f38d2aeb3f36d7b5401d2420b1e6710641a93a
36,573
import urllib import asyncio import os import ssl async def protocol_factory(cot_url: urllib.parse.ParseResult): """ Given a COT Destination URL, create a Connection Class Instance for the given protocol. `url` is urllib-parsed URL to remote host. eg. 'udp://example.com:1234' """ reader = No...
ad65747d32b529a74d482c80f7518b05e9ee8af6
36,574
import sys def _login(nick, password, users_storage, library) -> int: """ Function for login user in system :param nick: user nick :param password: user password :param users_storage: place where store all users :param library: library interface, join all library functions in one interface...
1a5d032b29ee97f81277467b1496aca795fc43b5
36,575
import json def decode_resource_id_options(request): """ Extract resource ID options from a HTTP request, making sure the keys have the same names as the ResourceIdentifier object's fields. """ return { # Resource ID 'resource_id': request['id'], 'target_platforms': json.dumps(requ...
97f61b5c1ffb82cb9f29caebb9a85d42348fbfa7
36,576
import os def vimming_process(path_to_file): """Search for vim editting that file with the ps command""" filename = escape_quotes(os.path.basename(path_to_file)) if not filename: return [] command = find_vimming_process_command(path_to_file) output = getoutput(command) if not output: ...
a4144f74440b767b405b45f24027cd5c3b4ddc44
36,577
import json def load_data(data): """ Wrapper to load json data, to be compatible with Python3. Returns: JSON data Keyword arguments: data: might be bytes or str """ if type(data) == bytes: return json.loads(data.decode("utf-8")) else: return json.loads(data)
c33c661c2a42d162d06c3e17487e072908fd0bf4
36,578
import itertools def Pauli_strings(num_qubits): """Returns the matrix representation of Pauli strings of size=num_qubits. e.g., for num_qubits=2, it returns the matrix representations of ['II','IX','IY','IZ,'XI','YI',...]""" pauli_labels = ['I', 'X', 'Y', 'Z'] Pauli_strings_matrices = [Pauli(''.join(p...
256fa607695c067c4d4c13543a5c7010e2c0b212
36,579
def factor_rank_autocorrelation(factor_data, period=1): """ Computes autocorrelation of mean factor ranks in specified time spans. We must compare period to period factor ranks rather than factor values to account for systematic shifts in the factor values of all names or names within a group. This ...
d1a527313aa44f0fbd0b9abe23581934c163cd1f
36,580
def indices_for(df, nprocs): """ group rows in dataframe and assign each group to each process Args: df: Pandas dataframe object nprocs: number of processes used Returns: indeces grouped to each process """ N = df.shape[0] L = int(N / nprocs) indices...
c68408e6fcf70b885ca86fb80f8c31b0bd07e334
36,581
def _dynamic_range(fig, range_padding=0.05, range_padding_units='percent'): """Automatically rescales figure axes range when source data changes.""" fig.x_range.range_padding = range_padding fig.x_range.range_padding_units = range_padding_units fig.y_range.range_padding = range_padding fig.y_range.r...
e3c82605ab20ad6ab3c6f2a6e6d32479a9012ed2
36,582
def norm(x): """ This function takes an array and makes it strictly superior to zero. This is NOT a normalizing function, as it doesn't scale each value relatively to the others. :param x: Array to make superior to zero. :return: Resulting array. """ return np.log(np.exp(x + 1))
630c77de869d36d02b987fa6d3c755501d162cd5
36,583
def _match_expr(parent, expr): """Match expressions to rewrite `A.select(A < 5)` into select expression The argument must match the parent, so this _won't_ be rewritten: `A.select(B < 5)` """ args = expr.args op = expr.op if ( expr.method_name == "apply" and len(args) == 2 ...
8eaaff2b5edf7c36ea500479bee70c7d67cff412
36,584
def generate_new_api_key(user_id): """ Generate a new API key for the user. :param user_id: User ID for which to generate a new API key :return: User object for that user ID with a modified API key :raises UserDoesNotExistException: If no user exists with the given user_id """ user = get_us...
e374fbc5f7da258e67ec2101741230e34b6b3eb9
36,585
def account_reset(): """Handler for account reset.""" return account_handler("account_reset")
c395bd8fa18080ddc4d9aaf8183d899aee6dfbd3
36,586
def _get_validated_config_mapping(name, config_schema, config_fn): """Config mapping must set composite config_schema and config_fn or neither.""" if config_fn is None and config_schema is None: return None elif config_fn is not None and config_schema is not None: return ConfigMapping(confi...
cddab5a70c64d1985ce65e56887138cf9a9a0aef
36,587
def find_ops(optype): """Find ops of a given type in graphdef or a graph. Args: optype: operation type (e.g. Conv2D) Returns: List of operations. """ gd = tf.get_default_graph() return [var for var in gd.get_operations() if var.type == optype]
03d1902adc0872170b618257da488c4ec05d276d
36,588
import os import sys def prompt_and_delete(path, no_input=False): """ Ask user if it's okay to delete the previously-downloaded file/directory. If yes, delete it. If no, checks to see if the old version should be reused. If yes, it's reused; otherwise, Cookiecutter exits. :param path: Previously...
35168c1d5483dfce2c4ba75bcac13e21b107ea0a
36,589
def continuous_ob(orderbooks): """ Creates a continuous orderbook timeseries data, for all orderbooks included as input. i.e. all timestamps that one orderbook has and the other dont, in the latter repeates the information of the former, with this, the output will deliver two historical orderbooks with ...
03a5124a58f51625b1a63535f8b7ca3d06058aa7
36,590
from util import PriorityQueue # i use PriorityQueue to store the frontier def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" frontier = PriorityQueue() # initialize frontier explored = s...
99ff121f4415f7e730963b73ee5269f310f8ce4d
36,591
import subprocess as sp import numpy as np def ffmpeg_decode(file_name, sr, mono=True): """Reads an audio file and returns its data. If `mono` is set to true, the returned audio data are monophonic. :param file_name: The file name of the audio file. :type file_name: str :param sr: The sample rate...
9098dc43e5bb340028a25d1b7dac1d1ad0b3bba8
36,592
def split_irregular_date_list(date_list): """ Takes a list of dates and groups it into blocks of continuous dates. It returns the begin and end of those blocks eg. A list with continuous dates from januari to march and september to october will be split into two lists Parameters ---------- ...
d246e25dacb4d1c7e60f40cbafb653a90d4556d3
36,593
import tqdm import torch def validate(args, fid_stat, gen_net: nn.Module, writer_dict=None): """ Compute both IS and FID (torch). :param args: :param fid_stat: :param gen_net: :param writer_dict: :return: """ # eval mode gen_net = gen_net.eval() eval_iter = args.num_eval_i...
ceadaca144a937eadf7b47fd69ae9b1e65700c14
36,594
def transform_observation(attribute, data): """ place to hook any transforms on te data """ output = data if (attribute == 'observation_time'): output = data[16:] return output
875d35a6c66cf57fe7ac4995f913b8dbe70e63f3
36,595
import json def batch_handler(repo, request): """Handle batch requests.""" req = {} try: req = json.loads(request) except json.JSONDecodeError: return create_response(status_code=400) operation = req['operation'] objects = req['objects'] res_objects = [] for obj in ob...
5a159645edcda539f3a56f53ffb5f3273b7cea49
36,596
def cos_angular_separation_tf(y_true, y_pred): """ Compute the angular separation in radians between two pointing direction given with lat-long Parameters ---------- lat1: 1d `numpy.ndarray` , latitude of the first pointing direction long1: 1d `numpy.ndarray` longitude of the first pointing ...
2ff53483b94f07d7c34e096bf5c2757813aa152a
36,597
def all_stocks(): """ #查询当前所有正常上市交易的股票列表 :return: """ data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date') # d = data["symbol"].values # random.shuffle(d) return data["symbol"].values
0f8ef4b09ea908b0012b6605feaf9c97287e069c
36,598
def get_dependent_databases(demand_dict): """Demand can be activitiy ids or tuple keys.""" db_labels = [ x[0] if isinstance(x, tuple) else get_activity(x)["database"] for x in demand_dict ] return set.union(*[Database(label).find_graph_dependents() for label in db_labels])
37edfaa699bc2d1deefd93dc90961ac76b0470d5
36,599