content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_url(query_str: str, base_url: str, page: int = 1) -> str: """Create query URL for Google CSE API search. Args: query_str: Search term to use. base_url: Site URL. page: Result page to start at. Returns: Completed URL. """ return ( _API_URL + "...
151c47a1680356a9c6744d774bbec70ba0d9cc3c
3,620,300
def build_full_traversal(): """ Builds a traversal spec that will recurse through all objects .. or at least I think it does. additions welcome. See com.vmware.apputils.vim25.ServiceUtil.buildFullTraversal in the java API. Extended by Sebastian Tello's examples from pysphere to reach networks a...
03f039945d4d5d34462e8f6dc9266a730300b837
3,620,301
def tonum(s): """Converts a string representation of a decimal, hexadecimal, or binary number to a number value or None.""" if type(s) in (int, float): return s if s is None: return 0 base = 10 if isinstance(s, str): if "x" in s: base = 16 elif "b" in s:...
4878a5619fcd96897f5bec6167bb8f0b4539588a
3,620,302
from pathlib import Path def mock_derived_metadata_derivation( path: Path, parameters: any_pb2.Any) -> symfs_pb2.Metadata: """Mock custom derived metadata function. The metadata this function generates will be simply a copy of the parameters, which is assumed to be everchanging.symfs.ext.TestMessage, with ...
9a2a3bd79765e2b8abdb0af15990a66234744ef3
3,620,303
import typing def has_permissions(*permissions: typing.Tuple[str]): """ Checks if the user has the permissions. """ def decorator(func: typing.Awaitable): func.has_permissions = permissions return func return decorator
faf5cdc4eb63bfb8925bed8fde7d7afbe29501a5
3,620,304
from typing import Optional from typing import Type from typing import MutableMapping from typing import Any def fromtree( tree: etree.Element, use_builtin_types: Optional[bool] = None, dict_type: Type[MutableMapping[str, Any]] = dict, ) -> Any: """Convert an XML tree to a plist structure. Args: ...
67861407353fbf745a547854ad76971a3ec217d3
3,620,305
def patch_with_user_globals(data, skip_noexist=True): """ Patch the paths.json data structure with the user's globals in place. :param data: the paths.json data structure :param skip_noexist: skip applying global data if it doesn't exist otherwise raise an error for a non-existant file :ret...
785bddc58f6bb2d0394e79b9a11cdbf2e90957fd
3,620,306
import sys def crop_frames(args, data): """ Indexing is done this way ################## # 1 # 2 # 3 # # 4 # 5 # 6 # ################# """ if args.num_features % (args.v_crop_scale * args.h_crop_scale) != 0: print("Incorrect Crop Scaling selected. Please ensure original d...
15f95c5840782e6eb0aebf3a95f2e11e77749fff
3,620,307
def getdeleted(ref): """ Return the deleted positions (p=0 or p=1) from a report file. """ return [int(i) for i in fopen(ref+'.rep')[7]]
72144fdd5f6ada178b303107c6c8d966aad28115
3,620,308
import os def recursive_glob(rootdir=".", suffix=""): """Performs recursive glob with given suffix and rootdir :param rootdir is the root directory :param suffix is the suffix to be searched """ return [ os.path.join(looproot, filename) for looproot, _, filenames in os.walk...
cb4eec634cee15fdd2109828f1ec5574f58614b9
3,620,309
def generate_permutations(ls): """ Question 16.3: Generate all permutations of a list """ if len(ls) <= 1: return [ls] result = [] for perm in generate_permutations(ls[1:]): for idx in xrange(len(ls)): result.append(perm[:idx] + ls[0:1] + perm[idx:]) return resu...
f0d622b599d8b79e4c290f00a807afb9ac32cf55
3,620,310
import glob import logging def get_filename(work_dir, product_id): """Retrieve the Landsat metadata filename to use The file may have issues, so call the fix function to remove those issues. """ try: parser = lambda x: 'old' not in x and not x.startswith('lnd') filename = filter(parse...
a6b04e6954671b9904541f79bffa3c807afbcf00
3,620,311
from typing import Callable from typing import Iterable from typing import Any async def async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities: Callable[[Iterable[Entity]], Any], discovery_info=None, ): """Set up the sensor platform""" return False
912aedbc1cc844a6b18c93c3e566324173a4ba10
3,620,312
def l2_regularization(W, reg_strength): """ Computes L2 regularization loss on weights and its gradient Arguments: W, np array - weights reg_strength - float value Returns: loss, single value - l2 regularization loss gradient, np.array same shape as W - gradient of weight by l2...
d43af7204a7de8d1b1d922d186a235e7889681dc
3,620,313
from china_stock_data_api import netease def financial_info(index): """ get the company financial info for index :param index: stock index :return: data frame containing financial data by season """ return netease.NeteaseStockInfo.latest(index)
14a1f85ea8ed70db11d25a0a7f5e93c991dc8969
3,620,314
import sys def handle_response(response, display=False): """ Dispatch response based on scripting response or event. """ def handle_script_response(response, display=False): if display: sys.stderr.write( u'Scripting request submitted with request id: {}\n'.form...
a254ffc5084d8b0d2eaef255bbd122a5a10ec8f2
3,620,315
import pathlib import glob def presto_fft(eventfile,segment_length,demod,PI1,PI2,t1,t2): """ Obtain the FFT files that were generated from PRESTO eventfile - path to the event file. Will extract ObsID from this for the NICER files. segment_length - length of the segments demod - whether we're dea...
48d1579dd72575214dd757750964d4eb0b24926f
3,620,316
import socket def hostname(): """ Check the system's hostname :rtype: str :return: system hostname """ return socket.gethostname().split('.')[0]
438ccd56367565e0cf0c9e8783bc73cb4507e83b
3,620,317
def run_optimizers(args): """Optimize each of an iterable of PySource objects.""" sources = tuple(load_path(args.source)) for source in sources: utils.execute(args, source.node) return sources
4e43a1addbf3693eb29282ed0e0c85a4d6440976
3,620,318
import csv def import_data(file): """ Imports instruction data from a .csv file, at the specified filepath :param file: file File object, to be read by the CSV reader :return: list A list of dictionaries, per row in the file, with the keys specified in the headers list below ...
472f47c2e2111d5ce9a9d20e1ac447a504941aa2
3,620,319
def recipe_footpod_symmetry( df_footpods, df_music, df_phone_activity, df_sessions, sections=None ): """ Recipe for extracting statistical symmetry information per song for valid bouts of running of the real-time footpod data. Parameters ---------- df_footpods : pandas.DataFrame Dat...
b2112eea9df824678b1405b39f3825e1fea9b697
3,620,320
import os import json def get_authed_registries(): """Reads the local Docker client config for the current user and returns all registries to which the user may be logged in. This is intended to be run client-side, not by the daemon.""" result = set() if not os.path.exists(constants.DOCKER_CONFIG_...
2091ff4beed7bf3f4dcf3083d8ba3610e965aa18
3,620,321
import re def filter_data(data_frame): """ Process string value :param data_frame: raw data in data frame type :return: data frame """ data_frame[data_frame.columns[len(data_frame.columns) - 2]] = \ data_frame[data_frame.columns[len(data_frame.columns) - 2]].apply(lambda x: int("".join...
75e3a40c0c1d06db7da71e8b6ddb0001c5933634
3,620,322
from datetime import datetime def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None): """ get timezone as tz_offset """ tz_offset = datetime_to_timezone( datetime.now(), tz=tz_from).strftime('%z') tz_offset = tz_offset[:3] + ':' + tz_offset[3:] date = parse_date(str(date_str) + tz_off...
35aa52eee969dd3532b50c3a3679c24f0cf4f04e
3,620,323
from typing import Tuple from typing import List from typing import Any def _extract_bracket_params(meta_type: str) -> Tuple[str, List[Any]]: """ Gets parameters from the string representation of the type Args: meta_type (str): The string name of the metadata type Returns: Tuple[str,...
38fc3872c18bb788a54d50b09a36cf3f5925550e
3,620,324
def make_classification_df( seed: int, n_samples: int = 10_000, n_features: int = 25, n_informative: int = 10, n_redundant: int = 10, n_repeated: int = 5, class_sep: float = 0.2, flip_y: float = 0.1, target_col: str = "target", ) -> pd.DataFrame: """Source of default values: http...
31ea883341dbd2900ed7bd8402a796bad490ebde
3,620,325
import hashlib def create_view_ID(img): """ Generates 12-digit ID of image to make sure each image has a unique identifier. When saving and reading image features, two images with the same filename will have unique identifiers. :param img: image to create an ID for. :return viewID: a unique viewId...
2b429a5c504386e486542ac9f7a4fa663a08c996
3,620,326
import os def readList(flist, list_type='array',sep='\s+'): """ Function to read a key files and performs checks for required columns parameters Parameters: flist: str or pandas dataframe A path to the key file or DataFrame itself list_type: str "array" for array list, "event" for earthquake list, "coda"...
a2705888fb7bea5ff87abf9ca1185fe9ee78048b
3,620,327
import hashlib def calc_local_file_md5_sum(path): """ Calculate and return the MD5 checksum of a local file Arguments: path(str): The path to the file Returns: str: The MD5 checksum """ with open(path, "rb") as file_to_hash: file_as_bytes = file_to_hash.read() re...
78020e86a6d9a6939de6b9050d34fca0d482aab4
3,620,328
import json def news_keywords() -> str: """[Fetches the keywords used to gather news articles] Returns: str: [A string of the keywords searched for by the news API] """ with open("config.json", encoding="UTF-8") as config: config_data = json.load(config) news_kw = config_data[...
b0830625f58de9089130a3d571588ab558b2a3db
3,620,329
from typing import Any def default_weapon_type_option( description: str = "Restrict the weapon type. Default: All types", required: bool = False ) -> Any: """ Decorator that replaces @slash_option() Call with `@default_weapon_type_option()` """ def wrapper(func): return slash_option(...
5e5fe8e05e39ec7329264b4828b4047ea06b368a
3,620,330
from datetime import datetime async def get_patrol_id(request: Request): """ 获取当前order id,已经加 1 的了 """ _date_str = datetime.now().strftime('%Y%m') patrol_id = await request.app['redis'].get(f'it:patrolID:{_date_str}') if patrol_id is None: async with request.app['mysql'].acquire() as conn: ...
fcc0137e1af3ba2a22dc6d54b459af05db4c0e8b
3,620,331
from typing import Union from typing import List def parse( response_text: str, *, batch: bool, validate_against_schema: bool = True ) -> Union[JSONRPCResponse, List[JSONRPCResponse]]: """ Parses response text, returning JSONRPCResponse objects. Args: response_text: JSON-RPC response string. ...
ff0d2c5a4852255588db28068685f92dd6c4c66d
3,620,332
import os def install_client(request): """Displays an agreement that the user must agree to before they can download the MDM Client installer""" context = {} if request.method == 'POST': form = ClientForm(request.POST) if form.is_valid(): installer = os.path.join(settings.MEDIA...
7de1ed614ed1ffa0ec9701c85e27616db07deba5
3,620,333
def get_ping_ip(): # TODO: convert return to json object """ Get ips for network testing. @return: HTML containing a list of IPs """ config = request.form['config'] peers = g.cur.execute("SELECT id, name, allowed_ip, endpoint FROM " + config).fetchall() html = "" for i in peers: ...
f0428d485972a01a861de2820f1cb08a11b2d06e
3,620,334
def compute_warped_image_multiNC( I0, phi, spacing, spline_order, zero_boundary=False, use_01_input=True ): """Warps image. :param I0: image to warp, image size BxCxXxYxZ :param phi: map for the warping, size BxdimxXxYxZ :param spacing: image spacing [dx,dy,dz] :return: returns the warped image ...
1f2fffb1ed09fe2b40061dfc5728ed5b672e8828
3,620,335
from datetime import datetime def get_day(days: int = 0): """ 返回的日期格式 %Y-%m-%d :param days: 距离今天的天数 :return: 格式 %Y-%m-%d """ return (datetime.datetime.now() + datetime.timedelta(days=days)).strftime("%Y-%m-%d")
9626098ad53489d8fa9c1d5364e7a471003c48d6
3,620,336
def emit_compare(field_name, value, session, model): """Emit a comparison operation comparing the value of ``field_name`` on ``model`` to ``value``.""" property = getattr(model, field_name) return property == value
a9ad880951f87f488b12c4ce7c38c5e0e463a798
3,620,337
def line_loglog(x, m, n): """a straight line in loglog-space""" return x ** m * np.e ** n
119c6b1d4e758279c10c4667839ea83742556492
3,620,338
def plot_statistical_uncertainty(response_matrix, filename=None, **kwargs): """Plot the maximum sqrt(statistical variance) of each truth bin. This plots will contain the minimum, maximum, and median marginalization of these maximum numbers. Parameters ---------- response_matrix : ResponseMatr...
7b86e929a4d620d3302dce67bfb546f4b05f7c42
3,620,339
import numpy as np import scipy.linalg as la def milcshake_a ( dt, bond, r_old, r, v ): """First part of velocity Verlet algorithm with constraints.""" # This subroutine iteratively adjusts the positions stored in the array r # and the velocities stored in the array v, to satisfy the bond constraints ...
9184b7861383710d84cbe6176e4cca1c206d29c0
3,620,340
def parse_LDI_ins(tokens): """Attempts to parse a LDI instruction.""" failure = None assert len(tokens) > 0 token1 = tokens[0] op = token1.text if op.upper() != 'LDI': return failure statement = Obj() statement.type = 'STATEMENT' statement.statement_type = 'INSTRUCTION' s...
92c6102ccaea4b5fda025c7e7ac10cf0549b56d3
3,620,341
def mad(a, axis=None): """ Compute *Median Absolute Deviation* of an array along given axis. """ # Median along given axis, but *keeping* the reduced axis so that result can still broadcast against a. med = np.nanmedian(a, axis=axis, keepdims=True) mad = np.nanmedian(np.absolute(a - med), axis=a...
7a439c970bab9696d4a1b50725afd6636f437843
3,620,342
import torch def torch_image_to_numpy(image: torch.Tensor): """ We've created a function `torch_image_to_numpy` to help you out. This function transforms an torch tensor with shape (batch size, num channels, height, width) to (batch size, height, width, num channels) numpy array """ ...
0ce27349d40a8063137a79351fa7a696cd8c6615
3,620,343
import os def has_data(file_path): """ Check if a file has any data in it. `Args:` file_path: str The file path. `Returns:` boolean ``True`` if data in the file and ``False`` if not. """ if os.stat(file_path).st_size == 0: return False els...
d135bbca9281f1f258b845506c40c95f01a80e48
3,620,344
def unsigned32(i): """cast signed 32 bit integer to an unsigned integer""" return i & 0xFFFFFFFF
1d4e06406d3ee7ce7d8f5cefd28955f135059917
3,620,345
import json def get_snippet_edit_code(request, snippet_id): """ Returns a HTTPResponse that renders the admin of a smartsnippet. :param request: Request needed to create the rendering context :param snippet_id: id of the smartsnippet model :param request.POST.config: dictionary containing existi...
5eaf24488ef8d3ffa8f46356d840fa4b63cf99b3
3,620,346
def get_user_legs(df, user_id, use_multiprocessing=True) -> pd.DataFrame: """ Builds the legs DataFrame for the given user. Args: df (pandas.DataFrame): waypoints DataFrame user_id (str): ID of the user whose legs are to be created use_multiprocessing (bool, optional): Specifie...
6d21192236ad72578e4d9c443f9fdaab12be254a
3,620,347
from typing import List from typing import Tuple from typing import Dict import torch from typing import OrderedDict def generate_input( seq_len: int, batch_size: int, input_names: List[str], device: str = "cuda" ) -> Tuple[Dict[str, torch.Tensor], Dict[str, np.ndarray]]: """ Generate dummy inputs. :p...
d084e1a982ee2ecd60b0e986ead75bc5273ccbb1
3,620,348
def get_task_or_404(challenge_slug, task_identifier): """Return a task based on its challenge and task identifier""" t = Task.query.filter( Task.challenge_slug == challenge_slug).filter( Task.identifier == task_identifier).first() if not t: abort(404) return t
1765069d18604ba00a4efd1fd18a645ccc666fd6
3,620,349
def BuildToken(request, execution_time): """Build an ACLToken from the request.""" token = access_control.ACLToken( username=request.user, reason=request.REQ.get("reason", ""), process="GRRAdminUI", expiry=rdfvalue.RDFDatetime().Now() + execution_time) for field in ["REMOTE_ADDR", "HTTP_X...
164244ca93710c45d0eb8b19b1eb0c934ac89361
3,620,350
import re from datetime import datetime def parse_logfile_event_marker(line_str): """ Parse a logfile line as an event marker. Parameters: line_str (str): a line from the locust log for a load test with markers enabled. Returns: dict: dict object with the following keys: ...
0746e23926c3f4262d163c6e10d0ae8177e36ece
3,620,351
import logging import torch def preprocess_pipeline(image): """preprocess_pipeline processes the image data. args: image: a numpy array in shape of (224, 224, 3) returns: image: the processed image numpy array """ assert np.array_equal(image.shape, (224, 224, 3)), \ "...
e5ae77b0a0f8c18825b546a4ec4135eb8385bcc1
3,620,352
import tkinter as tk from tkinter import filedialog import os def ask_path(folder_flag=True, multiple_files_flag=False): """Makes a tkinter dialog for choosing the folder if folder_flag=True or file(s) otherwise. For multiple files the multiple_files_flag should be True. """ # This method is almos...
675f36f34a97a3445d35d1e7a45ee71e60a7ea48
3,620,353
def compute_gad_point_indices_mp(args: tuple) -> dict: """ Computes geometric anomaly detection (GAD) Procedure 1 from [1], for data point indices, taking in args for multiprocessing purposes. Parameters ---------- args : tuple Multiprocessing argument tuple: data_points : n...
c0cc874af561f15b0b8234a5279f54d4df9afdee
3,620,354
def has_and_not_none(obj, name): """ Returns True iff obj has attribute name and obj.name is not None """ return hasattr(obj, name) and (getattr(obj, name) is not None)
0d68a9b01d56ba056768d06a88c68b4bd5bbd4d2
3,620,355
from typing import OrderedDict import attr def _dump(config_instance, dict_type=OrderedDict): """ Dumps an instance from ``instance`` to a dictionary type mapping. :param object instance: The instance to serialized to a dictionary :param object dict_type: Some dictionary type, defaults to ``OrderedDict``...
d8b1242d4ab47b518dfd4523e83c1d67f5e87537
3,620,356
def eval_jac_g(x, out): """Values of the jacobian of g""" assert len(x) == nvar out[()] = [ x[1] * x[2] * x[3], x[0] * x[2] * x[3], x[0] * x[1] * x[3], x[0] * x[1] * x[2], 2.0 * x[0], 2.0 * x[1], 2.0 * x[2], 2.0 * x[3], ] return out
a50f3e8621ad5a54f69d2d154464e6ba8e818337
3,620,357
import torch from typing import Optional import os def pytorch_load_save_functions( state_dict_objects: dict, mutable_state: Optional[dict] = None, fname: str = "checkpoint.json", ): """ Provides default `load_model_fn`, `save_model_fn` functions for standard PyTorch models (arguments to `resu...
ee232e386daffbdcd29ef08511fc36683d6adbca
3,620,358
import re def trivial_tokenize_urdu(s): """ A trivial tokenizer which just tokenizes on the punctuation boundaries. This also includes punctuations for the Urdu script. These punctuations characters were identified from the Unicode database for Arabic script by looking for punctuation symbols. return...
a631328849afb1fbee74788a85169874f1a895ef
3,620,359
def fpath_to_link(repo_id, path, is_dir=False): """Translate file path of a repo to its view link""" if is_dir: url = reverse("repo", args=[repo_id]) else: url = reverse("repo_view_file", args=[repo_id]) href = url + '?p=/%s' % urllib2.quote(path.encode('utf-8')) return '<a href="%...
bd4763c12983763480631714befbb771459a6b1e
3,620,360
def _qname_matches(tag, namespace, qname): """Logic determines if a QName matches the desired local tag and namespace. This is used in XmlElement.get_elements and XmlElement.get_attributes to find matches in the element's members (among all expected-and-unexpected elements-and-attributes). Args: ...
66aa9272fd6e4a6e281d39f03dd63acabad0bbe7
3,620,361
def NodeArrangementHexToTet(C): """Node ordering for conversion of a hexahedron into 6 tetrahedra refer to: [Julien Dompierre et.al. "How to Subdivide Pyramids, Prisms and Hexahedra into Tetrahedra", 8th International Meshing Roundtable, Lake Tahoe, California, 10-13 October 1999.] for only p=1...
919773449d323e6d7b4c632938d89cb6d25440d3
3,620,362
def datetogmt(str): """ Convert date string to gmt time. """ date_tuple = datetotuple(str) return mkgmtime(date_tuple)
5fa593d94926c787c700e5f9aff73d3b5dc5d2e2
3,620,363
def parse_color(color): """ Parses color into a vtk friendly rgb list """ if color is None: color = rcParams['color'] if isinstance(color, str): return vtki.string_to_rgb(color) elif len(color) == 3: return color else: raise Exception(""" Invalid color input M...
c06eec3de5d50e2e3902a66e469f6df96e679971
3,620,364
def skewness(iterable, sample=False): """ Returns the degree of asymmetry of the given list of values: > 0.0 => relatively few values are higher than mean(list), < 0.0 => relatively few values are lower than mean(list), = 0.0 => evenly distributed on both sides of the mean (= normal distribu...
3cee6e2eaf7095d92229d6744deb775e7d5b64a0
3,620,365
def create_plant(user_id, plant_name, plant_type, photo_url, germinate_date, directsow, transplant_date, growing_medium, location, environment, lighting, schedule): """ For example: >>> create_plant(1, "Nadine", "Aloe", "/static/img/aloe.jpg", "11/11/2020", "direct s...
517ff885f551ec898a52138a3179ca2c6830af52
3,620,366
def writeDaily(config, daily, data_binding, table_type): """ Writes a Daily object or list of Daily objects to the specified data_binding and table. table_type must be 'obs', 'verif', 'climo', 'hourly_forecast', or 'daily_forecast', or something defined in the schema of data_binding as %(stid)_%(table_t...
445c0e645fc0c94d5347401648fc4d0131a47cae
3,620,367
import json def get_line_extents_from_json(json_data, font_file_name): """Find the vertical extents of a line based on HarfBuzz JSON output.""" max_height = None min_height = None for glyph_position in json.loads(json_data): glyph_id = glyph_position['g'] glyph_ymin, glyph_ymax = get_g...
241e715e1393ab2de9f592178ccc9e7f1f516b2f
3,620,368
def findSpikes( file_name, sweep_IB_concatenated, prominence_min = None, prominence_max = None, wlen_ms = 10, sampling_rate_khz = 25 ): """ `findSpikes` uses scipy's `find_peaks` on the concatenated sweeps to detect peaks in the data and obtain their prominences. It then plots the di...
52586d3e55dbc8fbf5cd2a97afb612e1ce8fd3b3
3,620,369
def promptForFlirtFiles(parent, overlay, overlayList, displayCtx, save=False): """Displays a dialog prompting the user to select a FLIRT transformation matrix file and associated reference image for the given overlay. :arg parent: The :mod:`wx` parent object. :arg overlay: The overlay to l...
b17834d762c236b4b6cabfcae779fbd4d4899b29
3,620,370
def coord_c2g(map_): """Rotate a map from celestial co-ordinates into galactic co-ordinates. This will operate on a series of maps (provided the Healpix index is last). Parameters ---------- map : np.ndarray[..., npix] Healpix map. Returns ------- rotmap : np.ndarray T...
4850fb1be975bc2acf6020aa878381f40e1c29ba
3,620,371
def tourism_per_year_by_country(country): """Returns the number of arrivals (tourism) per year of the given country.""" cur = get_db().execute('SELECT Year, Value FROM Indicators WHERE CountryCode="{}" AND IndicatorCode="ST.INT.ARVL"'.format(country)) tourism = cur.fetchall() cur.close() return json...
e8515f8d31de021b53c568ee01bb29aeda188e8e
3,620,372
from typing import Optional from typing import Union import subprocess def run_local(command: str, str_output: Optional[bool] = False) -> Union[int, str]: """Runs a command locally and captures output.""" print(command) if str_output: process = subprocess.Popen( command, s...
fc56e2106a4f4104c30ec2f4a3252b8e43e8bdf3
3,620,373
def get_hst_to_jwst_coefficient_order(polynomial_degree): """Return array of indices that convert an aeeay of HST coefficients to JWST ordering. This assumes that the coefficient orders are as follows HST: 1, y, x, y^2, xy, x^2, y^3, xy^2, x^2y, x^3 ... (according to Cox's /grp/hst/OTA/alignment/Fo...
ceec3c2a7202ba1250f11e0d2ce3e01dc771de0f
3,620,374
from typing import List def get_categories(title: str) -> List[str]: """ Gets the categories of the wikipedia page `title` from https://en.wikipedia.org/w/api.php?action=query&format=json&titles={title}&prop=categories Returns empty list for invalid title with no redirects """ params = { ...
644eb7b110ff7e7684b8cc4dff5ca957c754941f
3,620,375
def get_chombo_box_extent(box, space_dim): """ Parse box extents from Chombo HDF5 files into low and high limits Parameters ---------- box : List Chombo HDF5 format box limits, e.g. [x_lo, y_lo, x_hi, y_hi] = [0,0,1,1] space_dim : int Number of spatial dimensions ...
d72b409a96c8a1936f456d87a341fba22ee9f97e
3,620,376
def _fast_rcnn_box_loss(box_outputs, box_targets, class_targets, normalizer=1.0, delta=1.): """Computes box regression loss.""" # delta is typically around the mean value of regression target. # for instances, the regression targets of 512x512 input with 6 anchors on # P2-P6 pyramid is a...
e408ab6068ee56af3a96be41ae894abea1a0e439
3,620,377
def calc_gcn_norm(edge_index, num_nodes, edge_weight=None): """ calculate GCN Normalization. Parameters ---------- edge_index: edge index num_nodes: number of nodes of graph edge_weight: edge weights of graph Returns ------- 1-dim Tensor "...
da1f74b1a0ad907320a6426354228d4da97df7aa
3,620,378
def get_raw_pdb_filename_from_interim_filename(interim_filename, raw_pdb_dir): """Get raw pdb filename from interim filename.""" pdb_name = interim_filename slash_tokens = pdb_name.split('/') slash_dot_tokens = slash_tokens[-1].split(".") raw_pdb_filename = raw_pdb_dir + '/' + slash_tokens[-2] + '/'...
084239659220ea65ae57a006c8ce28df73b2fd5e
3,620,379
import re import os def txt_to_csv(dfile): """Converting the textfile to another textfile where elements are seperated with commas Function meant for false detection module only """ with open("resultsdata_mod_.txt", "a") as f: f.write("_id,time_ratio,intensity_ratio,bandwidth_1,bandwidth_2,er...
689128ca8f9b951e76aedb83f6e1a57925d895e4
3,620,380
def mae(y_true, y_pred): """Mean absolute error""" assert y_true.shape == y_pred.shape, f"{y_true.shape} != {y_pred.shape}" return np.mean(np.abs(y_true - y_pred), axis=0)
6c2a230b6a109af097cdc4fd44dadc87a6de9f5b
3,620,381
def class_tree_graph(bases, linker, context=None, **options): """ Return a `DotGraph` that graphically displays the class hierarchy for the given classes. Options: - exclude - dir: LR|RL|BT requests a left-to-right, right-to-left, or bottom-to- top, drawing. (corresponds to the dot op...
9782086a8928cdebc4f619d5bdf742b53bd8a502
3,620,382
import logging import sympy import operator def generate_parameters(phase_models, datasets, ref_state, excess_model, ridge_alpha=None, aicc_penalty_factor=None, dbf=None): """Generate parameters from given phase models and datasets Parameters ---------- phase_models : dict Dictionary of compo...
16099955dbae2dc7333b0f3e9e53d9769f9c76ad
3,620,383
def cg_optimize(th,floss,fgradloss,metric_length, substeps,damping,cg_iters=10, fmetric=None, num_diff_eps=1e-4,with_projection=False, use_scipy=False, fancy_damping=0,do_linesearch=True, min_lm = 0.0): """ Use CG to take one or more truncated newton steps, where a line search is used to enforce improv...
2320e3847ec88fa1d88859d610b902b99daa662e
3,620,384
import signal import re import sys def create_ipython_shortcuts(shell): """Set up the prompt_toolkit keyboard shortcuts for IPython""" kb = KeyBindings() insert_mode = vi_insert_mode | emacs_insert_mode if getattr(shell, 'handle_return', None): return_handler = shell.handle_return(shell) ...
558e1c3d244b947d3e33970bdc26679b61cabe70
3,620,385
def add_forth_coord(points): """forth coordinate is const = 1""" return np.hstack((points, np.ones((len(points), 1))))
09bfcd59bafd7764b78568d6496ec895dd923e31
3,620,386
import os def tf_tol(): """Numerical tolerance for equality tests.""" return float(os.environ.get("TF_TOL", TF_TOL))
7de67b0839131caac72af785cfe2a41c07905633
3,620,387
def _read_reaction_gpr_from_sbml(reaction, mass_notes, f_replace): """Read the GPR information from SBMLDocument and return as a string. Warnings -------- This method is intended for internal use only. """ reaction_fbc = reaction.getPlugin("fbc") if reaction_fbc: # GPR rules ...
a9d1a91f93345c57ab91dd8f7b2eb70a2bb6e28b
3,620,388
def conv_block(x, nfeat, strides=1, name=None): """ Specific convolutional block followed by leakyrelu for unet. """ ndims = len(x.get_shape()) - 2 assert ndims in (1, 2, 3), 'ndims should be one of 1, 2, or 3. found: %d' % ndims Conv = getattr(KL, 'Conv%dD' % ndims) convolved = Conv(nfeat,...
90ed04ca5122158d609b0999db63665fa6d5121b
3,620,389
import torch def sample_from_discretized_mix_logistic(y, log_scale_min=None): """ https://github.com/fatchord/WaveRNN/blob/master/utils/distribution.py Sample from discretized mixture of logistic distributions Args: y (Tensor): B x C x T log_scale_min (float): Log scale minimum value ...
4d864be504bc0a08f58c5332785578c4c8cc551f
3,620,390
def min_dist_conformer_zma(dist_name, cnf_save_fs): """ locators for minimum energy conformer """ cnf_locs_lst = cnf_save_fs[-1].existing() cnf_zmas = [] for locs in cnf_locs_lst: zma_fs = autofile.fs.zmatrix(cnf_save_fs[-1].path(locs)) cnf_zmas.append(zma_fs[-1].file.zmatrix.read([0])) ...
6575a7ff9f1af4d971bb01580cbbf2af2f93cac9
3,620,391
def array_offset(x): """Get offset of array data from base data in bytes.""" if x.base is None: return 0 base_start = x.base.__array_interface__["data"][0] start = x.__array_interface__["data"][0] return start - base_start
b383a91790b06ffb1b5b976b9575efe637fa47a6
3,620,392
def get_kernelf(config, context={}): """Get a kernel function.""" return _from_config(config, classes=classes, context=context)
ff549e6e20f48bec1e9bda9721fdd9a0afc84003
3,620,393
def solve_evolutionary_op(problem, save_results=True, return_history=False, step_hook=None, post_process_hook=None, nls_status=None): """TODO return_history""" step_args = problem, nls_status time_solver = problem.get_time_s...
80238385181b6d6d624de036ef5b65ca27aa35e1
3,620,394
import requests def layer_ogc_request(request, layername): """Provide one OGC server per layer, with their own GetCapabilities. :param layername: The layer name in Geonode. :type layername: basestring :return: The HTTPResponse with the response from QGIS Server. """ layer = get_object_or_404...
5707e3aed6223160260b2b6313d03cb98f612362
3,620,395
import torch def _demo_inputs_pair(img_shape=(64, 64), batch_size=1, cuda=False): """ Create a superset of inputs needed to run backbone. Args: img_shape (tuple): shape of the input image. batch_size (int): batch size of the input batch. cuda (bool): whether transfer input into gp...
fd0d68db73338f30de4d4dbe7939068b453981cd
3,620,396
def get_song(song_name): """Return information about a song. Parameters ---------- song_name : str The song name. Returns ------- dict name - The song name. files - Dictionary with downloaded files for this song. """ song = cache.get(song_name) if song ...
40a9752f077aeaf185d1bbc7a21f6be28658f926
3,620,397
def message_create(request, slug, topic_id, template_name='groups/message_form.html'): """ Returns a group message form. Templates: ``groups/message_form.html`` Context: form GroupMessageForm object """ group = get_object_or_404(Group, slug=slug) topic = get_object_or_40...
a0ff989c73fecbe681c167637fee35d86d3e1afd
3,620,398
def index(): """ Simple Home Page """ module_name = deployment_settings.modules[module].name_nice return dict(module_name=module_name)
5628a30596688917fdc19956f16cd7d0f68754e6
3,620,399