content
stringlengths
22
815k
id
int64
0
4.91M
def fits_downloaded_correctly(fits_loc): """ Is there a readable fits image at fits_loc? Does NOT check for bad pixels Args: fits_loc (str): location of fits file to open Returns: (bool) True if file at fits_loc is readable, else False """ try: img, _ = fits.getdat...
5,358,200
def union_of_rects(rects): """ Calculates union of two rectangular boxes Assumes both rects of form N x [xmin, ymin, xmax, ymax] """ xA = np.min(rects[:, 0]) yA = np.min(rects[:, 1]) xB = np.max(rects[:, 2]) yB = np.max(rects[:, 3]) return np.array([xA, yA, xB, yB], dtype=np.int32)
5,358,201
def configure_services(config: List[Dict]) -> Dict[str, GcpServiceQuery]: """ Generate GcpServiceQuery list from config :param config: list with GcpServieQuery's configuration :return: mapping of service name to GcpServiceQuery objects """ if not isinstance(config, list): raise GcpServic...
5,358,202
def tags_get(): """ Get endpoint /api/tag args: optional company_filter(int) - id of a company, will only return tag relation to said company optional crowd(int) - 0 - 2 specifing crowd sourcing option. Key: 0 - all tags 1 - Only crowd sourced tags 2 - Only non crowd...
5,358,203
def gunzip(filename, targetdir): """Decompress a gzip-compressed file into a target directory. Args: filename: Full path to gzip file. targetdir: Directory to decompress file into. Returns: The output file name. Raises: FileNotFoundError: `filename` does not exist. ...
5,358,204
def async_sendmail(subject, message, to): """异步邮件发送,可用于多线程及非Web上下文环境""" def send_async_email(app): with app.test_request_context(): app.preprocess_request() sendmail(subject, message, to) app = current_app._get_current_object() t = Thread(target=send_async_email, args=[ap...
5,358,205
def get_accept_languages(accept): """Returns a list of languages, by order of preference, based on an HTTP Accept-Language string.See W3C RFC 2616 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) for specification. """ langs = parse_http_accept_header(accept) for index, lang in enumerate...
5,358,206
def get_princ_axes_xyz(tensor): """ Gets the principal stress axes from a stress tensor. Modified from beachball.py from ObsPy, written by Robert Barsch. That code is modified from Generic Mapping Tools (gmt.soest.hawaii.edu) Returns 'PrincipalAxis' classes, which have attributes val, trend, p...
5,358,207
def extractYoushoku(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if 'The Other World Dining Hall' in item['tags'] and (chp or vol): return buildReleaseMessageWithType(item, 'The Other World Dining Hall', vol, chp, frag=frag, postfix=postfix) return False
5,358,208
def _perform_Miecalculations(diam, wavelength, n, noOfAngles=100.): """ Performs Mie calculations Parameters ---------- diam: NumPy array of floats Array of diameters over which to perform Mie calculations; units are um wavelength: float Wavelength...
5,358,209
def load_config_dict(pipette_id: str) -> Tuple[ 'PipetteFusedSpec', 'PipetteModel']: """ Give updated config with overrides for a pipette. This will add the default value for a mutable config before returning the modified config value. """ override = load_overrides(pipette_id) model = ov...
5,358,210
def ErrorAddEncKey(builder, encKey): """This method is deprecated. Please switch to AddEncKey.""" return AddEncKey(builder, encKey)
5,358,211
def test_run_without_exception(): """Not a good test at all. :(""" try: settings = { "LINKEDIN_USER": os.getenv("LINKEDIN_USER"), "LINKEDIN_PASSWORD": os.getenv("LINKEDIN_PASSWORD"), "LINKEDIN_BROWSER": "Chrome", "LINKEDIN_BROWSER_DRIVER": "/Users/dayhatt/...
5,358,212
def _read_txs_from_file(f): """ Validate headers and read buy/sell transactions from the open file-like object 'f'. Note: we use the seek method on f. """ ans = [] f.seek(0) workbook = openpyxl.load_workbook(f) sheet = workbook.active all_contents = list(sheet.rows) _validate_he...
5,358,213
def get_generator_regulation_lower_term_4(data, trader_id, intervention) -> Union[float, None]: """Get L5RE term 4 in FCAS availability calculation""" # Term parameters enablement_min = get_effective_enablement_min(data, trader_id, 'L5RE') energy_target = lookup.get_trader_solution_attribute(data, trad...
5,358,214
def count_parameters(model): """count model parameters""" return sum(p.numel() for p in model.parameters() if p.requires_grad)
5,358,215
def scenario(l_staticObject, l_cross, l_road): """ Coordinates of objects in a scenario. Include: l_staticObject: list of static objects l_cross: list of pedestrian crosses l_road: list of road layouts """ # road layout road = Road( left=np.array([[-100, 2], ...
5,358,216
def string_rule_variable(label=None, params=None, options=None, public=True): """ Decorator to make a function into a string rule variable. NOTE: add **kwargs argument to receive Rule as parameters :param label: Label for Variable :param params: Parameters expected by the Variable function :pa...
5,358,217
def detect_horizon_lines(image_thre, row, busbar, cell_size, thre=0.6, split=50, peak_interval=None, margin=None): """ Detect horizontal edges by segmenting image into vertical splits Parameters --------- image_thre: array Adaptive threshold of raw images row: int Number of rows of solar m...
5,358,218
def countRoem(cards, trumpSuit=None): """Counts the amount of roem (additional points) in a list of cards Args: Returns: Integer value how many points of roem are in the cards in total """ roem = 0 # Stuk # Without a trumpSuit, stuk is impossible if trumpSuit is not None: ...
5,358,219
def batch_to_space( data: NodeInput, block_shape: NodeInput, crops_begin: NodeInput, crops_end: NodeInput, name: Optional[str] = None, ) -> Node: """Perform BatchToSpace operation on the input tensor. BatchToSpace permutes data from the batch dimension of the data tensor into spatial dimens...
5,358,220
def test_DetectionMAP(): """ test DetectionMAP :return: """ train_program = fluid.Program() startup_program = fluid.Program() with fluid.unique_name.guard(): with fluid.program_guard(train_program, startup_program): detect_res = fluid.layers.data( name='de...
5,358,221
def url_in(url): """ Send a URL and I'll post it to Hive """ custom_json = {'url': url} trx_id , success = send_notification(custom_json) return trx_id, success
5,358,222
def login(): """ Display a basic login form in order to log in a user """ if request.method == 'GET': return render_template('login.html') else: try: usr = User.query.get(request.form['user_id']) if bcrypt.checkpw(request.form['user_password'].encode('utf-...
5,358,223
def hflip(stream): """Flip the input video horizontally. Official documentation: `hflip <https://ffmpeg.org/ffmpeg-filters.html#hflip>`__ """ return FilterNode(stream, hflip.__name__).stream()
5,358,224
def get_diagonal_ripple_rainbows_2(): """ Returns 11 diagonal ripple rainbows Programs that use this function: - Diagonal Ripple 3 - Diagonal Ripple 4 """ rainbow01 = [ [C1, C2, C3, C4, C5, C6, C7, C8], [C1, C2, C3, C4, C5, C6, C7, C8], [C1, C2, C3, C4, C5, ...
5,358,225
def add_file(original_filepath: Path, path_from_repo: Path) -> None: """Copies the file from the repository to staging area. All parent folders will be created, albeit empty. """ hierarchy = paths.staging_area / path_from_repo if not hierarchy.exists(): hierarchy.mkdir(parents=True) shut...
5,358,226
def matrix_prod(A, B, display = False): """ Computes the matrix product of two matrices using array slicing and vector operations. """ if A.shape[1] != B.shape[0]: raise ValueError("Dimensions not compatible.") # Not allowed!? #matrix = A.dot(B) # Dotproduct of each A.row*B.clm ...
5,358,227
def remove_quat_discontinuities(rotations): """ Removing quat discontinuities on the time dimension (removing flips) :param rotations: Array of quaternions of shape (T, J, 4) :return: The processed array without quaternion inversion. """ rots_inv = -rotations for i in range(1, rotations.sha...
5,358,228
def compute_profile_from_frames(frames_str, ax, bt, box, N_bins=100, \ shift=None, verbose=False): """ Compute a density profile from a batch of xyz frames. Input ===== - frames_str: a regex containing frames in xyz format - ax: axis along which to compute the profile - bt: bead typ...
5,358,229
def wikipedia_search(query, lang="en", max_result=1): """ https://www.mediawiki.org/wiki/API:Opensearch """ query = any2unicode(query) params = { "action":"opensearch", "search": query, "format":"json", #"formatversion":2, #"namespace":0, "suggest"...
5,358,230
def group_result(result, func): """ :param result: A list of rows from the database: e.g. [(key, data1), (key, data2)] :param func: the function to reduce the data e.g. func=median :return: the data that is reduced. e.g. [(key, (data1+data2)/2)] """ data = {} for key, value in result: ...
5,358,231
def prep_image(img, inp_dim): """ Prepare image for inputting to the neural network. Returns a Variable """ orig_im = img dim = orig_im.shape[1], orig_im.shape[0] img = cv2.resize(orig_im, (inp_dim, inp_dim)) # img_ = img[:,:,::-1].transpose((2,0,1)).copy() img_ = img.transpos...
5,358,232
def add_periodic_callback(doc, component, interval): """ Add periodic callback to doc in a way that avoids reference cycles If we instead use ``doc.add_periodic_callback(component.update, 100)`` then the component stays in memory as a reference cycle because its method is still around. This way we avo...
5,358,233
def s11_warmup_plot( freq: np.ndarray, s11_re: Dict[str, List[np.ndarray]], s11_im: Dict[str, List[np.ndarray]], temperatures: np.ndarray, filename=None, ): """Plot all the S11 measurements taken in warmup, to illustrate convergence.""" nfreq = len(freq) assert len(s11_re) == len(s11_im)...
5,358,234
def extractLogData(context): """ helper function to extract all important data from the web context. :param context: the web.py context object :return: a dictionary with all information for the logging. """ logData = {} logData['ip'] = context.ip logData['account'] = context.env.get('H...
5,358,235
def slithering_snake_32(): """ Lights up then turns off the LEDs on arms 3 and 2 """ LOGGER.debug("SLITHERING SNAKE 32") sleep_speed = 0.10 # Light up Snake 32 PYGLOW.led(13, 100) sleep(sleep_speed) PYGLOW.led(14, 100) sleep(sleep_speed) PYGLOW.led(15, 100) sleep(sleep_...
5,358,236
def balance_test(): """Balance the site frequency spectrum""" pos = [1, 10, 20, 30] stop = [2, 11, 21, 31] ref = ['A', 'C', 'T', 'G'] alt = ['T', 'G', 'G', 'A'] p = [0.1, 0.9, 0.3, 0.2] l = vr.VariantList(pos, stop, ref, alt, p) # The core things here are to make sure the sfs is balanced AND the rank o...
5,358,237
def Backbone(backbone_type='ResNet50', use_pretrain=True): """Backbone Model""" weights = None if use_pretrain: weights = 'imagenet' def backbone(x_in): if backbone_type == 'ResNet50': return ResNet50(input_shape=x_in.shape[1:], include_top=False, ...
5,358,238
def start(ctx, vca_client, **kwargs): """ power on server and wait network connection availability for host """ # combine properties obj = combine_properties( ctx, kwargs=kwargs, names=['server'], properties=[VCLOUD_VAPP_NAME, 'management_network']) # get external if obj.get(...
5,358,239
def softplus(z): """Numerically stable version of log(1 + exp(z)).""" # see stabilizing softplus: http://sachinashanbhag.blogspot.com/2014/05/numerically-approximation-of-log-1-expy.html # noqa mu = z.copy() mu[z > 35] = z[z > 35] mu[z < -10] = np.exp(z[z < -10]) mu[(z >= -10) & (z <= 35)] = log...
5,358,240
def merge_indexes( indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]], variables: Mapping[Hashable, Variable], coord_names: Set[Hashable], append: bool = False, ) -> "Tuple[OrderedDict[Any, Variable], Set[Hashable]]": """Merge variables into multi-indexes. Not public API. Used in D...
5,358,241
def least_squares(m, n): """ Create a least squares problem with m datapoints and n dimensions """ A = np.random.randn(m, n) _x = np.random.randn(n) b = A.dot(_x) x = cp.Variable(n) return (x, cp.Problem(cp.Minimize(cp.sum_squares(A * x - b) + cp.norm(x, 2))))
5,358,242
def main(): """ Implements the first step of the experiment pipeline. Creates feature \ sets for each one of the folds. Returns: None """ # Construct argument parser and parse arguments ap = argparse.ArgumentParser() ap.add_argument('-fpath', required=True) args = vars(ap.pa...
5,358,243
def getRef(refFile): """Returns a genome reference.""" refDict={} hdList=[] ref='' num=0 try: f=open(refFile) except IOError: errlog.error('Cannot find reference file ' +refFile+'. Please check pathname.') sys.exit('Cannot find reference file '+refFile+'. Please check...
5,358,244
def cleanup_path(paths, removedir=True): """ remove unreable files and directories from the input path collection, skipped include two type of elements: unwanted directories if removedir is True or unaccessible files/directories """ checked = [] skipped = [] for ele in paths: ele = ...
5,358,245
def expand_amn(a, kpoints, idx, Rvectors, nproj_atom=None): """ Expand the projections matrix by translations of the orbitals Parameters ---------- a : ndarray, shape (nkpts, nbnds, nproj) kpoints : ndarray, shape (nkpts, 3) idx : ndarray indices of translated orbitals Rvectors:...
5,358,246
def combine_basis_vectors(weights, vectors, default_value=None, node_num=None): """ Combine basis vectors using ``weights`` as the Manning's n value for each basis vector. If a ``default_value`` is set then all nodes with out data are set to the ``default_value``. :type weights: :class:`numpy....
5,358,247
def demo1(): """ 假设我们有三台洗衣机, 现在有三批衣服需要分别放到这三台洗衣机里面洗. """ def washing1(): sleep(3) # 第一台洗衣机, 需要洗3秒才能洗完 (只是打个比方) print('washer1 finished') # 洗完的时候, 洗衣机会响一下, 告诉我们洗完了 def washing2(): sleep(2) print('washer2 finished') def washing3(): sleep(5) ...
5,358,248
def test_managed_static_method_handler(): """Test managed static method handlers.""" ob = EventTest() EventTest.s_value = 0 ob.PublicEvent += ob.StaticHandler assert EventTest.s_value == 0 ob.OnPublicEvent(EventArgsTest(10)) assert EventTest.s_value == 10 ob.PublicEvent -= ob.StaticHa...
5,358,249
def _prepare_data_for_node_classification( graph: nx.Graph, seed_node: int ) -> List[Tuple[Any, Any]]: """ Position seed node as the first node in the data. TensorFlow GNN has a convention whereby the node to be classified, the "seed node", is positioned first in the component. This is for use with...
5,358,250
def init(): """ Init the application and add routes """ logging.basicConfig(format='%(asctime)s: [%(levelname)s]: %(message)s', level=logging.DEBUG) global theconfig theconfig = get_config() global rc rc = init_redis(theconfig) app = default_app() return app
5,358,251
def norm_potential(latitude, longitude, h, refell, lmax): """ Calculates the normal potential at a given latitude and height Arguments --------- latitude: latitude in degrees longitude: longitude in degrees height: height above reference ellipsoid in meters refell: reference ellipsoid n...
5,358,252
def _findPlugInfo(rootDir): """ Find every pluginInfo.json files below the root directory. :param str rootDir: the search start from here :return: a list of files path :rtype: [str] """ files = [] for root, dirnames, filenames in os.walk(rootDir): files.extend(glob.glob(root + '/plug...
5,358,253
def get_pp_gene_chains(chain_class_file, v=False): """Get gene: pp chains dict.""" gene_to_pp_chains = defaultdict(list) # init the dict f = open(chain_class_file, "r") # open file with classifications f.__next__() # skip header for line in f: line_data = line.rstrip().split("\t") ...
5,358,254
def test_load_accessor(test_df): """Function_docstring.""" check.is_not_none(getattr(test_df, "mp_pivot")) check.is_not_none(getattr(test_df.mp_pivot, "run")) check.is_not_none(getattr(test_df.mp_pivot, "display")) check.is_not_none(getattr(test_df.mp_pivot, "tee")) check.is_not_none(getattr(tes...
5,358,255
def rec_search(wildcard): """ Traverse all subfolders and match files against the wildcard. Returns: A list of all matching files absolute paths. """ matched = [] for dirpath, _, files in os.walk(os.getcwd()): fn_files = [os.path.join(dirpath, fn_file) for fn_file ...
5,358,256
def skip_object(change_mode, change): """ If `Mode` is `change`: we do not care about the `Conditions` Else: If `cfn` objects: - We can omit the `Conditions`, objects will be involed when `Mode` is `provision` or `destroy`. (Original design. Backward compatibility.) - In case...
5,358,257
def rootfinder(*args): """ rootfinder(str name, str solver, dict:SX rfp, dict opts) -> Function Create a solver for rootfinding problems Takes a function where one of the rootfinder(str name, str solver, dict:MX rfp, dict opts) -> Function rootfinder(str name, str solver, Function f, dic...
5,358,258
def f18(x, rotation=None, shift=None, shuffle=None): """ Hybrid Function 8 (N=5) Args: x (array): Input vector of dimension 2, 10, 20, 30, 50 or 100. rotation (matrix): Optional rotation matrix. If None (default), the official matrix from the benchmark suite will be used. ...
5,358,259
def shake_256_len(data: bytes, length: int) -> hashes.MessageDigest: """ Convenience function to hash a message. """ return HashlibHash.hash(hashes.shake_256_len(length), data)
5,358,260
def rgb_to_cmyk(color_values: tp.List[float]) -> tp.List[float]: """Converts list of RGB values to CMYK. :param color_values: (list) 3-member RGB color value list :return: (list) 4-member CMYK color value list """ if color_values == [0.0, 0.0, 0.0]: return [0.0, 0.0, 0.0, 1.0] r, g, b =...
5,358,261
def check_family(matrix): """Check the validity of a family matrix for the vine copula. Parameters: ---------- matrix : array The pair-copula families. Returns ------- matrix : array The corrected matrix. """ # TODO: check if the families are in the list of copulas ...
5,358,262
def parse_pgt_programmearray(url): """ Parse filter.js programmearray for pgt information :param url: base url for timetabling system :return: pgt programme name to id dict """ # get filter.js file source = get_filterjs(url) name_to_id = {} # e.g. programmearray[340] [0] = "MSc Fi...
5,358,263
def distance_calc(x1, y1, x2, y2): """Calculates distance between two points""" return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
5,358,264
def LoadNasaData(lat, lon, show= False, selectparms= None): """ Execute a request from NASA API for 10 years of atmospheric data required to prepare daily statistical data used in Solar Insolation calculations """ cmd = formulateRequest(-0.2739, 36.3765, selectparms) jdi = requests.get(cmd...
5,358,265
def mmyy_date_slicer(date_str): """Return start and end point for given date in mm-yy format. :param date_str: date in mmyy format, i.e. "1222" or "0108". :return: start and end date string for a given mmyy formatted date string """ # Initialize output start = "" end = "" if mmyy_...
5,358,266
def constant_arg(name: str): """ Promises that the given arg will not be modified Only affects mutable data types Removes the need to copy the data during inlining """ def annotation(target: typing.Callable): optimiser = _schedule_optimisation(target) optimiser.constant_args.add...
5,358,267
def place_connection(body): # noqa: E501 """Place an connection request from the SDX-Controller # noqa: E501 :param body: order placed for creating a connection :type body: dict | bytes :rtype: Connection """ if connexion.request.is_json: body = Connection.from_dict(connexion.re...
5,358,268
def tag_list(request): """展示所有标签""" return render(request, 'admin/tags_list.html')
5,358,269
def scan_url(urls): """ Scan the url using the API Args: urls: the list of urls Returns: A tuple of a bool indicating if all the urls are safe and a list indicating the safeness of individual urls """ is_safe = True safe_list = [True] * len(urls) safe...
5,358,270
def test_chain_rewrite_save_one_before_last(): """Take chain of length 5, save first node.""" tf.reset_default_graph() tf_dev = tf.device('/cpu:0') tf_dev.__enter__() n = 5 a0, a1, a2, a3, a4 = make_chain_tanh_constant(n) grad = memory_saving_gradients.gradients([a4], [a0], checkpoints=[a2])[0] exp...
5,358,271
def head_to_tree(head, len_, prune, subj_pos, obj_pos): """ Convert a sequence of head indexes into a tree object. """ head = head[:len_].tolist() root = None if prune < 0: nodes = [Tree() for _ in head] for i in range(len(nodes)): h = head[i] nodes[i].i...
5,358,272
def capped_subtraction(x, y): """Saturated arithmetics. Returns x - y truncated to the int64_t range.""" assert_is_int64(x) assert_is_int64(y) if y == 0: return x if x == y: if x == INT_MAX or x == INT_MIN: raise OverflowError( 'Integer NaN: subtracting IN...
5,358,273
def plotInterestPoint(ax): """ """ from pandas import read_excel filepath="../data/points.xls" points=read_excel(filepath, sheet_name="Map3" ) for lon, lat, cname, h_alig in zip(points.lon, points.lat, points.name, points.h_alig): #range(len(cities_name)): ax.plot(...
5,358,274
def evaluate_points(func, begin, total_samps, var_list, attr): """ Inputs: func- the lambda function used to generate the data from the evaluation vector begin- the index to start at in the `attr` array total_samps- the total number of samples to generate var_lis...
5,358,275
def get_username(): """Return username Return a useful username even if we are running under HT-Condor. Returns ------- str : username """ batch_system = os.environ.get('BATCH_SYSTEM') if batch_system == 'HTCondor': return os.environ.get('USER', '*Unknown user*') return os...
5,358,276
def corresponding_chromaticities_prediction_CIE1994(experiment=1): """ Returns the corresponding chromaticities prediction for *CIE 1994* chromatic adaptation model. Parameters ---------- experiment : integer or CorrespondingColourDataset, optional {1, 2, 3, 4, 6, 8, 9, 11, 12} ...
5,358,277
def interpExtrap(x, xp, yp): """numpy.interp interpolation function extended by linear extrapolation.""" y = np.interp(x, xp, yp) y = np.where(x < xp[0], yp[0]+(x-xp[0])*(yp[0]-yp[1])/(xp[0]-xp[1]), y) return np.where(x > xp[-1], yp[-1]+(x-xp[-1])*(yp[-1]-yp[-2]) / (xp[-1]-xp[-2]), y...
5,358,278
def get_operating(): """Get latest operating budgets from shared drive.""" logging.info('Retrieving latest operating budget') command = "smbclient //ad.sannet.gov/dfs " \ + "--user={adname}%{adpass} -W ad -c " \ + "'prompt OFF;"\ + " cd \"FMGT-Shared/Shared/BUDGET/" \ + "Open...
5,358,279
def test_parameter_creation(mock_settings_env_vars) -> None: # type: ignore """Test the creation of parameters to be used in settings.""" aws_parameter = AwsParameterStore(name="Setting", check_settings=True) assert aws_parameter.name == "Setting" with mock.patch.dict(os.environ, {"SETTINGS_NAME": ""...
5,358,280
def removeNodesFromMRMLScene(nodesToRemove): """Removes the input nodes from the scene. Nodes will no longer be accessible from the mrmlScene or from the UI. Parameters ---------- nodesToRemove: List[vtkMRMLNode] or vtkMRMLNode Objects to remove from the scene """ for node in nodesToRemove: removeN...
5,358,281
def get_nome_socio(id): """pega o nome de um livro pelo id.""" if request.method == 'GET': try: socio = db.query_bd('select * from socio where id = "%s"' % id) if socio: print(socio) socio = socio[0] print(socio) ...
5,358,282
def processDeps(element: etree.Element, params: dict = {}) -> None: """Function to NAF deps layer to RDF Args: element: element containing the deps layer params: dict of params to store results Returns: None """ output = params["out"] for dep in element: if dep...
5,358,283
def fit_solution_matrix(weights, design_matrix, cache=None, hash_decimal=10, fit_mat_key=None): """ Calculate the linear least squares solution matrix from a design matrix, A and a weights matrix W S = [A^T W A]^{-1} A^T W Parameters ---------- weights: array-like ndata x ndata matr...
5,358,284
def version_from(schema_path, document_path): """HACK A DID ACK derives non-default 1.1 version from path.""" LOG.debug("xml version derivation flat inspection schema_path=%s", schema_path) if CRVF_PRE_OASIS_SEMANTIC_VERSION in str(schema_path): return CRVF_PRE_OASIS_SEMANTIC_VERSION if CRVF_DEF...
5,358,285
def nessus_vuln_check(request): """ Get the detailed vulnerability information. :param request: :return: """ if request.method == 'GET': id_vul = request.GET['vuln_id'] else: id_vul = '' vul_dat = nessus_report_db.objects.filter(vul_id=id_vul) return render(request, ...
5,358,286
def wait_for_job_completion(namespace, timeout, error_msg): """ This is a WORKAROUND of particular ocsci design choices: I just wait for one pod in the namespace, and then ask for the pod again to get it's name (but it would be much better to just wait for the job to finish instead, then ask for a n...
5,358,287
def delete_data(data, object_name, **kwargs): """ Delete data """ data.delete() is_queryset = isinstance(data, QuerySet) return { "is_queryset": is_queryset, "data": data, "object_name": object_name, }
5,358,288
def test_create_box(client, default_qr_code): """Verify base GraphQL query endpoint""" box_creation_input_string = f"""{{ product_id: 1, items: 9999, location_id: 100000005, comments: "", size_id: 1, ...
5,358,289
def get_g(source): """ Read the Graph from a textfile """ G = {} Grev = {} for i in range(1, N+1): G[i] = [] Grev[i] = [] fin = open(source) for line in fin: v1 = int(line.split()[0]) v2 = int(line.split()[1]) G[v1].append(v2) Grev[v2].append(v1) ...
5,358,290
def _mercator(lat_long): """ Calculate the 2D X and Y coordinates from a set of coordinates based on radius, latitude and longitude using the Mercator projection. :param lat_long: The coordinates of the points to be projected expressed as radius, latitude and longitude. :type lat_long: list[tuple] ...
5,358,291
def subjectForm(request, experiment_id): """ Generates the fourth page, the demographic/participant data form of an experiment. """ experiment = get_object_or_404(Experiment, pk=experiment_id) form = SubjectDataForm(experiment=experiment) t = Template(experiment.demographic_data_page_tpl) ...
5,358,292
def sigma_0(x): """First rotational + shifting mixing function σ_256_0(x) = ROTR_7(x) ⊕ ROTR_18(x) ⊕ SHR_3(x) """ return ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3)
5,358,293
def mat_mult(a=[1.0, 0.0], b=[1.0, 0.0], n=3, result=[0.0, 0.0]): """Multiply two square matrices (not element-wise). Stores the result in `result`. Parameters ---------- a: list b: list n: int : number of rows/columns result: list """ i, j, k = declare('int', 3) for i in ...
5,358,294
def edit_entry(edit_result): """Edit entry""" new_entry = edit_result.copy() edit_key = None edit_value = None date_keys = ["Date"] int_keys = ["Time Spent"] while edit_key not in edit_result: reset_screen("key", "Please type the key you want to edit.") for key, value in edit...
5,358,295
def build_input_files(filename, base_path = 'input_files', out = sys.stdout): """ build_input_files(filename, base_path = 'input_files') takes a 'well-formated' input fileand outputs a directory structure with the properly formated input files created in them. """ calling_dir = os.get...
5,358,296
def srpd(mvec, k, ra, Nmax, w, V): """ Calculate the Steered Response Power Density (SRPD) :param mvec: SHD coefficients for the TF bin to be analysed :param k: Wave number (2*pi*f/c) :param ra: Radius of the microphone array :param Nmax: Maximum SHD order to be used :param w: Diagonal eig...
5,358,297
def batch_inverse(tensor): """ Compute the matrix inverse of a batch of square matrices. This routine is used for removing rotational motion during the molecular dynamics simulation. Taken from https://stackoverflow.com/questions/46595157 Args: tensor (torch.Tensor): Tensor of square matrices ...
5,358,298
def create(**kwds): """ Add data. """ status_code = 200 message = "Successfully added data." articles = [] for a in kwds.get("articles", []): a = Article.query.filter_by(id=a).first() if a: articles.append(a) cols = {"user_id": current_user.id, "name": kwds[...
5,358,299