content
stringlengths
22
815k
id
int64
0
4.91M
def load_data_test(test_path, diagnoses_list, baseline=True, multi_cohort=False): """ Load data not managed by split_manager. Args: test_path (str): path to the test TSV files / split directory / TSV file for multi-cohort diagnoses_list (List[str]): list of the diagnoses wanted in case of s...
5,333,600
def pratn_writer(clf, y_true, y_prob, eval_folder, i=''): """ This function will produce a plot of precision & recall vs. percent population given a classifier's name or the object itself, true labels and predicted scores for each fold, and a folder to save it in. Can be used stand-alone. Support...
5,333,601
def render_thread(gui): """ This thread runs the gui.render function thirty times per second and stops the gui if any errors occur. """ while gui: sleep(SLEEP_TIME) try: # Update the window size gui.screen_size = gui.screen.getmaxyx() gui.screen_he...
5,333,602
def load_augmentations_config( placeholder_params: dict, path_to_config: str = "configs/augmentations.json" ) -> dict: """Load the json config with params of all transforms Args: placeholder_params (dict): dict with values of placeholders path_to_config (str): path to the json config file ...
5,333,603
def simplify_mask(mask, r_ids, r_p_zip, replace=True): """Simplify the mask by replacing all `region_ids` with their `root_parent_id` The `region_ids` and `parent_ids` are paired from which a tree is inferred. The root of this tree is value `0`. `region_ids` that have a corresponding `parent_id` of 0 ...
5,333,604
def _write_single_annotation(doc: str, annotation: str, values, append: bool, root: Path, allow_newlines: bool = False): """Write an annotation to a file.""" is_span = not split_annotation(annotation)[1] if is_span: # Make sure that spans are sorted assert all(values[i] <= values[i + 1] for...
5,333,605
def getStops(ll): """ getStops Returns a list of stops based off of a lat long pair :param: ll { lat : float, lng : float } :return: list """ if not ll: return None url = "%sstops?appID=%s&ll=%s,%s" % (BASE_URI, APP_ID, ll['lat'], ll['lng']) try: f = u...
5,333,606
def rws(log_joint, observed, latent, axis=None): """ Implements Reweighted Wake-sleep from (Bornschein, 2015). This works for both continuous and discrete latent `StochasticTensor` s. :param log_joint: A function that accepts a dictionary argument of ``(string, Tensor)`` pairs, which are mappin...
5,333,607
def fit_svr(X, y, kernel: str = 'rbf') -> LinearSVR: """ Fit support vector regression for the given input X and expected labes y. :param X: Feature data :param y: Labels that should be correctly computed :param kernel: type of kernel used by the SVR {‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed...
5,333,608
def test_g_month_day_min_inclusive005_1247_g_month_day_min_inclusive005_1247_v(mode, save_output, output_format): """ TEST :Facet Schemas for string : (facet=minInclusive and value=- -01-01 and facet=maxExclusive and value=- -10-01) and document value=- -03-15 """ assert_bindings( schema...
5,333,609
def process_get_namespaces_from_accounts( status: int, json: list, network_type: models.NetworkType, ) -> typing.Sequence[models.NamespaceInfo]: """ Process the "/account/namespaces" HTTP response. :param status: Status code for HTTP response. :param json: JSON data for response message. ...
5,333,610
def plot_time_shifts(filename, data, greens, component, misfit, stations, origin, source, backend='matplotlib'): """ For a given component, creates a "spider plot" showing how time shifts vary geographically """ if backend.lower()=='gmt': raise NotImplementedError # prepare synthetics...
5,333,611
def _initialize_pydataverse(DATAVERSE_URL: Optional[str], API_TOKEN: Optional[str]): """Sets up a pyDataverse API for upload.""" # Get environment variables if DATAVERSE_URL is None: try: DATAVERSE_URL = os.environ["DATAVERSE_URL"] except KeyError: raise MissingURLE...
5,333,612
def _hexsplit(string): """ Split a hex string into 8-bit/2-hex-character groupings separated by spaces""" return ' '.join([string[i:i+2] for i in range(0, len(string), 2)])
5,333,613
def get_analysis_id(analysis_id): """ Get the new analysis id :param analysis_id: analysis_index DataFrame :return: new analysis_id """ if analysis_id.size == 0: analysis_id = 0 else: analysis_id = np.nanmax(analysis_id.values) + 1 return int(analysis_id)
5,333,614
def get_station_pqr(station_name: str, rcu_mode: Union[str, int], db): """ Get PQR coordinates for the relevant subset of antennas in a station. Args: station_name: Station name, e.g. 'DE603LBA' or 'DE603' rcu_mode: RCU mode (0 - 6, can be string) db: instance of LofarAntennaDatabas...
5,333,615
def hello_world(cities: List[str] = ["Berlin", "Paris"]) -> bool: """ Hello world function. Arguments: - cities: List of cities in which 'hello world' is posted. Return: - success: Whether or not function completed successfully. """ try: [print("Hello {}!".format(c)) for c in ...
5,333,616
def init_db_command(): """Clear the existing data and create new tables.""" init_db() print("Database initalized") click.echo('Initialized the database.')
5,333,617
def parse_dir(directory, default_settings, oldest_revision, newest_revision, rep): """Parses bench data from files like bench_r<revision>_<scalar>. (str, {str, str}, Number, Number) -> {int:[BenchDataPoints]}""" revision_data_points = {} # {revision : [BenchDataPoints]} file_list = os...
5,333,618
def random_samples(traj_obs, expert, num_sample): """Randomly sample a subset of states to collect expert feedback. Args: traj_obs: observations from a list of trajectories. expert: an expert policy. num_sample: the number of samples to collect. Returns: new expert data. """ expert_data = [...
5,333,619
def test_normalization_of_images(test_link): """ Test if normalize_pages returns 0 for None, or pages number otherwise. """ assert test_link.pages == 15 assert Reddit('http://www.reddit.com/', None).pages == 0
5,333,620
def makeFolder(path): """Build a folder. Args: path (str): Folder path. Returns: bool: Creation status. """ if(not os.path.isdir(path)): try: os.makedirs(path) except OSError as error: print("Directory %s can't be created (%s)" % (path, error...
5,333,621
def get_p2_vector(img): """ Returns a p2 vector. We calculate the p2 vector by taking the radial mean of the autocorrelation of the input image. """ radvars = [] dimX = img.shape[0] dimY = img.shape[1] fftimage = np.fft.fft2(img) final_image = np.fft.ifft2(fftimage*np.conj(fftim...
5,333,622
def start_replica_cmd(builddir, replica_id): """ Return a command that starts an skvbc replica when passed to subprocess.Popen. Note each arguments is an element in a list. """ statusTimerMilli = "500" viewChangeTimeoutMilli = "10000" path = os.path.join(builddir, "tests", "simpleKVBC",...
5,333,623
def multiplex(n, q, **kwargs): """ Convert one queue into several equivalent Queues >>> q1, q2, q3 = multiplex(3, in_q) """ out_queues = [Queue(**kwargs) for i in range(n)] def f(): while True: x = q.get() for out_q in out_queues: out_q.put(x) t...
5,333,624
def sse_md5(params, **kwargs): """ S3 server-side encryption requires the encryption key to be sent to the server base64 encoded, as well as a base64-encoded MD5 hash of the encryption key. This handler does both if the MD5 has not been set by the caller. """ _sse_md5(params, 'SSECustomer')
5,333,625
def identity_of(lines): """ extract identity of each line """ rex = re.compile("^#[0-9]+") for line in lines: match = rex.search(line) if match is None: yield None else: yield line[match.start():match.end()]
5,333,626
def stack(arrays, axis=0): """ Join a sequence of arrays along a new axis. The `axis` parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension. .. versionadded:: 1.1...
5,333,627
def get_runs(runs, selected_runs, cmdline): """Selects which run(s) to execute based on parts of the command-line. Will return an iterable of run numbers. Might also fail loudly or exit after printing the original command-line. """ name_map = dict((r['id'], i) for i, r in enumerate(runs) if 'id' in...
5,333,628
def declare_default_toolchain(): """The default ReasonML/BuckleScript toolchain. This toolchain will register as `bs-platform` and will include the `nix` managed ReasonML tools (such as `refmt`) and the `bazel` compiled BuckleScript and patched Ocaml compilers. It defaults to: * `bs_stdlib = ...
5,333,629
def verifica_cc(numero): """verifica_cc(numero): int -> tuple Funcao que verifica o numero do cartao, indicando a categoria e a rede emissora""" numero_final = str(numero) if luhn_verifica(numero_final) == True: categor = categoria(numero_final) rede_cartao = valida_iin(numero_final) ...
5,333,630
def check_modified_file(filename, errors): """Check each modified file to make sure it adheres to the standards""" # skip code that isn't ours if filename.find("dependency") != -1 or "/eigen3/" in filename: return # don't check header guard in template headers if filename.find("templates") !...
5,333,631
def create_security_group(stack, name, rules=()): """Add EC2 Security Group Resource.""" ingress_rules = [] for rule in rules: ingress_rules.append( SecurityGroupRule( "{0}".format(rule['name']), CidrIp=rule['cidr'], FromPort=rule['from_por...
5,333,632
def features_targets_and_externals( df: pd.DataFrame, region_ordering: List[str], id_col: str, time_col: str, time_encoder: OneHotEncoder, weather: Weather_container, time_interval: str, latitude: str, longitude: str, ): """ Function that computes the node features (outflows)...
5,333,633
def main(argv=None): """ Execute the application CLI. Arguments are taken from sys.argv by default. """ args = _cmdline(argv) config.load(args.config) results = get_package_list(args.search_term) results = sorted(results, key=lambda a: sort_function(a[1]), reverse=True) results_normali...
5,333,634
def transform_child_joint_frame_to_parent_inertial_frame(child_body): """Return the homogeneous transform from the child joint frame to the parent inertial frame.""" parent_joint = child_body.parent_joint parent = child_body.parent_body if parent_joint is not None and parent.inertial is not None: ...
5,333,635
def delete_article_number_sequence( sequence_id: ArticleNumberSequenceID, ) -> None: """Delete the article number sequence.""" db.session.query(DbArticleNumberSequence) \ .filter_by(id=sequence_id) \ .delete() db.session.commit()
5,333,636
def team_to_repos(api, no_repos, organization): """Create a team_to_repos mapping for use in _add_repos_to_teams, anc create each team and repo. Return the team_to_repos mapping. """ num_teams = 10 # arrange team_names = ["team-{}".format(i) for i in range(num_teams)] repo_names = ["some-rep...
5,333,637
def test_min(hass): """Test the min filter.""" assert template.Template("{{ [1, 2, 3] | min }}", hass).async_render() == "1"
5,333,638
def box_minus(plus_transform: pin.SE3, minus_transform: pin.SE3) -> np.ndarray: """ Compute the box minus between two transforms: .. math:: T_1 \\boxminus T_2 = \\log(T_1 \\cdot T_2^{-1}) This operator allows us to think about orientation "differences" as similarly as possible to position...
5,333,639
def ipykernel(ctx, name=None, display_name=None): """Installs an IPyKernel for this project""" if not name: name = 'spines-dev' if not display_name: display_name = 'Spines Dev' log("Installing IPyKernel: %s (%s)" % (name, display_name)) ctx.run( 'python -m ipykernel install ...
5,333,640
def padandsplit(message): """ returns a two-dimensional array X[i][j] of 32-bit integers, where j ranges from 0 to 16. First pads the message to length in bytes is congruent to 56 (mod 64), by first adding a byte 0x80, and then padding with 0x00 bytes until the message length is congruent to 56 ...
5,333,641
def base_put(url_path, content): """ Do a PUT to the REST API """ response = requests.put(url=settings.URL_API + url_path, json=content) return response
5,333,642
def inverse_rotation(theta: float) -> np.ndarray: """ Compute inverse of the 2d rotation matrix that rotates a given vector by theta without use of numpy.linalg.inv and numpy.linalg.solve. Arguments: theta: rotation angle Return: Inverse of the rotation matrix """ rotation_matri...
5,333,643
def _config_validation_decorator(func): """A decorator used to easily run validations on configs loaded into dicts. Add this decorator to any method that returns the config as a dict. Raises: ValueError: If the configuration fails validation """ @functools.wraps(func) def validation_wr...
5,333,644
def image_transpose_exif(im): """ https://stackoverflow.com/questions/4228530/pil-thumbnail-is-rotating-my-image Apply Image.transpose to ensure 0th row of pixels is at the visual top of the image, and 0th column is the visual left-hand side. Return the original image if unable to determine the orie...
5,333,645
def GetFileList(folder, surfixs=".xls,.xlsx"): """ 遍历文件夹查找所有满足后缀的文件 """ surfix = surfixs.split(",") if type(folder) == str: folder = folder.decode('utf-8') p = os.path.abspath(folder) flist = [] if os.path.isdir(p): FindFileBySurfix(flist, p, surfix) else: r...
5,333,646
def generateHTML(fileName, styles): """We generate the HTML""" """and write the string into a file.""" code = markdown(getFC(fileName)) htmlName = fileName.split('.')[0] + '.html' htmlFile = open(htmlName, 'w') compCode = insertStyles(code, styles, fileName.split('.')[0]) htmlFile.write(comp...
5,333,647
def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs): """Return optimised pore diameter and it's COM.""" args = elements, coordinates if com is not None: pass else: com = center_of_mass(elements, coordinates) if bounds is None: pore_r = pore_diameter(...
5,333,648
async def test_create_contestants_csv_event_not_found( client: _TestClient, mocker: MockFixture, token: MockFixture, event: dict, new_contestant: dict, ) -> None: """Should return 404 Not found.""" EVENT_ID = "event_id_1" CONTESTANT_ID = "290e70d5-0933-4af0-bb53-1d705ba7eb95" mocker....
5,333,649
def test_update_bad_token(app, combatant): """Test user update API with bad token.""" client = app.test_client() response = client.put( '/api/combatant_update', data=json.dumps({'token': uuid4().hex}), content_type = 'application/json' ) assert response.status_code == 401
5,333,650
def example() -> None: """create example config files in ~/.aec/.""" config_dir = os.path.expanduser("~/.aec/") os.makedirs(config_dir, exist_ok=True) for r in resources.files("aec.config-example").iterdir(): copy(r, config_dir)
5,333,651
def animate_operators(operators, date): """Main.""" results = [] failures = [] length = len(operators) count = 1 for i in operators: try: i = i.encode('utf-8') except: i = unicode(i, 'utf-8') i = i.encode('utf-8') print(i, count, "/",...
5,333,652
def random_sampler(vocs, evaluate_f, executor=None, output_path=None, chunk_size=10, max_samples=100, verbose=None): """ Makes random samples based on vocs """ if verbose is not None: warnin...
5,333,653
def get_span_encoding(key, zero_span_rep=None): """ Input: document key Output: all possible span tuples and their encodings """ instance = reader.text_to_instance(combined_json[key]["sentences"]) instance.index_fields(model.vocab) generator = iterator(instances=[instance]) batch = next(...
5,333,654
def _check_component_dtypes(value_type): """Checks all components of the `value_type` to be either ints or floats.""" if not (type_analysis.is_structure_of_floats(value_type) or type_analysis.is_structure_of_integers(value_type)): raise TypeError('Component dtypes of `value_type` must all be integers ...
5,333,655
def add_stocks(letter, page, get_last_page=False): """ goes through each row in table and adds to df if it is a stock returns the appended df """ df = pd.DataFrame() res = req.get(BASE_LINK.format(letter, page)) soup = bs(res.content, 'lxml') table = soup.find('table', {'id': 'Companyli...
5,333,656
def available_parent_amount_rule(model, pr): """ Each parent has a limited resource budget; it cannot allocate more than that. :param ConcreteModel model: :param int pr: parent resource :return: boolean indicating whether pr is staying within budget """ if model.parent_possible_allocations[...
5,333,657
def extract_coords(filename): """Extract J2000 coordinates from filename or filepath Parameters ---------- filename : str name or path of file Returns ------- str J2000 coordinates """ # in case path is entered as argument filename = filename.split("/")[-1] if ...
5,333,658
def exponential(mantissa, base, power, left, right): """Return the exponential signal. The signal's value will be `mantissa * base ^ (power * time)`. Parameters: mantissa: The mantissa, i.e. the scale of the signal base: The exponential base power: The exponential power left: Left bound of...
5,333,659
def move_distribute_blocks( parent_folder, new_folders, blocks, relation_filepath, template_extension="xlsx" ): """Move and distribute equal number of blocks of files to a list of new folders (person names)""" distribution = np.random.permutation( np.tile( np.random.permutation(new_fold...
5,333,660
def get_features(features, featurestore=None, featuregroups_version_dict={}, join_key=None, online=False): """ Gets a list of features (columns) from the featurestore. If no featuregroup is specified it will query hopsworks metastore to find where the features are stored. It will try to construct the query ...
5,333,661
def get_flex_bounds(x, samples, nsig=1): """ Here, we wish to report the distribution of the subchunks 'sample' along with the value of the full sample 'x' So this function will return x, x_lower_bound, x_upper_bound, where the range of the lower and upper bound expresses the standard deviation ...
5,333,662
def make_intervention_frequencies_plot(medication_df, cols_to_plot, fig_filename=None): """ Given a bunch of binary cols_to_plot, plot the frequency with which they occur in the data overall and in disadvantaged racial/SES groups. Two plots: one of absolute risks, one of relative risks (relative to the ou...
5,333,663
def _parse_multi_header(headers): """ Parse out and return the data necessary for generating ZipkinAttrs. Returns a dict with the following keys: 'trace_id': str or None 'span_id': str or None 'parent_span_id': str or None 'sampled_str': ...
5,333,664
def get_tgimg(img): """ 处理提示图片,提取提示字符 :param img: 提示图片 :type img: :return: 返回原图描边,提示图片按顺序用不同颜色框,字符特征图片列表 :rtype: img 原图, out 特征图片列表(每个字), templets 角度变换后的图 """ imgBW = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) h, w = imgBW.shape _, imgBW = cv2.threshold(imgBW, 0, 255, ...
5,333,665
def brand_profitsharing_order_query(self, transaction_id, out_order_no, sub_mchid): """查询连锁品牌分账结果 :param transaction_id: 微信支付订单号,示例值:'4208450740201411110007820472' :param out_order_no: 商户分账单号,只能是数字、大小写字母_-|*@,示例值:'P20150806125346' :param sub_mchid: 子商户的商户号,由微信支付生成并下发。示例值:'1900000109' """ if sub_...
5,333,666
def get_controller_from_module(module, cname): """ Extract classes that inherit from BaseController """ if hasattr(module, '__controller__'): controller_classname = module.__controller__ else: controller_classname = cname[0].upper() + cname[1:].lower() + 'Controller' controller_c...
5,333,667
def exp(d: D) -> NumDict: """Compute the base-e exponential of d.""" return d.exp()
5,333,668
def test_init_invalid_q(): """Verify constructor invalid q """ # String not fully specified base_conversion = list(uut.properties.StrConv.values()) errmsg = r"^String literal initialization Q format must be fully constrained\.$" for nbit in tools.test_iterator(): s = random.randrange(2) ...
5,333,669
def Main(operation, args): """Supports 2 operations 1. Consulting the existing data (get) > get ["{address}"] 2. Inserting data about someone else (certify) > certify ["{address}","{hash}"] """ if len(args) == 0: Log('You need to provide at least 1 parameter - [address]')...
5,333,670
def get_latest_file_list_orig1(input_list, start_time, num_files): """ Return a list of file names, trying to get one from each index file in input_list. The starting time is start_time and the number of days to investigate is num_days. """ out = [] for rind in input_list: # Create time...
5,333,671
def get_ogheader(blob, url=None): """extract Open Graph markup into a dict The OG header section is delimited by a line of only `---`. Note that the page title is not provided as Open Graph metadata if the image metadata is not specified. """ found = False ogheader = dict() for line in...
5,333,672
def cleanup(): """Cleanup the oslo_messaging layer.""" global TRANSPORTS, NOTIFIERS NOTIFIERS = {} for url in TRANSPORTS: TRANSPORTS[url].cleanup() del TRANSPORTS[url]
5,333,673
def rm(user, host="submit-3.chtc.wisc.edu", keyfile=None, expr=None, verbose=False): """Remove condor jobs on a remote machine. Parameters ---------- user : str the remote machine user name host : str, optional the remote machine host keyfile : str, optional ...
5,333,674
def run_pool_exhaust_test(server_host_ip, server_port, num_runs, global_model_real): """ Run the workers loop to exhaust the gevent pool in a stress test. This involves running requesting the global model from the server for all but one worker 20 times. Since the server only allocates enough gevent ...
5,333,675
def check_key(k, expected_keys): """Used to check if k is an expected key (with some fudging for DACs at the moment)""" if k in expected_keys: return elif k[0:3] in ['DAC', 'ADC']: # TODO: This should be checked better return else: logger.warning(f'Unexpected key in logs: k = {k...
5,333,676
def variable_accessed(variable): """Notifies all tapes in the stack that a variable has been accessed. Args: variable: variable to be watched. """ strategy, context = ( distribution_strategy_context.get_strategy_and_replica_context()) if context: variables = [strategy.extended.value_container(v...
5,333,677
def list_ingredient(): """List all ingredients currently in the database""" ingredients = IngredientCollection() ingredients.load_all() return jsonify(ingredients=[x.to_dict() for x in ingredients.models])
5,333,678
def ParseSavedQueries(cnxn, post_data, project_service, prefix=''): """Parse form data for the Saved Queries part of an admin form.""" saved_queries = [] for i in xrange(1, MAX_QUERIES + 1): if ('%ssavedquery_name_%s' % (prefix, i)) not in post_data: continue # skip any entries that are blank or have n...
5,333,679
def label_anchors(anchors, anchor_is_untruncated, gt_classes, gt_bboxes, background_id, iou_low_threshold=0.41, iou_high_threshold=0.61): """ Get the labels of the anchors. Each anchor can be labeled as positive (1), negative (0) or ambiguous (-1). Truncated anchors are always labeled as ambiguous. """ n = anch...
5,333,680
def make_hash_md5(obj): """make_hash_md5 Args: obj (any): anything that can be hashed. Returns: hash (str): hash from object. """ hasher = hashlib.md5() hasher.update(repr(make_hashable(obj)).encode()) return hasher.hexdigest()
5,333,681
def fbx_data_bindpose_element(root, me_obj, me, scene_data, arm_obj=None, mat_world_arm=None, bones=[]): """ Helper, since bindpose are used by both meshes shape keys and armature bones... """ if arm_obj is None: arm_obj = me_obj # We assume bind pose for our bones are their "Editmode" pose....
5,333,682
def lambda_( db_path, table, columns, code, imports, dry_run, multi, output, output_type, drop, silent, ): """ Transform columns using Python code you supply. For example: \b $ sqlite-transform lambda my.db mytable mycolumn --code='"\\n".join(textwrap...
5,333,683
def partitioned_rml_estimator(y, sigma2i, iterations=50): """ Implementation of the robust maximum likelihood estimator. Parameters ---------- y : :py:class:`~numpy.ndarray`, (n_replicates, n_variants) The variant scores matrix sigma2i : :py:class:`~numpy.ndarray`, (n_replicates, n_vari...
5,333,684
def inv_kinema_cal_3(JOINT_ANGLE_OFFSET, L, H, position_to_move): """逆運動学を解析的に解く関数. 指先のなす角がηになるようなジョイント角度拘束条件を追加して逆運動学問題を解析的に解く 引数1:リンク長さの配列.nd.array(6).単位は[m] 引数2:リンク高さの配列.nd.array(1).単位は[m] 引数3:目標位置(直交座標系)行列.nd.array((3, 1)).単位は[m] 戻り値(成功したとき):ジョイント角度配列.nd.array((6)).単位は[°] 戻り値(失敗したとき):...
5,333,685
def create(path): """Crea un árbol de dominios a partir de un archivo y lo imprime. Permite al usuario decidir sobre el proceso de creación. Parameters: path (str): Path al archivo que contiene los dominios. """ global root if not root.is_leaf: opt = input("Ya existe un árbo...
5,333,686
def get_log_filename(log_directory, device_name, name_prefix=""): """Returns the full path of log filename using the information provided. Args: log_directory (path): to where the log file should be created. device_name (str): to use in the log filename name_prefix (str): string to prepend to the...
5,333,687
def getTime(dataPath, indatatype, grdROMS, grdMODEL, year, month, day, mytime, firstRun): """ Create a date object to keep track of Julian dates etc. Also create a reference date starting at 1948/01/01. Go here to check results:http://lena.gsfc.nasa.gov/lenaDEV/html/doy_conv.html """ if indataty...
5,333,688
def delete_voting(request, slug): """Delete voting view.""" if request.method == 'POST': poll = get_object_or_404(Poll, slug=slug) if poll.automated_poll and Bug.objects.filter(id=poll.bug.id): # This will trigger a cascade delete, removing also the poll. Bug.objects.fil...
5,333,689
def http_delete_request( portia_config: dict, endpoint: str, payload: dict=None, params: dict=None, optional_headers: dict=None ) -> object: """Makes an HTTP DELETE request. Arguments: portia_config {dict} -- Portia's configuration arguments endpoint {str} -- endpoint t...
5,333,690
def test_parse_annotations_in_all_sections(parse_numpy, docstring, name): """Assert annotations are parsed in all relevant sections. Parameters: parse_numpy: Fixture parser. docstring: Parametrized docstring. name: Parametrized name in annotation. """ docstring = docstring.forma...
5,333,691
def action_copy(sourcepaths, targetpaths): """Copy a file or directory.""" format = request.format # Copying a symlink/junction means copying the real file/directory. # It makes no sense if the symlink/junction is broken. if not os.path.exists(sourcepaths[0]): abort(404, "Source does not ex...
5,333,692
def http_basic_auth(func): """ Attempts to login user with u/p provided in HTTP_AUTHORIZATION header. If successful, returns the view, otherwise returns a 401. If PING_BASIC_AUTH is False, then just return the view function Modified code by: http://djangosnippets.org/users/bthomas/ fro...
5,333,693
def update_modules(to_build, cfg): """ Updates modules to be built with the passed-in config. Updating each individual module section will propogate the changes to STATUS as well (as the references are the same). Note that we have to apply overrides in a specific order - 1) reset the modules being built to the de...
5,333,694
def stats_to_df(stats_data): """ Transform Statistical API response into a pandas.DataFrame """ df_data = [] for single_data in stats_data['data']: df_entry = {} is_valid_entry = True df_entry['interval_from'] = parse_time( single_data['interval']['from']).date() ...
5,333,695
def make_risk_metrics( stocks, weights, start_date, end_date ): """ Parameters: stocks: List of tickers compatiable with the yfinance module weights: List of weights, probably going to be evenly distributed """ if mlfinlabExists: Var, VaR, CVaR, CD...
5,333,696
def decrypt(bin_k, bin_cipher): """decrypt w/ DES""" return Crypto.Cipher.DES.new(bin_k).decrypt(bin_cipher)
5,333,697
def send_shopfloor_activities_summary_report(): """ Similar to auto_email_report.send(), but renders the report in to a jinja template to allow for more flexibility """ # Get auto email report auto_email_report = frappe.get_doc("Auto Email Report", "Horizon Global (PTA): Shopfloor Activities Summary...
5,333,698
def mass_recorder(grams, item, sigfigs): """Record the mass of different items. Args: grams ([type]): [description] item ([type]): [description] sigfigs ([type]): [description] Raises: ValueError: [description] """ item_dict = {} if isinstance(grams, float) and ...
5,333,699