content
stringlengths
27
928k
path
stringlengths
4
230
size
int64
27
928k
nl_text
stringlengths
21
396k
nl_size
int64
21
396k
nl_language
stringlengths
2
3
nl_language_score
float64
0.04
1
#!/usr/bin/env python """Tests for the export mechanisms of tulip.dumpsmach.""" from __future__ import print_function import logging import networkx as nx from nose.tools import assert_raises from tulip import spec, synth, dumpsmach logging.getLogger('tulip').setLevel('ERROR') logging.getLogger('astutils').setLeve...
tests/dumpsmach_test.py
2,695
Tests for the export mechanisms of tulip.dumpsmach. !/usr/bin/env python print(dumpsmach.python_case(self.dcounter_M)) previous line creates the class `Machine` Sinit -> 0 0 -> 1 invalid input for index 2 in time sequence 1 -> 2 dead-end
238
en
0.509687
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script. Based on Jeff Knupp's Demo + Cookiecutter""" import io import os from setuptools import setup, find_packages def read(*filenames, **kwargs): encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filenam...
setup.py
2,192
The setup script. Based on Jeff Knupp's Demo + Cookiecutter !/usr/bin/env python -*- coding: utf-8 -*- Metadata about the module Load the package's __version__.py module as a dictionary. Via https://github.com/kennethreitz/setup.py/blob/master/setup.py
253
en
0.678242
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/models.ccpm.ipynb (unless otherwise specified). __all__ = ['CCPM'] # Cell import torch from torch import nn from .layers.embedding import EmbeddingLayer from .layers.common import KMaxPooling from .bases.ctr import CTRModel # Internal Cell def get_activation(a...
_docs/py/models/ccpm.py
3,796
Input X: tensor of shape (batch_size, 1, num_fields, embedding_dim) AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/models.ccpm.ipynb (unless otherwise specified). Cell Internal Cell Internal Cell Cell 3 is k-max-pooling size of the last layer shape (bs, 1, field, emb)
276
en
0.613783
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', 'BaxA']) M...
log_mito/model_112.py
16,078
exported from PySB model 'model'
32
en
0.742345
# Copyright 2011 OpenStack Foundation # Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
nova/api/openstack/compute/plugins/v3/pause_server.py
3,430
Enable pause/unpause server actions. Permit Admins to pause the server. Permit Admins to unpause the server. Copyright 2011 OpenStack Foundation Copyright 2013 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain ...
711
en
0.81833
# coding=utf-8 import websocket import datetime import csv import time import logging import redis import json import copy import pytz from hftcoin.mdagent.ccws.configs import REDIS_HOST from hftcoin.mdagent.ccws.configs import TIMEZONE from hftcoin.mdagent.ccws.configs import ExConfigs from hftcoin.mdagent.ccws.confi...
ccws/base.py
5,841
coding=utf-8 self.Logger.debug(msg) data[1] is timestamp divide by 2 to avoid precision
87
en
0.658612
import json import os import re import sys import sysconfig RX_VERSION = re.compile(r"\d\.\d") INSIGHTS = { "_gdbm": "_GDBM_VERSION", "_tkinter": "TCL_VERSION TK_VERSION", "_sqlite3": "sqlite_version version", "_ssl": "OPENSSL_VERSION", "dbm.gnu": "_GDBM_VERSION", "ensurepip": "_PIP_VERSION", ...
src/portable_python/external/_inspect.py
3,442
edge case: py2 reports an odd '.' as srcdir whoever compiled didn't use realpath(tmp) nosec, just simplifying paths
115
en
0.868153
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRrblup(RPackage): """Ridge Regression and Other Kernels for Genomic Selection. Softw...
var/spack/repos/builtin/packages/r-rrblup/package.py
882
Ridge Regression and Other Kernels for Genomic Selection. Software for genomic prediction with the RR-BLUP mixed model (Endelman 2011, <doi:10.3835/plantgenome2011.08.0024>). One application is to estimate marker effects by ridge regression; alternatively, BLUPs can be calculated based on an additive relationship matr...
535
en
0.753238
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
openstack-dashboard/openstack_dashboard/test/integration_tests/basewebobject.py
5,021
Base class for all web objects. Waiting for a text to appear in a certain element very often is actually waiting for a _different_ element with a different text to appear in place of an old element. So a way to avoid capturing stale element reference should be provided for this use case. Better to wrap getting entity ...
1,282
en
0.871154
import os os.environ["CUDA_VISIBLE_DEVICES"] = "1" # import deepspeed # import mpi4py # import pandas import torch import transformers import wandb #%env WANDB_PROJECT=wine_gpt2_Trainer_42 MODEL_NAME = "gpt2-medium" # wandb.login(anonymous='never', key="222a37baaf0c1b0d1499ec003e5c2fe49f97b107") wandb.init() # wan...
extra_code/transformers-gpt2-finetune.py
2,802
import deepspeed import mpi4py import pandas%env WANDB_PROJECT=wine_gpt2_Trainer_42 wandb.login(anonymous='never', key="222a37baaf0c1b0d1499ec003e5c2fe49f97b107") wandb.watch(log='all') Tokenizers wines_raw_train, wines_raw_test = train_test_split(wines_raw,test_size=0.2) wine_encodings_train = tokenizer(wines_raw_trai...
536
en
0.420306
import time from django.db import connections from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command to pause execution until database is available """ def handle(self, *args, **options): self.stdout.write('Waitin...
app/core/management/commands/wait_for_db.py
669
Django command to pause execution until database is available
61
en
0.853355
from .base import * # noqa pylint: disable=wildcard-import, unused-wildcard-import from .base import env # GENERAL # ------------------------------------------------------------------------------ SECRET_KEY = env("DJANGO_SECRET_KEY") ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["coronacircles.de"]) # DA...
settings/production.py
5,737
noqa pylint: disable=wildcard-import, unused-wildcard-import GENERAL ------------------------------------------------------------------------------ DATABASES ------------------------------------------------------------------------------ noqa F405 noqa F405 noqa F405 CACHES ----------------------------------------------...
2,501
en
0.31123
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
setup.py
22,279
Command to tidy up the project root. Registered as cmdclass in setup() so it can be called with ``python setup.py extra_clean``. Compile and build the frontend assets using yarn and webpack. Registered as cmdclass in setup() so it can be called with ``python setup.py compile_assets``. List all available extras Register...
4,185
en
0.764358
#!/usr/bin/env python # Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
pw_watch/py/pw_watch/watch.py
24,653
Process filesystem events and launch builds if necessary. Searches for a build directory, returning the first it finds. Returns true if path matches according to the watcher patterns Sets up an argument parser for pw watch. Find commonly excluded directories, and return them as a [Path] Returns true if this file is in ...
6,881
en
0.883986
import os import string import textwrap import unittest import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging # # DMRIInstall # class DMRIInstall(ScriptedLoadableModule): """ """ helpText = textwrap.dedent( """ The SlicerDMRI extension provides diffusion-related tools inclu...
Modules/Scripted/DMRIInstall/DMRIInstall.py
3,909
Uses ScriptedLoadableModuleWidget base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py DMRIInstall Hide this module if SlicerDMRI is already installed Open links in default browser Apply Button
258
en
0.346724
from django.shortcuts import render,HttpResponse from game.models import Contact from django.contrib import messages # Create your views here. def index(request): context={'variable':"This is sent."} return render(request,'index.html',context) def about(request): return render(request,'about.html'...
views.py
1,020
Create your views here.return HttpResponse("This is about page.")return HttpResponse("This is products page.")return HttpResponse("This is contact page.")
154
en
0.661429
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import account_config_settings import account_move import account_partial_reconcile import account_tax import res_company
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/account_tax_cash_basis/models/__init__.py
222
-*- coding: utf-8 -*- Part of Odoo. See LICENSE file for full copyright and licensing details.
94
en
0.883753
# import libraries from pyspark.sql import SparkSession from pyspark import SparkConf from pyspark.sql.types import * from pyspark.sql.functions import col, count, lit, rand, when import pandas as pd from math import ceil ################################################# # spark config ##############################...
spark_cluster/04_2_HV_basic/HV_v1_NYT_sim1_and_sim3_to_sim2/6200_ML2_HV_v1_NYT_sim1_and_sim3_to_sim2_round5_human_validation.py
15,787
import libraries spark config create spark session check things are working define major topic codes major topic codes for loop (NO 23 IN THE NYT CORPUS)majortopic_codes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 100] read result data from round 3 verdict to integer for the comparison...
4,375
en
0.784428
"""Extra types understood by apitools. This file will be replaced by a .proto file when we switch to proto2 from protorpc. """ import collections import json import numbers from protorpc import message_types from protorpc import messages from protorpc import protojson from apitools.base.py import encoding from apit...
.install/.backup/lib/apitools/base/py/extra_types.py
7,094
A JSON array value. A JSON object value. Messages: Property: A property of a JsonObject. Fields: properties: A list of properties of a JsonObject. Any valid JSON value. A property of a JSON object. Fields: key: Name of the property. value: A JsonValue attribute. Handle the special case of int64 as a string. ...
940
en
0.678448
#!/usr/bin/python3 import click import os import tempfile import filecmp import shutil import difflib import sys import git import shell_utils SOURCE_EXTENSIONS = [".cpp", ".c", ".cxx", ".cc", ".h", ".hxx", ".hpp"] class Colors: HEADER = '\033[95m' BLUE = '\033[94m' CYAN = '\033[96m' GREEN = '\033...
tools/run_clang_format.py
4,665
!/usr/bin/python3 Find all the source files we want to check Check which files have been added or modified by git Recursively walk through the repo and find all the files that meet the extensions criteria Given a list of files, run clang-format on them. Optionally fix the files in place if desired format the file with ...
921
en
0.918375
#filling 2nd form and validating ans import time from selenium import webdriver from selenium.webdriver.common.by import By driver=webdriver.Chrome("../chromedriver.exe") driver.get("https://www.seleniumeasy.com/test/basic-first-form-demo.html") num1=2 num2=3 element1=driver.find_element(By.ID,"sum1").s...
selenium/filling form/form-2.py
698
filling 2nd form and validating ans
35
en
0.699341
from collections import OrderedDict from sympy import Basic, true from devito.tools import as_tuple, is_integer, memoized_meth from devito.types import Dimension __all__ = ['Vector', 'LabeledVector', 'vmin', 'vmax'] class Vector(tuple): """ A representation of an object in Z^n. The elements of a Vect...
devito/ir/support/vector.py
12,353
A Vector that associates a Dimension to each element. A representation of an object in Z^n. The elements of a Vector can be integers or generic SymPy expressions. Notes ----- 1) Vector-scalar comparison If a comparison between a vector and a non-vector is attempted, then the non-vector is promoted to a vector; if thi...
3,939
en
0.872604
#!/usr/bin/env python # -*- coding: utf-8 -*- from threathunter_common.geo.phonelocator import * __author__ = "nebula" def test_phone(): print check_phone_number("+13482345020", None) assert check_phone_number("13482345020", 'CN') assert not check_phone_number("+134823450", None) print get_carrier("...
threathunter_common_python/test/testphone.py
751
!/usr/bin/env python -*- coding: utf-8 -*-
42
en
0.34282
#!/usr/bin/env python3 """Pre-commit hook to verify that all extras are documented in README.rst""" import configparser import re from pathlib import Path repo_dir = Path(__file__).parent.parent.parent config = configparser.ConfigParser(strict=False) config.read(repo_dir / "setup.cfg") all_extra = [] extra_to_exclud...
.circleci/scripts/pre_commit_readme_extra.py
1,189
Pre-commit hook to verify that all extras are documented in README.rst !/usr/bin/env python3
93
en
0.689687
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from lda import LDA def learn_topics(texts, topicnum): # Get vocabulary and word counts. Use the top 10,000 most frequent # lowercase unigrams with at least 3 alphabetical, non-numeric characters, # punctuation treate...
Programs/env_lda.py
1,208
Get vocabulary and word counts. Use the top 10,000 most frequent lowercase unigrams with at least 3 alphabetical, non-numeric characters, punctuation treated as separators. Learn topics. Refresh conrols print frequency.
221
en
0.879337
import os import glob import psycopg2 import pandas as pd import numpy as np from sql_queries import * def process_song_file(cur, filepath): # open song file df = pd.read_json(filepath, lines = True) # insert song record song_data = df[["song_id", "title", "artist_id", "year", "duration"]].values[0] ...
ETL-data-with-postgres/etl.py
3,111
open song file insert song record insert artist record open log file filter by NextSong action convert timestamp column to datetime insert time data records load user table insert user records insert songplay records get songid and artistid from song and artist tables insert songplay record get all files matching exten...
402
en
0.779201
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD from setuptools import setup from catkin_pkg.python_setup import generate_distutils_setup # fetch values from package.xml setup_args = generate_distutils_setup( packages=['soccer_trajectories'], package_dir={'': 'src'}, ) setup(**setup_args)
soccer_trajectories/setup.py
315
! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD fetch values from package.xml
88
en
0.330696
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
model_zoo/official/gnn/gat/preprocess.py
2,312
Generate bin files. preprocess Copyright 2021 Huawei Technologies Co., Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable l...
671
en
0.794616
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'birdview.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtG...
src/visualization_simulator/src/ui/ui_birdview.py
2,436
-*- coding: utf-8 -*- Form implementation generated from reading ui file 'birdview.ui' Created by: PyQt5 UI code generator 5.15.1 WARNING: Any manual changes made to this file will be lost when pyuic5 is run again. Do not edit this file unless you know what you are doing.
273
en
0.902997
from django.utils import timezone from maestros.models import Unidades from maestros_generales.models import Empresas __author__ = 'julian' from django.contrib.gis.db import models import datetime class WaspTypeSensor(models.Model): name = models.CharField(max_length=50) units = models....
rest_waspmote/models.py
2,324
loc = models.PointField(srid=4326)objects = models.GeoManager()timestamp_server = models.DateTimeField()
132
en
0.282704
"""Test length measured in half bytes (nibbles). Nibbles were added in v2.1""" import copy import iso8583 import iso8583.specs import pytest # fmt: off @pytest.mark.parametrize( ["data_enc", "len_enc", "len_type", "max_len", "len_count", "result", "result_f2_len"], [ ("ascii", "ascii", 2, 8, "bytes"...
tests/test_nibbles.py
16,991
Fixed field is missing Fixed field is provided partially Variable field is missing Variable field length is over maximum allowed Variable field is provided partially Fixed field is missing Fixed field is provided partially Variable field length is over maximum allowed Test length measured in half bytes (nibbles). Nibbl...
445
en
0.933005
import argparse import os, sys import os.path as osp import torchvision import numpy as np import torch import torch.nn as nn import torch.optim as optim from torchvision import transforms import network, loss from torch.utils.data import DataLoader import random, pdb, math, copy from tqdm import tqdm from scipy.spatia...
experiments/digit/unsupervised_digit_inspect.py
7,716
inverse_transform = None class InverseTransform(torchvision.transforms.Normalize): """ Undoes the normalization and returns the reconstructed images in the input domain. """ def __init__(self, mean, std): mean = torch.as_tensor(mean) std = torch.as_tensor(std) std_inv = 1 / (std ...
1,534
en
0.235312
# -*- coding: utf-8 -*- # Copyright (c) 2018, SIS and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class Encuesta(Document): pass
encuestaapp/encuestaapp/doctype/encuesta/encuesta.py
248
-*- coding: utf-8 -*- Copyright (c) 2018, SIS and contributors For license information, please see license.txt
110
en
0.783907
""" Tests for Timestamp parsing, aimed at pandas/_libs/tslibs/parsing.pyx """ from datetime import datetime import re from dateutil.parser import parse import numpy as np import pytest from pandas._libs.tslibs import parsing from pandas._libs.tslibs.parsing import parse_time_string import pandas.util._tes...
venv/Lib/site-packages/pandas/tests/tslibs/test_parsing.py
6,830
Tests for Timestamp parsing, aimed at pandas/_libs/tslibs/parsing.pyx Raise on invalid input, don't just return it see gh-9688 see gh-5418 A datetime string must include a year, month and a day for it to be guessable, in addition to being a string that looks like a datetime. see gh-11142 issue 20684
302
en
0.872254
""" This file is also being used by the GalaxyCloudRunner (gcr) Docker image. """ from getpass import getuser from multiprocessing import cpu_count from socket import gethostname from string import Template SLURM_CONFIG_TEMPLATE = ''' # slurm.conf file generated by configurator.html. # Put this file on all nodes of y...
pulsar/scripts/_configure_slurm.py
2,178
This file is also being used by the GalaxyCloudRunner (gcr) Docker image.
73
en
0.960302
# Licensed under a 3-clause BSD style license - see LICENSE.rst import logging import numpy as np from astropy import units as u from astropy.coordinates import Angle from astropy.io import fits from astropy.table import Table from gammapy.maps import MapAxes, MapAxis from gammapy.utils.array import array_stats_str fro...
gammapy/irf/psf/gauss.py
16,206
Triple Gauss analytical PSF depending on energy and theta. To evaluate the PSF call the ``to_energy_dependent_table_psf`` or ``psf_at_energy_and_theta`` methods. Parameters ---------- energy_axis_true : `MapAxis` True energy axis offset_axis : `MapAxis` Offset axis. sigmas : list of 'numpy.ndarray' Triple...
4,259
en
0.471116
# We need to make our string alternating, i. e. si≠si+1. When we reverse substring sl…sr, # we change no more than two pairs sl−1,sl and sr,sr+1. Moreover, one pair should be a # consecutive pair 00 and other — 11. So, we can find lower bound to our answer as maximum # between number of pairs of 00 and number of pair...
Codeforces_problems/Reverse Binary Strings/solution.py
1,173
We need to make our string alternating, i. e. si≠si+1. When we reverse substring sl…sr, we change no more than two pairs sl−1,sl and sr,sr+1. Moreover, one pair should be a consecutive pair 00 and other — 11. So, we can find lower bound to our answer as maximum between number of pairs of 00 and number of pairs of 11....
720
en
0.879149
import numpy as np import cv2 import matplotlib.pylab as plt from keras.preprocessing.image import load_img from keras.models import model_from_json from models import ( create_cam_model, preprocess_image, get_cam_img ) # Define CAM conv layer name CAM_CONV_LAYER = 'cam_conv_layer' def read_model(model_path, wei...
demo.py
3,223
Return your trained CAM model Plot class activation map. Load your pretrained model Train CAM model based on your pretrained model # Arguments model: your pretrained model, CAM model is trained based on this model. Define CAM conv layer name Use your allready trained model Your pretrained ...
934
en
0.832267
#!/usr/bin/python """Plot LFEs of given order parameter.""" import argparse import sys import matplotlib.pyplot as plt from matplotlib import cm from matplotlib import gridspec from matplotlib.ticker import MaxNLocator import numpy as np import pandas as pd from matplotlibstyles import styles from matplotlibstyles ...
scripts/plotting/plot_lfes.py
4,177
Plot LFEs of given order parameter. !/usr/bin/pythonset_labels(ax)mappable = plotutils.create_linear_mappable( cmap, abs(stacking_enes[0]), abs(stacking_enes[-1]))colors = [mappable.to_rgba(abs(e)) for e in stacking_enes]f.savefig(plot_filebase + '.pgf', transparent=True)
276
en
0.272372
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Fabian Affolter <fabian()affolter-engineering.ch>' __copyright__ = 'Copyright 2014 Fabian Affolter' __license__ = """Eclipse Public License - v 1.0 (http://www.eclipse.org/legal/epl-v10.html)""" HAVE_DBUS=True try: import dbus except ImportError: ...
services/dbus.py
1,566
!/usr/bin/env python -*- coding: utf-8 -*-
42
en
0.34282
# encoding: utf-8 import datetime import logging from ckan.common import config from six import text_type from sqlalchemy import Table, select, join, func, and_ import ckan.plugins as p import ckan.model as model log = logging.getLogger(__name__) cache_enabled = p.toolkit.asbool( config.get('ckanext.stats.cache_...
ckanext/stats/stats.py
3,678
encoding: utf-8 by package
26
en
0.959346
import time import numpy as np import os.path as osp import datetime from collections import OrderedDict import torch import torch.nn as nn from torch.utils.tensorboard import SummaryWriter import nni from dassl.data import DataManager from dassl.optim import build_optimizer, build_lr_scheduler from dassl.utils import...
dassl/engine/trainer.py
23,578
A simple neural network composed of a CNN backbone and optionally a head such as mlp for classification. A simple trainer class implementing generic functions. Base class for iterative trainer. A base trainer using labeled data only. A base trainer using both labeled and unlabeled data. In the context of domain adapta...
1,869
en
0.790593
import json import os import pickle import requests import shutil import tempfile import uuid from flask import Blueprint, current_app, jsonify, request, send_file name = 'HTTP' prefix = 'http' storage_enabled = True global storage_path plugin = Blueprint(name, __name__) def register(app, plugin_storage_path=None...
http/__init__.py
5,958
Assign values from config if they are stored in the config, otherwise assign None Check if required parameters are set Send request with given parameters Create UUID for execution Test was executed with any possible outcome Get execution results
245
en
0.781348
""" Copyright 2021 K.M Ahnaf Zamil Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, su...
pogweb/models.py
3,242
An immutable dictionary implementation for query arguments and form data An object that contains information related to the HTTP request Just an object for simulating a redirect The route/endpoint used for that specific request Form data sent via HTTP request HTTP method used for the request Query arguments from the re...
1,449
en
0.843492
# Scrapy settings for amzASINScrapper project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-mi...
amzASINScrapper/amzASINScrapper/settings.py
3,156
Scrapy settings for amzASINScrapper project For simplicity, this file contains only settings considered important or commonly used. You can find more settings consulting the documentation: https://docs.scrapy.org/en/latest/topics/settings.html https://docs.scrapy.org/en/latest/topics/downloader-middleware.html ...
2,860
en
0.619686
"""Test cases around the demo fan platform.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import fan from homeassistant.const import STATE_OFF, STATE_ON from tests.components.fan import common FAN_ENTITY_ID = 'fan.living_room_fan' def get_entity(hass): """...
tests/components/demo/test_fan.py
2,876
Get the fan entity. Initialize components. Test cases around the demo fan platform.
83
en
0.672301
from brownie import AdvancedCollectible, network import pytest from scripts.advanced_collectible.deploy_and_create import deploy_and_create, get_contract from scripts.utils.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account def test_can_create_advanced_collectible(): if network.show_active() not in...
tests/unit/test_advanced_collectible.py
912
getting the requestId value from the requestedCollectible event
63
en
0.672916
# Digital OCEAN FLASK SERVER RECEIVES IMAGE from flask import Flask, request, jsonify import classify import base64 import json import firebase import env # Instantiate Flask app = Flask(__name__) # health check @app.route("/status") def health_check(): return "Running!" # Performing image Recognition on Image...
app.py
1,030
Digital OCEAN FLASK SERVER RECEIVES IMAGE Instantiate Flask health check Performing image Recognition on Image, sent as bytes via POST payload Pass image bytes to classifier Return results as neat JSON object, using
215
en
0.908955
#!/usr/bin/env python3 import os.path import tensorflow as tf import helper import warnings from distutils.version import LooseVersion import project_tests as tests # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.fo...
main.py
7,750
Create the layers for a fully convolutional network. Build skip-layers using the vgg layers. :param vgg_layer3_out: TF Tensor for VGG Layer 3 output :param vgg_layer4_out: TF Tensor for VGG Layer 4 output :param vgg_layer7_out: TF Tensor for VGG Layer 7 output :param num_classes: Number of classes to classify :return:...
2,804
en
0.674212
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
tensorflow/python/keras/_impl/keras/datasets/cifar10.py
2,090
Loads CIFAR10 dataset. Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. CIFAR10 small image classification dataset. Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wit...
806
en
0.802723
""" Django settings for scannerKH project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os ...
scannerKH/scannerKH/settings.py
3,309
Django settings for scannerKH project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ Build paths insid...
990
en
0.679119
# -*- coding: utf-8 -*- import scrapy import re import json from locations.hourstudy import inputoutput class AldiUKSpider(scrapy.Spider): name = "aldiuk" allowed_domains = ['www.aldi.co.uk'] start_urls = ( 'https://www.aldi.co.uk/sitemap/store', ) def parse(self, response): respo...
locations/spiders/aldi_uk.py
1,878
-*- coding: utf-8 -*- properties = { 'name': data['seoData']['name'], 'ref': data['seoData']['name'], 'addr_full': data['seoData']['address']['streetAddress'], 'city': data['seoData']['address']['addressLocality'], 'postcode': data['seoData']['address']['postalCode'], 'country': data['seoData']['address']['addressCount...
561
en
0.206151
""" Django settings for api_drf project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os #...
api_drf/api_drf/settings.py
3,401
Django settings for api_drf project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ Build paths inside ...
1,146
en
0.657073
# See LICENSE for licensing information. # # Copyright (c) 2016-2019 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # import debug from tech import drc, parameter, sp...
compiler/characterizer/measurements.py
9,162
Generates a spice measurement for the delay of 50%-to-50% points of two signals. Generates a spice measurement for the average power between two time points. Base class for spice stimulus measurements. Generates a spice measurement to measure the voltage at a specific time. The time is considered variant with different...
2,183
en
0.870244
from setuptools import find_packages, setup NAME = "popmon" MAJOR = 0 REVISION = 3 PATCH = 8 DEV = False # NOTE: also update version at: README.rst with open("requirements.txt") as f: REQUIREMENTS = f.read().splitlines() # read the contents of abstract file with open("README.rst", encoding="utf-8") as f: lo...
setup.py
2,993
The main setup method. It is responsible for setting up and installing the package. Write package version to version.py. This will ensure that the version in version.py is in sync with us. :param filename: The version.py to write too. :type filename: str NOTE: also update version at: README.rst read the contents o...
520
en
0.868609
# -*- coding: utf-8 -*- """Access to FAIRsharing via its API. .. seealso:: https://beta.fairsharing.org/API_doc """ from typing import Any, Iterable, Mapping, MutableMapping, Optional import pystow import requests import yaml from tqdm import tqdm __all__ = [ "ensure_fairsharing", "load_fairsharing", "...
src/fairsharing_client/api.py
4,932
A client for programmatic access to the FAIRsharing private API. Instantiate the client and get an appropriate JWT token. :param login: FAIRsharing username :param password: Corresponding FAIRsharing password :param base_url: The base URL Get the FAIRsharing registry. Get the JWT. Iterate over all FAIRsharing records....
634
en
0.865712
# # Copyright 2022 DMetaSoul # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
demo/search/src/eval/evaluation.py
7,430
Compute MRR metric Args: p_qids_to_relevant_passageids (dict): dictionary of query-passage mapping Dict as read in with load_reference or load_reference_from_stream p_qids_to_ranked_candidate_passages (dict): dictionary of query-passage candidates Returns: dict: dictionary of metrics {'MRR': <MRR Score>} Load c...
2,290
en
0.670816
""" Copyright [2021] [DenyS] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
multibar/core/variants/lib_info.py
1,248
Annotation for filtering global variables. Parameters: ----------- value: :class:`TypeVar` A parameter that stores the value of a certain variable. Features: --------- * `__repr__`: repr(Info()) Development Information. * `__str__`: str(Info()) | Info() Will output the value that stores value. Copyright ...
859
en
0.724577
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ # Examples: # url(r'^$', 'simpleproject.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^simpleapp/', includ...
simpleproject/simpleproject/urls.py
344
Examples: url(r'^$', 'simpleproject.views.home', name='home'), url(r'^blog/', include('blog.urls')),
100
en
0.288443
# -*- coding: utf-8 -*- """ Demonstrates basic use of LegendItem """ import initExample ## Add path to library (just for examples; you do not need this) import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np win = pg.plot() win.setWindowTitle('pyqtgraph example: BarGraphItem') # # option1:...
examples/Legend.py
1,378
Demonstrates basic use of LegendItem -*- coding: utf-8 -*- Add path to library (just for examples; you do not need this) option1: only for .plot(), following c1,c2 for example----------------------- win.addLegend(frame=False, colCount=2) bar graph curve scatter plot option2: generic method--------------------------...
342
en
0.508734
class TimedData(object): """ Struttura dati per eventi accompagnati da un informazione temporale discreta (timestamp o intervallo) """ def __init__(self, data, time, timestamp=True): """ I parametri di input sono - "data": il dato che si vuole memorizzare (di qualsiasi natura) ...
timed_structures.py
9,525
Array di oggetti TimedData Struttura dati per eventi accompagnati da un informazione temporale discreta (timestamp o intervallo) I parametri di input sono - "data": il dato che si vuole memorizzare (di qualsiasi natura) - "time": l'informazione temporale associata al dato (numero intero) - "timestamp": flag booleana. S...
3,464
it
0.973974
""" This problem was asked by Amazon. Given a matrix of 1s and 0s, return the number of "islands" in the matrix. A 1 represents land and 0 represents water, so an island is a group of 1s that are neighboring whose perimeter is surrounded by water. For example, this matrix has 4 islands. 1 0 0 0 0 0 0 1 1 0 0 1 1 0 0...
DailyCodingProblem/84_Amazon_Find_Islands_From_Matrix.py
1,963
This problem was asked by Amazon. Given a matrix of 1s and 0s, return the number of "islands" in the matrix. A 1 represents land and 0 represents water, so an island is a group of 1s that are neighboring whose perimeter is surrounded by water. For example, this matrix has 4 islands. 1 0 0 0 0 0 0 1 1 0 0 1 1 0 0 0 0...
455
en
0.978998
# The following comments couldn't be translated into the new config version: # untracked PSet maxEvents = {untracked int32 input = 2} #include "Configuration/ReleaseValidation/data/Services.cff" # include "Configuration/StandardSequences/data/FakeConditions.cff" # untracked PSet options = { # include "FWC...
L1Trigger/RegionalCaloTrigger/test/rctInputTest_cfg.py
1,912
The following comments couldn't be translated into the new config version: untracked PSet maxEvents = {untracked int32 input = 2}include "Configuration/ReleaseValidation/data/Services.cff" include "Configuration/StandardSequences/data/FakeConditions.cff" untracked PSet options = { include "FWCore/Framework...
738
en
0.641233
from twisted.internet import defer from signing.processor import expose class SayHiImplementation(object): """ Responds with 'hello, %s' % arg """ @expose def say_hi(self, identifier): d = defer.Deferred() d.callback('hello, %s' % identifier) return d
signing/processorimpl/sayhiimplementation.py
297
Responds with 'hello, %s' % arg
31
en
0.390518
# -*- coding: utf-8 -*- from collections import namedtuple from subprocess import check_output import click from .utils import cd try: from subprocess import call as run except ImportError: from subprocess import run class VueJs(object): """ Provide subprocess call to `npm` and `vue-cli` """ ...
python_vuejs/vuejs.py
2,963
Provide subprocess call to `npm` and `vue-cli` Click entry point: vue-cli commands group By convention all new cli has a cli function with a pass statement Install vue-cli Node and npm version checker Init vue project via vue-cli vue-cli version checker Build Vue.js project via npm Check if node > 5 and npm > 3 are ins...
382
en
0.656057
import numpy as np from PIL import Image, ImageDraw from scipy import interpolate, ndimage, stats, signal, integrate, misc from astropy.io import ascii, fits from astropy.wcs import WCS from astropy.coordinates import SkyCoord import astropy.units as u import astropy.constants as c import corner as triangle # formerly...
schmidt_funcs.py
26,232
this returns -1*alpha, and optionally kappa and errors uses maximum likelihood to estimation to determine power-law and error From Clauset et al. 2010 Complimentary CDF for cdf2 (not normalized to 1) Value at b is total amount above b. NOT a general averaging function return bin centers (lin and log) (smooth) bootstrap...
7,099
en
0.649984
"""A word2vec implementation using Tensorflow and estimators.""" import os from collections import defaultdict import logging import tensorflow as tf # from tensorflow.python import debug as tf_debug # pylint: disable=E0611 import word2vec.utils.datasets as datasets_utils import word2vec.models.word2vec as w2v_mod...
word2vec/estimators/word2vec.py
6,383
Tensorflow implementation of Word2vec. Initialize vocab dictionaries. Create vocabulary-related data. Load a previously saved vocabulary file. Train Word2Vec. Return the number of items in vocabulary. Since we use len(word_freq_dict) as the default index for UKN in the index_table, we have to add 1 to the length A wor...
1,062
en
0.553409
import argparse import collections import fnmatch import os.path import pprint import re import sys ####################### ### OSimStatsHelper ### ####################### class OSimStatsHelper: """Takes a list of stats and returns a stat containing their summation by each sample.""" @staticmethod def sumS...
analysis/opensimulator-stats-analyzer/src/osta/osta.py
7,766
OSimStatsHelper print "Summing %s" % (totalStat['name'])lineRe = re.compile("(.* .*) - (.*) : (\d+)[ ,]([^:]*)")lineRe = re.compile("(.* .*) - (.*) : (?P<abs>[\d\.-]+)(?: (?:\D+))?(?P<delta>[\d\.-]+)?") OSimStatsCorpus Set structure category : { container : { stat : { 'abs' : { 'values' : [], ...
723
en
0.170001
import os import sys import errno import random import pickle import numpy as np import torch import torchvision import torch.nn.functional as F from torch.utils.data.dataset import Dataset from torch.utils.data import Dataset, DataLoader from torch.utils.data.sampler import BatchSampler from torchvision.datasets imp...
src/pytorch-template/old/models/baseline_3D_single.py
1,851
============================================================================== Network definition============================================================================== print("size", x.size()) print("size", x.size())
223
en
0.332277
#!/usr/bin/python """Cartesian execution of options for experiments""" import itertools from pprint import pprint import os # GROUPS = [ # ('train', {'type': 'option', # 'order': 0, # 'values': ['train5k']}), # ('lang', {'type': 'option', # 'order': 1, # ...
scripts/cartesian_experiments.py
5,102
!/usr/bin/python GROUPS = [ ('train', {'type': 'option', 'order': 0, 'values': ['train5k']}), ('lang', {'type': 'option', 'order': 1, 'values': 'hungarian,basque,french,korean,polish,swedish'.split(',')}), ('infuse', {'type': 'option', 'o...
2,354
en
0.112564
# Copyright (c) 2020 The Regents of the University of Michigan # All rights reserved. # This software is licensed under the BSD 3-Clause License. import garnett import hoomd import hoomd.hpmc # Vertices of a cube cube_verts = [[-1, -1, -1], [-1, -1, 1], [-1, 1, 1], [-1, 1, -1], [1, -1, -1], [1, -1, 1], ...
examples/example-hpmc.py
1,633
Copyright (c) 2020 The Regents of the University of Michigan All rights reserved. This software is licensed under the BSD 3-Clause License. Vertices of a cube Restore a snapshot from saved data Create a HOOMD snapshot from a garnett Trajectory frame
249
en
0.830578
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import json import xmind import logging from xmind2testcase2021.zentao import xmind_to_zentao_csv_file from xmind2testcase2021.testlink import xmind_to_testlink_xml_file from xmind2testcase2021.utils import xmind_testcase_to_json_file from xmind2testcase2021.utils import xmi...
samples.py
2,152
!/usr/bin/env python _*_ coding:utf-8 _*_ 1、testcases import file (1) zentao (2) testlink 2、 testcases json file (1) testsuite (2) testcase 3、test dict/json data (1) testsuite (2) testcase (3) xmind file
203
en
0.212822
# =============================================================================== # Copyright 2015 Jake Ross # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses...
pychron/dvc/meta_repo.py
21,588
example cocktail.json { "chronology": "2016-06-01 17:00:00", "j": 4e-4, "j_err": 4e-9 } :return: =============================================================================== Copyright 2015 Jake Ross Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in co...
1,975
en
0.636685
#!/usr/bin/python import glob,re,sys,math,pyfits import numpy as np import utils if len(sys.argv) < 2: print '\nconvert basti SSP models to ez_gal fits format' print 'Run in directory with SED models for one metallicity' print 'Usage: convert_basti.py ez_gal.ascii\n' sys.exit(2) fileout = sys.argv[1]...
ezgal/scripts/convert_basti.py
4,032
!/usr/bin/python try to extract meta data out of fileout split on _ but get rid of the extension look for sfh tau? metallicity imf does the file with masses exist? read it in! extract the age from the filename and convert to years read in this file if this is the first file, generate the data table convert to ergs/s/an...
693
en
0.833455
import path4gmns as pg from time import time def test_download_sample_data_sets(): pg.download_sample_data_sets() def test_find_shortest_path(): load_demand = False network = pg.read_network(load_demand) print('\nshortest path (node id) from node 1 to node 2, ' +network.find_shortest_path...
tests/demo.py
6,457
validation using DTALite retrieve the shortest path under a specific mode (which must be defined in settings.yaml) find agent paths under a specific mode defined in settings.yaml, say, w (i.e., walk) network.find_path_for_agents('w') or network.find_path_for_agents('walk') output unique agent paths to a csv file if ...
1,745
en
0.776592
"""Define family of algorithms and make them interchangeable The algorithms vary independetly from the clients using it. This class implements to IngestorInterface and dynamically invoke a suitable algorithm (strategy.algorithm()), through parse() abstract method. i.e. it is independent of how an algorithm is im...
QuoteEngine/Ingestor.py
1,241
Define family of algorithms & dynamically invoke the one of interest Define family of algorithms and make them interchangeable The algorithms vary independetly from the clients using it. This class implements to IngestorInterface and dynamically invoke a suitable algorithm (strategy.algorithm()), through parse() abstr...
611
en
0.870318
from infoblox_netmri.utils.utils import locate, to_snake from infoblox_netmri.api.exceptions.netmri_exceptions import NotImplementedException class Broker(object): """ Base class for broker instances, provides methods for API requests. And return responces wrapped with specific class :param client...
infoblox_netmri/api/broker/broker.py
3,759
Base class for broker instances, provides methods for API requests. And return responces wrapped with specific class :param client: InfobloxNetMRI client Returns full API method name using controller name **Input** :param method: method name :return: full API path Generate full path to specific RemoteModel instance ...
1,009
en
0.638667
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
swift/proxy/controllers/account.py
8,404
WSGI controller for account requests HTTP DELETE request handler. Handler for HTTP GET/HEAD requests. HTTP POST request handler. HTTP PUT request handler. Copyright (c) 2010-2012 OpenStack Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with th...
1,722
en
0.940426
""" ASGI config for backend project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault(...
backend/backend/asgi.py
407
ASGI config for backend project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
213
en
0.716352
from thriftpy2.thrift import TType class ThriftError(Exception): """ Base Exception defined by `aiothrift` """ class ConnectionClosedError(ThriftError): """Raised if connection to server was closed.""" class PoolClosedError(ThriftError): """Raised when operating on a closed thrift connection pool""" ...
aiothrift/errors.py
1,428
Raised if connection to server was closed. Raised when operating on a closed thrift connection pool Application level thrift exceptions. Base Exception defined by `aiothrift`
174
en
0.95419
""" From https://zenodo.org/record/3539363 """ import re def section_text(text): """Splits text into sections. Assumes text is in a radiology report format, e.g.: COMPARISON: Chest radiograph dated XYZ. IMPRESSION: ABC... Given text like this, it will output text from each section, ...
src/data/datasets/mimic_cxr/section_parser.py
10,850
Splits text into sections. Assumes text is in a radiology report format, e.g.: COMPARISON: Chest radiograph dated XYZ. IMPRESSION: ABC... Given text like this, it will output text from each section, where the section type is determined by the all caps header. Returns a three element tuple: sections ...
3,241
en
0.580666
# SVG Path specification parser import re from . import path COMMANDS = set('MmZzLlHhVvCcSsQqTtAa') UPPERCASE = set('MZLHVCSQTA') COMMAND_RE = re.compile("([MmZzLlHhVvCcSsQqTtAa])") FLOAT_RE = re.compile("[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?") def _tokenize_path(pathdef): for x in COMMAND_RE.split(pathdef)...
svg/path/parser.py
6,912
SVG Path specification parser In the SVG specs, initial movetos are absolute, even if specified as 'm'. This is the default behavior here as well. But if you pass in a current_pos variable, the initial moveto will be relative to that current_pos. This is useful. Reverse for easy use of .pop() New command. Used by S and...
1,582
en
0.907254
# -*- coding: utf-8 -*- from tests.integration import TestsBase from chsdi.models.bod import Catalog from sqlalchemy.orm import scoped_session, sessionmaker from chsdi.views.catalog import create_digraph from chsdi.lib.filters import filter_by_geodata_staging class TestCatalogService(TestsBase): def test_nodes_...
tests/integration/test_catalog.py
6,699
-*- coding: utf-8 -*- We fix staging for next calls to prod Get catalog Get flat catalog table entries Check if every node in the catalog is in view_catalog of db reset staging to previous setting We fix staging for next calls to prod Get catalog Get LayersConfig for this topic Check if all layers of catalog are in Lay...
363
en
0.681486
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use ...
elasticsearch/_sync/client/text_structure.py
8,785
Finds the structure of a text file. The text file must contain data that is suitable to be ingested into Elasticsearch. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/find-structure.html>`_ :param text_files: :param charset: The text’s character set. It must be a character set that is supported...
5,438
en
0.789518
""" Tests for the utils module """ import datetime import operator as op from math import ceil from types import SimpleNamespace import pytest import pytz from mitol.common.utils import ( is_near_now, has_equal_properties, first_or_none, first_matching_item, max_or_none, partition_to_lists, ...
main/utils_test.py
10,561
Assert that all_equal returns True if all of the provided args are equal to each other Assert that all_unique returns True if all of the items in the iterable argument are unique test for chunks test that chunks works on non-list iterables too Test that filter_dict_by_key_set returns a dict with only the given keys fir...
2,060
en
0.659819
""" Test admin tools """ from io import BytesIO, TextIOWrapper import csv import six import zipfile import django from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.test import Client, TestCase import gdpr_assist from .gdpr_assist_tests_app.factories...
tests/test_admin.py
10,416
Test admin tools Django 1.8 support - no client.force_login Django 1.9+ Django 1.8 support - redirects include host Django 1.9+ Django 1.8 support - redirects include host Django 1.9+ Django 1.8 support - redirects include host Django 1.9+ Request an object we know doesn't exist Creating 4 records: * One matching in ...
589
en
0.853858
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
sdks/python/apache_beam/io/textio.py
25,387
A ``PTransform`` for reading a ``PCollection`` of text files. Reads a ``PCollection`` of text files or file patterns and and produces a ``PCollection`` of strings. Parses a text file as newline-delimited elements, by default assuming UTF-8 encoding. Supports newline delimiters '\n' and '\r\n'. This implementation ...
11,982
en
0.821316
import os import click from flask import Flask, render_template from flask_wtf.csrf import CSRFError from telechat.extensions import db, login_manager, csrf, moment from telechat.blueprints.auth import auth_bp from telechat.blueprints.chat import chat_bp from telechat.blueprints.admin import admin_bp from telechat.bl...
telechat/__init__.py
3,161
程序工厂:创建 Flask 程序,加载配置,注册扩展、蓝图等程序包 生成虚拟数据 初始化数据库结构 注册需要的蓝图程序包到 Flask 程序实例 app 中 注册需要的CLI命令程序包到 Flask 程序实例 app 中 注册需要的错误处理程序包到 Flask 程序实例 app 中 注册需要的扩展程序包到 Flask 程序实例 app 中 数据库 ORM 登录状态管理 CSRF 令牌管理 时间格式化管理 Bad Request 客户端请求的语法错误,服务器无法理解 Not Found 服务器无法根据客户端的请求找到资源(网页) Internal Server Error 服务器内部错误,无法完成请求 CSRF 验证失败 确认删除...
413
zh
0.98702
"""Configuration format loaders""" import locale import os from abc import ABC, abstractmethod import yaml from pydantic import create_model def load_configuration(configuration_file_path, parameters_file_path, bundles): """Combines the configuration and parameters and build the configuration object""" mappin...
applauncher/configuration.py
3,210
Base configuration loader YML Format parser and config loader By using the loaded parameters and loaded config, build the final configuration object Check if the value is actually a string or not Prase the config file and build a dictionary For YML, the source it the file path Combines the configuration and parameters ...
555
en
0.48322
from sqlalchemy import and_ from sqlalchemy import exc from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import INT from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import Sequence from sqlalchemy import sql from sqlalchemy import String from sqlalchemy import t...
test/sql/test_insert_exec.py
15,732
test for consistent insert behavior across dialects regarding the inline=True flag, lower-case 't' tables. Tests the inserted_primary_key and lastrow_has_id() functions. Inserts a row into a table, returns the full list of values INSERTed including defaults that fired off on the DB side and detects rows that had defaul...
591
en
0.730241
import re import connexion import logging import auslib from os import path from flask import request from flask_compress import Compress from auslib.web.admin.views.problem import problem from auslib.web.admin.views.validators import BalrogRequestBodyValidator from raven.contrib.flask import Sentry from specsynthase....
auslib/web/admin/base.py
3,154
pragma: no cover When running under uwsgi, paths will not get decoded before hitting the app. We need to handle this ourselves in certain fields, and adding converters for them is the best way to do this. Connexion's error handling sometimes breaks when parameters contain unicode characters (https://github.com/zalando/...
583
en
0.822537
# -*- coding: utf-8 -*- # FLEDGE_BEGIN # See: http://fledge.readthedocs.io/ # FLEDGE_END """ Test end to end flow with: Notification service with Threshold in-built rule plugin notify-python35 delivery channel plugin """ import os import time import subprocess import http.client import json f...
tests/system/python/e2e/test_e2e_notification_service_with_plugins.py
14,103
Define the template file for fogbench readings This fixture clone a south repo and starts south instance add_south: Fixture that starts any south service with given configuration remove_data_file: Fixture that remove data file created during the tests remove_directories: Fixture that remove directories created during ...
1,072
en
0.864584
# coding: utf-8 # ... import symbolic tools weak_formulation = load('pyccel.symbolic.gelato', 'weak_formulation', True, 2) glt_function = load('pyccel.symbolic.gelato', 'glt_function', True, 3) Grad = load('pyccel.symbolic.gelato', 'Grad', False, 1) Curl = load('pyccel.symbolic.gelato', 'Curl', False, 1) ...
src_old/tests/scripts/lambda/pdes/2d/ex10.py
1,321
coding: utf-8 ... import symbolic tools ... ... Laplace ... ... ... ... ...
75
en
0.359709
from py12306.log.base import BaseLog from py12306.helpers.func import * @singleton class OrderLog(BaseLog): # 这里如果不声明,会出现重复打印,目前不知道什么原因 logs = [] thread_logs = {} quick_log = [] MESSAGE_REQUEST_INIT_DC_PAGE_FAIL = '请求初始化订单页面失败' MESSAGE_SUBMIT_ORDER_REQUEST_FAIL = '提交订单失败,错误原因 {} \n' MESS...
py12306/log/order_log.py
3,989
这里如果不声明,会出现重复打印,目前不知道什么原因
25
zh
0.999665
""" DarkWorldsMetricMountianOsteric.py Custom evaluation metric for the 'Observing Dark Worlds' competition. [Description of metric, or reference to documentation.] Update: Made for the training set only so users can check there results from the training c @Author: David Harvey Created: 22 August 2012 """ import nu...
Chapter5_LossFunctions/DarkWorldsMetric.py
20,353
Only works for number of halso > 1The number of possible different combThe array of combinationsI will pass backTHe array of the distancesfor all possible combinationsThe vector of distancesI will pass backPick a combination of true and predicted Input for the permutatiosn, 01 number halos or 012For the index of the di...
5,197
en
0.839903
#!/usr/bin/env python3 # methodological_experiment.py import sys, os, csv import numpy as np import pandas as pd import versatiletrainer2 import metaselector import matplotlib.pyplot as plt from scipy import stats def first_experiment(): sourcefolder = '../data/' metadatapath = '../metadata/mastermetadata...
variation/methodological_experiment.py
31,068
This function applies model a to b, and vice versa, and returns a couple of measures of divergence: notably lost accuracy and z-tranformed spearman correlation. This function gets several possible measures of divergence between two models. Loads metadata, selects instances for the positive and negative classes (using a...
3,499
en
0.899121
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
lingvo/core/ops/random_ops_test.py
2,279
Tests for random_ops. Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by a...
927
en
0.842928
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyFastjsonschema(PythonPackage): """Fast JSON schema validator for Python.""" homepage = "https://github.c...
var/spack/repos/builtin/packages/py-fastjsonschema/package.py
557
Fast JSON schema validator for Python. Copyright 2013-2022 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: (Apache-2.0 OR MIT)
229
en
0.593844
import pytest from datetime import date, datetime from dateutil.relativedelta import relativedelta from django.contrib.auth.models import User from records.models import ( Category, Record, Budget, OUTCOME, INCOME, SAVINGS, tmz) from records.month_control import MonthControl, MonthControlWithBudget @pytest.fixt...
moneyforecast/tests/records/fixtures.py
5,073
Return a date which is used to determine the end month the recurrence should occur Main category of income type Return a MonthControl object for the current date. Important: currently any Record fixture should come before month_control Return a MonthControlWithBudget object for the current date. Important: currently ...
966
en
0.875139
'''Ask two student's grade, inform 3 possible averages. average : > 7 = Approved < 7 & > 5 = Recovery < 5 = Failed ''' g1 = float(input("Inform the student's first grade: ")) g2 = float(input("Inform the student's second grade: ")) average = (g1 + g2)/2 # how to calculate the avarege grade between two values if averag...
Python-codes-CeV/40-Average.py
615
Ask two student's grade, inform 3 possible averages. average : > 7 = Approved < 7 & > 5 = Recovery < 5 = Failed how to calculate the avarege grade between two values
167
en
0.894869