content
stringlengths
22
815k
id
int64
0
4.91M
def get_chunks(array, chunk_size, mask): """ Get an iterator of chunks of data from array Parameters ---------- array: np.ndarray array to chunck or to rebuild chunk_size: int mask: np.ndarray Returns ------- iterator<ndarray> """ shape = array.shape for sl...
40,400
def quick_sort(seq, start, end): """quick sort with median of left, middle, right as pivot element""" if end - start >= 2: pivot_index = pivot_median(seq, start, end) k1, k2 = partition_three_way(seq, start, end, seq[pivot_index]) quick_sort(seq, start, k1) quick_sort(seq, k2, e...
40,401
def LFSR(m: int) -> Iterator[int]: """LFSR generator of the given size https://en.wikipedia.org/wiki/Linear-feedback_shift_register """ n: int = m.bit_length() - 1 # Set initial state to {1 0 0 ... 0} state: List[int] = [0] * n state[0] = 1 feedback: int = 0 poly: List[int] = polys[n...
40,402
def autodetect_camera() -> str: """Auto-detect camera using gphoto2. Returns: string returned from gphoto2. """ _logger.debug('Auto detecting camera.') result = execute('gphoto2 --auto-detect') if result.returncode: raise ValueError(result.stderr) return result.stdout.dec...
40,403
def info(token, customerid=None): """ Returns the info for your account :type token: string :param token: Your NodePing API token :type customerid: string :param customerid: Optional subaccount ID for your account :return: Return contents from the NodePing query :rtype: dict """ ur...
40,404
def overlay(*fields: SampledField or Tensor) -> Tensor: """ Specify that multiple fields should be drawn on top of one another in the same figure. The fields will be plotted in the order they are given, i.e. the last field on top. ```python vis.plot(vis.overlay(heatmap, points, velocity)) ``` ...
40,405
def load_identifier(value): """load identifier""" if value == "y": return True return False
40,406
def IKinSpaceConstrained(screw_list, ee_home, ee_goal, theta_list, position_tolerance, rotation_tolerance, joint_mins, joint_maxs, max_iterations): """ Calculates IK to a certain goal within joint rotation constraints Args: screw_list: screw list ee_home: home end effector position ...
40,407
def add_hidden_range(*args): """ add_hidden_range(ea1, ea2, description, header, footer, color) -> bool Mark a range of addresses as hidden. The range will be created in the invisible state with the default color @param ea1: linear address of start of the address range (C++: ea_t) @param ea2: linear ad...
40,408
def _fetch_certs(request, certs_url): """Fetches certificates. Google-style cerificate endpoints return JSON in the format of ``{'key id': 'x509 certificate'}``. Args: request (google.auth.transport.Request): The object used to make HTTP requests. certs_url (str): ...
40,409
def prose_print(prose: str, width: int): """ Prints string as separate paragraphs with appropriate line breaks at specified line lengths Args: prose (str): string to print as prose width (int): width of the lines before a new line """ for paragraph in prose.split("\n"): for l...
40,410
def get_mock_personalization_dict(): """Get a dict of personalization mock.""" mock_pers = dict() mock_pers['to_list'] = [To("test1@example.com", "Example User"), To("test2@example.com", "Example User")] mo...
40,411
def load_python_bindings(python_input): """ Custom key bindings. """ bindings = KeyBindings() sidebar_visible = Condition(lambda: python_input.show_sidebar) handle = bindings.add @handle("c-l") def _(event): """ Clear whole screen and render again -- also when the sideb...
40,412
def test_get_dictionary_by_word_len_with_non_existing_data_path(): """ Case: test get dictionary by word len with non-existing data path. Expect: no such file or directory error message. """ data_reader = DataReader(data_path='') with pytest.raises(FileNotFoundError): data_reader.get_dic...
40,413
def batch_retrieve_pipeline_s3(pipeline_upload): """ Data is returned in the form (chunk_object, file_data). """ study = Study.objects.get(id = pipeline_upload.study_id) return pipeline_upload, s3_retrieve(pipeline_upload.s3_path, study.object_id, ...
40,414
def indent(instr, nspaces=4, ntabs=0, flatten=False): """Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number...
40,415
def gat(gw, feature, hidden_size, activation, name, num_heads=8, feat_drop=0.6, attn_drop=0.6, is_test=False): """Implementation of graph attention networks (GAT) This is an implementation of the paper GRAPH ATTENTION NETWORKS (https://arxiv.o...
40,416
def _rotation_box2d_jit_(corners, angle, rot_mat_T): """Rotate 2D boxes. Args: corners (np.ndarray): Corners of boxes. angle (float): Rotation angle. rot_mat_T (np.ndarray): Transposed rotation matrix. """ rot_sin = np.sin(angle) rot_cos = np.cos(angle) rot_mat_T[0, 0] =...
40,417
def _number(string): """ Extracts an int from a string. Returns a 0 if None or an empty string was passed. """ if not string: return 0 else: try: return int(string) except ValueError: return float(string)
40,418
def get_email(sciper): """ Return email of user """ attribute = 'mail' response = LDAP_search( pattern_search='(uniqueIdentifier={})'.format(sciper), attribute=attribute ) try: email = get_attribute(response, attribute) except Exception: raise EpflLdapExce...
40,419
def test_move_interactive_somefiles(): """Tests interactive UI allows not renaming some files Rename and move first file, don't rename second file (so no move), and rename but do not move last file (Input is: y/y, n, y/n) """ conf = """ {"move_files_destination": "test", "batch": false} ...
40,420
def convert_size(size): """ Size should be in bytes. Return a tuple (float_or_int_val, str_unit) """ if size == 0: return (0, "B") KILOBYTE = 1024 size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size, KILOBYTE))) p = math.pow(KILOBYTE, i)...
40,421
def _backward(gamma, mask): """Backward recurrence of the linear chain crf.""" gamma = K.cast(gamma, 'int32') # (B, T, N) def _backward_step(gamma_t, states): # print('len(states)=', len(states)) # print(type(states)) # y_tm1 = K.squeeze(states[0], 0) y_tm1 = states[0] ...
40,422
def shell_reload(args): """ Update article infos of thread """ try: threads[args.id].article_infos.load() except IndexError: raise Exception("No such thread.")
40,423
def test_service_cache_make_job(svc_client_cache): """Test service cache jobs.""" client, _, cache = svc_client_cache user = cache.ensure_user({"user_id": "testuser"}) job_data = { "job_id": uuid.uuid4().hex, } job = cache.make_job(user, job_data=job_data) assert job assert j...
40,424
def t3err(viserr, N=7): """ provided visibilities, this put these into triple product""" amparray = populate_symmamparray(viserr, N=N) t3viserr = np.zeros(int(comb(N,3))) nn=0 for kk in range(N-2): for ii in range(N-kk-2): for jj in range(N-kk-ii-2): t3viserr[nn+j...
40,425
def add_standard_args( profile: Profile, command: typing.List[str], siteIds: typing.List[str], mqtt_host: str = "localhost", mqtt_port: int = 1883, mqtt_username: str = "", mqtt_password: str = "", ): """Add typical MQTT arguments to a command.""" command.append("--debug") comma...
40,426
def cli_create_aws_backingstore(mcg_obj, cld_mgr, backingstore_name, uls_name, region): """ Create a new backingstore with aws underlying storage using noobaa cli command Args: mcg_obj (MCG): Used for execution for the NooBaa CLI command cld_mgr (CloudManager): holds secret for backingstore...
40,427
def test_single_process_subwf_subwf_inline_step() -> None: """Test --single-process on an inline sub-sub-workflow step.""" err_code, stdout, stderr = get_main_output( [ "--single-process", "step1/stepX/stepY", get_data("tests/subgraph/count-lines17-wf.cwl.json"), ...
40,428
def lr_result_plot( adata: AnnData, use_lr: Optional["str"] = None, use_result: Optional["str"] = "lr_sig_scores", # plotting param title: Optional["str"] = None, figsize: Optional[Tuple[float, float]] = None, cmap: Optional[str] = "Spectral_r", ax: Optional[matplotlib.axes._subplots.Axe...
40,429
def compute_average_ml_vae(z0_mean: torch.Tensor, z0_var: torch.Tensor, z1_mean: torch.Tensor, z1_var: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Compute the product of the encoder distributions. - Ada-ML-VAE Averaging function (✓) Visual inspection against reference implementation: ...
40,430
def generate_diagram_from_dag(dag: DAG, diagram_file: Union[str, bytes, int]): """ Auto-generates a diagrams file from a given dag. :param dag: The airflow dag to generate the diagrams file from. :type dag: DAG :param diagram_file: The file to where the diagram code will be written. :type diagr...
40,431
def safe_sign_and_autofill_transaction( transaction: Transaction, wallet: Wallet, client: Client ) -> Transaction: """ Signs a transaction locally, without trusting external rippled nodes. Autofills relevant fields. Args: transaction: the transaction to be signed. wallet: the wallet...
40,432
def getMetricValue(glyph, attr): """ Get the metric value for an attribute. """ attr = getAngledAttrIfNecessary(glyph.font, attr) return getattr(glyph, attr)
40,433
def temporal_train_test_split( y: ACCEPTED_Y_TYPES, X: Optional[pd.DataFrame] = None, test_size: Optional[Union[int, float]] = None, train_size: Optional[Union[int, float]] = None, fh: Optional[FORECASTING_HORIZON_TYPES] = None, ) -> SPLIT_TYPE: """Split arrays or matrices into sequential train ...
40,434
def PrintBuildbotStepText(text, handle=None): """Prints out stage text to buildbot.""" text = ' '.join(text.split()) (handle or sys.stderr).write('\n@@@STEP_TEXT@%s@@@\n' % (text,))
40,435
def split_range_str(range_str): """ Split the range string to bytes, start and end. :param range_str: Range request string :return: tuple of (bytes, start, end) or None """ re_matcher = re.fullmatch(r'([a-z]+)=(\d+)?-(\d+)?', range_str) if not re_matcher or len(re_matcher.groups()) != 3: ...
40,436
def get_valid_extent(array: Union[np.ndarray, np.ma.masked_array]) -> tuple: """ Return (rowmin, rowmax, colmin, colmax), the first/last row/column of array with valid pixels """ if not array.dtype == 'bool': valid_mask = ~get_mask(array) else: valid_mask = array cols_nonzero = n...
40,437
def get_downloaded_dataset_ids(preprocess=Preprocess.RAW): """Get all dataset ids in the corresponding preprocessed data folder""" dataset_filenames = os.listdir(get_folder(preprocess)) dataset_filenames.sort() return [int(filename.rstrip(OLD_PICKLE_EXT)) for filename in dataset_filenames]
40,438
def epsmu2nz(eps, mu):#{{{ """ Accepts permittivity and permeability, returns effective index of refraction and impedance""" N = np.sqrt(eps*mu) N *= np.sign(N.imag) Z = np.sqrt(mu / eps) return N, Z
40,439
def tokenize_numbers(text_array: List[str]) -> List[str]: """ Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and dots with ' @.@ '. Args: text_array: An already tokenized text as list Returns: A list of strings with token...
40,440
def recursive_parse(node, parent_id): """ Function that recursively parses folders and lists <DL><p> """ # case where node is a folder if node.name == "dt": folder = parse_folder(node.contents[0], parent_id) recursive_parse(node.contents[2], folder.id) # case where node is a list...
40,441
def main( datapath, kwdpath, in_annot, note_types, batch, ): """ Select notes for an annotation batch, convert them to CoNLL format and save them in folders per annotator. The overview of the batch is saved as a pickled DataFrame. Parameters ---------- datapath: Path pat...
40,442
def test_from_str_raises_when_not_128_bits(api, valid_bytes_48): """ Assert that :func:`~ulid.api.from_str` raises a :class:`~ValueError` when given bytes that is not 128 bit in length. """ value = base32.encode(valid_bytes_48) with pytest.raises(ValueError) as ex: api.from_str(value) ...
40,443
def mask_to_bbox(mask): """ Convert mask to bounding box (x, y, w, h). Args: mask (np.ndarray): maks with with 0 and 255. Returns: List: [x, y, w, h] """ mask = mask.astype(np.uint8) contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) x = 0 y =...
40,444
def find_divisor(n, limit=1000000): """ Use sieve to find first prime divisor of given number :param n: number :param limit: sieve limit :return: prime divisor if exists in sieve limit """ primes = get_primes(limit) for prime in primes: if n % prime == 0: return prime...
40,445
def sort_all(batch, lens): """ Sort all fields by descending order of lens, and return the original indices. """ if batch == [[]]: return [[]], [] unsorted_all = [lens] + [range(len(lens))] + list(batch) sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=True))] return so...
40,446
def plot_G(G): """The function draws a graph object Args: G ([graph]): A networkX Graph object """ counts = [G.edges[edge]["count"] for edge in G.edges] pos = nx.spring_layout(G) color_map = [] for node in G: if G.degree(node) >= 10: color_map.append...
40,447
def teardown_paste_factories(): """Reverse the effect of setup_paste_factories().""" global app_factory, filter_factory del app_factory del filter_factory
40,448
def bh(p, fdr): """ From vector of p-values and desired false positive rate, returns significant p-values with Benjamini-Hochberg correction """ p_orders = np.argsort(p) discoveries = [] m = float(len(p_orders)) for k, s in enumerate(p_orders): if p[s] <= (k+1) / m * fdr: ...
40,449
def cursor_column(num: int = 0) -> None: """Moves the cursor to the `num`-th character of the current line. Args: num: The new cursor position. Note: This does not flush the terminal for performance reasons. You can do it manually with `sys.stdout.flush()`. """ terminal.wr...
40,450
def test_globally_enabled(): """ Configuration file in this format: PermitRootLogin yes # explicit """ config = OpenSshConfig( permit_root_login=[ OpenSshPermitRootLogin( value='yes', in_match=None) ], ) assert not semantics_chang...
40,451
def runner(fun, *args): """ Generic asyncio.run() equivalent for Python >= 3.5 """ if sys.version_info >= (3, 7): if os.name == "nt" and sys.version_info < (3, 8): asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) return asyncio.run(fun(*args)) if o...
40,452
def test_log_prob(flow, x, n): """Test the log prob method""" with torch.no_grad(): log_prob = flow.log_prob(x) assert log_prob.shape == (n,)
40,453
async def run(): """ Where the bot gets started. If you wanted to create an aiohttp pool or other session for the bot to use, it's recommended that you create it here and pass it to the bot as a kwarg. """ config = config_load() bot = Bot( config=config, description=config['description']) try: await bot.s...
40,454
def guess_if_last(lmsg): """Guesses if message is the last one in a group""" msg_day = lmsg['datetime'].split('T')[0] msg_day = datetime.datetime.strptime(msg_day, '%Y-%m-%d') check_day = datetime.datetime.today() - datetime.timedelta(days=1) if msg_day >= check_day: return True return F...
40,455
def refine_by_split(featIds, n, m, topo_rules, grid_layer, progress_bar = None, labelIter = None ) : """ Description ---------- Split input_features in grid_layer and check their topology Parameters ---------- featIds : ids of features from grid_layer to be refined n : number of split f...
40,456
def container_export(name=None, path=None, version=None): """ export the 3bot to image file, if not specified will be /tmp/3bot2.tar :param name: :param path: :return: """ docker = _containers.get(delete=True, name=name) docker.export(path=path, version=version)
40,457
def patch_swipe_ios_up(self, duration: int = 0): """ Swipe Up For IOS Mobile. :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: driver.swipe_ios_up() """ import time self.execute_script...
40,458
def read_custom_enzyme(infile): """ Create a list of custom RNase cleaving sites from an input file """ outlist = [] with open(infile.rstrip(), 'r') as handle: for line in handle: if '*' in line and line[0] != '#': outlist.append(line.rstrip()) return outlist
40,459
def all_features(movie_id): """Returns the concatenation of visual and audio features for a movie The numbers of frames are not egal for the visual and the audio feature. The overnumerous frame are deleted. """ T_v = all_visual_features(movie_id) T_a = all_audio_features(movie_id) min_ = mi...
40,460
def main_make_peaks(): """Run the main peak making from command line.""" args = parse_args_make_peaks(sys.argv[1:]) filename = args.filename z_scores, chrom = open_wig(filename) if args.method == "thresh": print(f"Using the thresholding method to find peaks for {filename}") peaks = t...
40,461
def test_list_events_filter_by_date(api_client, hobby_with_events, hobby_with_events2, frozen_date): """ HobbyEvents should be filterable by start date """ # initialize fixture data to expected values set_event_dates_week_apart(hobby_with_events.events.all(), frozen_date) set_event_dates_week_apart(hobb...
40,462
def main(): """Run the script""" setLogLevel('info') opt1 = sys.argv[1] if len(sys.argv) > 1 else '--flood' opt2 = sys.argv[2] if len(sys.argv) > 2 else '--udp' itfs = sys.argv[3:] if len(sys.argv) > 3 else [] n = Net(opt1, opt2, itfs) try: n.run() except KeyboardInterrupt: ...
40,463
def datetime_range(start, end, delta={'days': 1}): """ Build a generator with dates within a range of datetime objects """ current = start if not isinstance(delta, (timedelta, relativedelta)): delta = relativedelta(**delta) while current < end: yield current current += d...
40,464
def resnet34(pretrained=False, shift='TSM',num_segments = 8, flow_estimation=0,**kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if (shift =='TSM'): model = ResNet(BasicBlock, BasicBlock, [3, 4, 6, 3],num_segments=n...
40,465
def normalize_data_v3(data, cal_zero_points=np.arange(-4, -2, 1), cal_one_points=np.arange(-2, 0, 1), **kw): """ Normalizes data according to calibration points Inputs: data (numpy array) : 1D dataset that has to be normalized cal_zero_points (range) : range specifying ...
40,466
def read(path, encoding="utf-8"): """Read string from text file. """ with open(path, "rb") as f: return f.read().decode(encoding)
40,467
def min_equals_max(min, max): """ Return True if minimium value equals maximum value Return False if not, or if maximum or minimum value is not defined """ return min is not None and max is not None and min == max
40,468
def loadDataSet(fileName): """ 加载数据 解析以tab键分隔的文件中的浮点数 Returns: dataMat : feature 对应的数据集 labelMat : feature 对应的分类标签,即类别标签 """ # 获取样本特征的总数,不算最后的目标变量 numFeat = len(open(fileName).readline().split('\t')) - 1 dataMat = [] labelMat = [] fr = open(fileName) for line...
40,469
def subscription_check(): """Automatically depreciate assets as per their depreciation rate""" subscriptions = Subscription.objects.all() for subscription in subscriptions: subscription.check_status()
40,470
def infer_app_url(headers: dict, register_path: str) -> str: """ ref: github.com/aws/chalice#485 :return: The Chalice Application URL """ host: str = headers["host"] scheme: str = headers.get("x-forwarded-proto", "http") app_url: str = f"{scheme}://{host}{register_path}" return app_url
40,471
def test_check_pixel_in_tpf(): """testing check_pixel_in_tpf() method of TpfData""" campaign = 92 channel = 31 pix_y = 670 pix_x = 883 epic_id = 200071074 tpf_data = tpfdata.TpfData(epic_id=epic_id, campaign=campaign) assert tpf_data.check_pixel_in_tpf(column=pix_y, row=pix_x) is True ...
40,472
def get_index_where_most_spikes_in_unit_list(unit_list): """Returns the position in the list of units that has the most spikes. :param unit_list: list of unit dictionaries :return: index :rtype: int """ return np.argmax(Recordings.count_spikes_in_unit_list(unit_list))
40,473
def curate_bids_dir(fw, project_id, session_id=None, reset=False, template_file=None, session_only=False): """ fw: Flywheel client project_id: project id of project to curate session_id: The optional session id to curate reset: Whether or not to reset bids info before curation template_file: Th...
40,474
def test_load_or_create_experiment_different_sample_name(empty_temp_db): """ Test that an experiment is created for the case when the experiment name is the same, but the sample name is different """ exp = new_experiment("experiment_name", "sample_name_1") exp_2 = load_or_create_experiment("expe...
40,475
def ocr_boxes( img, boxes, halve=False, resize=False, blur=True, sharpen=False, erode=False, dilate=False, lang='eng', config=None): """ Detect strings in multiple related boxes and concatenate the results. Parameters ---------- halve : bool, optional ...
40,476
def multiply_inv_gaussians(mus, lambdas): """Multiplies a series of Gaussians that is given as a list of mean vectors and a list of precision matrices. mus: list of mean with shape [n, d] lambdas: list of precision matrices with shape [n, d, d] Returns the mean vector, covariance matrix, and precision m...
40,477
def mutationShuffle(individual, indpb): """ Inputs : Individual route Probability of mutation betwen (0,1) Outputs : Mutated individual according to the probability """ size = len(individual) for i in range(size): if random.random() < indpb: swap_indx = random.ra...
40,478
def best_shoot_angle(agent_coord: tuple, opponents: list): """ Tries to shoot, if it fail, kicks to goal randomly """ # Get best shoot angle: best_angles = [] player_coord = np.array(agent_coord) goal_limits = [np.array([0.9, -0.2]), np.array([0.9, 0]), np.array([0.9, 0.2])] f...
40,479
def adjust(*args, stdin=None): """run 'adjust' with the current directory set to the dir where this module is found. Return a tuple (exitcode, parsed_stdout), the second item will be None if stdout was empty. An exception is raised if the process cannot be run or parsing stdout as json fails. A non-zero exit co...
40,480
def read_STAR_Logfinalout(Log_final_out): """ Log_final_out -- Folder or Log.final.out produced by STAR """ if os.path.isdir(Log_final_out): Log_final_out = Log_final_out.rstrip('/') dirfiles = os.listdir(Log_final_out) if 'Log.final.out' in dirfiles: Log_fi...
40,481
def _parse_line(lineno: int, line: str) -> Optional[UciLine]: # pylint: disable=unsubscriptable-object """Parse a line, raising UciParseError if it is not valid.""" match = _LINE_REGEX.match(line) if not match: raise UciParseError("Error on line %d: unrecognized line type" % lineno) if match[4]...
40,482
def login(request, template_name="lfs/checkout/login.html"): """Displays a form to login or register/login the user within the check out process. The form's post request goes to lfs.customer.views.login where all the logic happens - see there for more. """ # If the user is already authenticate ...
40,483
def _is_valid_concrete_plugin_class(attr): """ :type attr: Any :rtype: bool """ return ( inspect.isclass(attr) and issubclass(attr, BasePlugin) and # Heuristic to determine abstract classes not isinstance(attr.secret_type, abstractproperty) )
40,484
def connect(production=False): """Connect to MTurk""" # Load API keys reseval.load.api_keys() # Connect to MTurk return boto3.Session( aws_access_key_id=os.environ['AWSAccessKeyId'], aws_secret_access_key=os.environ['AWSSecretKey'] ).client( 'mturk', region_name=...
40,485
def arrQuartiles(arr, arrMap=None, method=1, key=None, median=None): """ Find quartiles. Also supports dicts. This function know about this quartile-methods: 1. Method by Moore and McCabe's, also used in TI-85 calculator. 2. Classical method, also known as "Tukey's hinges". In common cases it ...
40,486
def check_response_status_code(url, response, print_format): """ check and print response status of an input url. Args: url (str) : url text. response (list) : request response from the url request. print_format (str) : format to print the logs according to. """ ...
40,487
def test_wild070_wild070_v1_xml(mode, save_output, output_format): """ Basic test of notQName=##definedSibling notQName=##definedSibling in a sequence content model """ assert_bindings( schema="saxonData/Wild/wild070.xsd", instance="saxonData/Wild/wild070.v1.xml", class_name=...
40,488
def make_state_manager(config): """ Parameters ---------- config : dict Parameters for this StateManager. Returns ------- state_manager : StateManager The StateManager to be used by the Controller. """ manager_dict = { "hierarchical": HierarchicalStateManager...
40,489
def get_books_information(url: str, headers: dict = None) -> list: """ Create list that contains dicts of cleaned data from google book API. Parameters ---------- url: str link to resources (default: link to volumes with q=war, target of recrutment task) headers: dict dict ...
40,490
def get_maintenance_window_execution_task(WindowExecutionId=None, TaskId=None): """ Retrieves the details about a specific task executed as part of a Maintenance Window execution. See also: AWS API Documentation :example: response = client.get_maintenance_window_execution_task( WindowE...
40,491
def test_jsonrpc_client_errors(httpserver, response): """ unit test for JSONRPC client code. uses pytest-localserver plugin """ client = JSONRPC(httpserver.url) httpserver.serve_content("invalid-json") with pytest.raises(InvalidResponseError) as exc: client.call('foo') assert st...
40,492
def get_agents() -> Dict[str, Type[Agent]]: """Returns dict of agents. Returns: Dictionary mapping agent entrypoints name to Agent instances. """ agents = {} for entry_point in pkg_resources.iter_entry_points("agents"): agents[entry_point.name] = entry_point.load() return agents
40,493
def rewrite_schemadef(document: MutableMapping[str, Any]) -> Set[str]: """Dump the schemadefs to their own file.""" for entry in document["types"]: if "$import" in entry: rewrite_import(entry) elif "name" in entry and "/" in entry["name"]: entry_file, entry["name"] = entr...
40,494
def decor(decoration, reverse=False): """ Return given decoration part. :param decoration: decoration's name :type decoration:str :param reverse: true if second tail of decoration wanted :type reverse:bool :return decor's tail """ if isinstance(decoration, str) is False: ra...
40,495
def group_data(data, degree=3, hash=hash): """ numpy.array -> numpy.array Groups all columns of data into all combinations of triples """ new_data = [] m,n = data.shape for indicies in combinations(range(n), degree): if 5 in indicies and 7 in indicies: print "feature Xd" elif 2 ...
40,496
def get_dataset(dataset_name: str, *args, **kwargs): """Get the Dataset instancing lambda from the dictionary and return its evaluation. This way, a Dataset object is only instanced when this function is evaluated. Arguments: dataset_name: The name of the Dataset to be instanced. Must b...
40,497
def _numeric_handler_factory(charset, transition, assertion, illegal_before_underscore, parse_func, illegal_at_end=(None,), ion_type=None, append_first_if_not=None, first_char=None): """Generates a handler co-routine which tokenizes a numeric component (a token or sub-token). Args:...
40,498
def unsafe_content(s): """Take the string returned by safe_content() and recreate the original string.""" # don't have to "unescape" XML entities (parser does it for us) # unwrap python strings from unicode wrapper if s[:2]==unichr(187)*2 and s[-2:]==unichr(171)*2: s = s[2:-2].encode('us-as...
40,499