code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import json from school.models.class_model import Class from school.models.school_model import School from django.urls.base import reverse from rest_framework.test import APITestCase from country.models import Country, City from django.contrib.auth import get_user_model User = get_user_model() class SchoolTests(APITe...
bookorbooks/school/tests/school_tests.py
import json from school.models.class_model import Class from school.models.school_model import School from django.urls.base import reverse from rest_framework.test import APITestCase from country.models import Country, City from django.contrib.auth import get_user_model User = get_user_model() class SchoolTests(APITe...
0.468304
0.230119
import configparser import psycopg2 from sql_queries import copy_table_queries, insert_table_queries import os import pandas as pd import numpy as np from datetime import datetime import pytz import dateutil from timezonefinder import TimezoneFinder import requests from bs4 import BeautifulSoup from utils import ( ...
etl.py
import configparser import psycopg2 from sql_queries import copy_table_queries, insert_table_queries import os import pandas as pd import numpy as np from datetime import datetime import pytz import dateutil from timezonefinder import TimezoneFinder import requests from bs4 import BeautifulSoup from utils import ( ...
0.169956
0.131507
from testplan.testing.multitest import MultiTest, testsuite, testcase from testplan.testing.multitest.base import Categories from testplan import Testplan from testplan.common.utils.testing import ( check_report, log_propagation_disabled ) from testplan.report.testing import TestReport, TestGroupReport, TestCaseRe...
test/functional/testplan/testing/multitest/test_pre_post_steps.py
from testplan.testing.multitest import MultiTest, testsuite, testcase from testplan.testing.multitest.base import Categories from testplan import Testplan from testplan.common.utils.testing import ( check_report, log_propagation_disabled ) from testplan.report.testing import TestReport, TestGroupReport, TestCaseRe...
0.531939
0.441854
from absl import flags import tensorflow as tf import numpy as np from tqdm import tqdm from pyrsostf.data import MNIST from pyrsostf.nn import AutoencoderLayer, corrupt_data_with_noise, transform_tf_variable from pyrsostf.plots import compare_images, save_image_collection, plot_autoencoder_weights flags.DEFINE_integ...
autoencoders/mnist_stacked_denoising_autoencoder.py
from absl import flags import tensorflow as tf import numpy as np from tqdm import tqdm from pyrsostf.data import MNIST from pyrsostf.nn import AutoencoderLayer, corrupt_data_with_noise, transform_tf_variable from pyrsostf.plots import compare_images, save_image_collection, plot_autoencoder_weights flags.DEFINE_integ...
0.890187
0.489686
import pickle import re import sys import time import pytest from loguru import logger from .conftest import default_threading_excepthook class NotPicklable: def __getstate__(self): raise pickle.PicklingError("You shall not serialize me!") def __setstate__(self, state): pass class NotUnpi...
tests/test_add_option_enqueue.py
import pickle import re import sys import time import pytest from loguru import logger from .conftest import default_threading_excepthook class NotPicklable: def __getstate__(self): raise pickle.PicklingError("You shall not serialize me!") def __setstate__(self, state): pass class NotUnpi...
0.307462
0.321753
import requests, json, sys, re, time, warnings, argparse from datetime import datetime warnings.filterwarnings("ignore") parser=argparse.ArgumentParser(description="Python script using Redfish API to either get controllers / disks / virtual disks / supported RAID levels or create virtual disk") parser.add...
CreateVirtualDiskREDFISH.py
import requests, json, sys, re, time, warnings, argparse from datetime import datetime warnings.filterwarnings("ignore") parser=argparse.ArgumentParser(description="Python script using Redfish API to either get controllers / disks / virtual disks / supported RAID levels or create virtual disk") parser.add...
0.304042
0.089058
from bc125csv import main from bc125csv.scanner import Channel, VirtualScanner, ScannerException from bc125csv.tests.base import BaseTestCase, mock class NonRespondingScanner(VirtualScanner): def writeread(self, command): return "" class ErrorRespondingScanner(VirtualScanner): def writeread(self, comm...
bc125csv/tests/test_scanner.py
from bc125csv import main from bc125csv.scanner import Channel, VirtualScanner, ScannerException from bc125csv.tests.base import BaseTestCase, mock class NonRespondingScanner(VirtualScanner): def writeread(self, command): return "" class ErrorRespondingScanner(VirtualScanner): def writeread(self, comm...
0.585457
0.341171
import argparse, sys, os import operator from Bio import SeqIO def make_rundir( run, verbose ): if os.path.exists( run ): if os.path.isdir( run ): if verbose: sys.stderr.write(run + ' already exists\n') return os.path.abspath(run) else: raise OSE...
bin/run_split_augustus.py
import argparse, sys, os import operator from Bio import SeqIO def make_rundir( run, verbose ): if os.path.exists( run ): if os.path.isdir( run ): if verbose: sys.stderr.write(run + ' already exists\n') return os.path.abspath(run) else: raise OSE...
0.188548
0.161783
import shutil import time import pytest from btclib_node import Node from btclib_node.chains import RegTest from btclib_node.config import Config from btclib_node.constants import NodeStatus from btclib_node.main import update_chain from tests.helpers import generate_random_chain, get_random_port, wait_until @pytes...
tests/functional/p2p/test_download.py
import shutil import time import pytest from btclib_node import Node from btclib_node.chains import RegTest from btclib_node.config import Config from btclib_node.constants import NodeStatus from btclib_node.main import update_chain from tests.helpers import generate_random_chain, get_random_port, wait_until @pytes...
0.210279
0.273096
import numpy as np import tensorflow as tf from copy import deepcopy from tf_rl.common.utils import create_checkpoint class DDPG: def __init__(self, ggnn, critic, node_info, num_action, params): self.params = params self.num_action = num_action self.eval_flg = False self.index_time...
tf_rl/examples/NerveNet/agent/DDPG.py
import numpy as np import tensorflow as tf from copy import deepcopy from tf_rl.common.utils import create_checkpoint class DDPG: def __init__(self, ggnn, critic, node_info, num_action, params): self.params = params self.num_action = num_action self.eval_flg = False self.index_time...
0.873485
0.301716
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse f...
sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/operations/_aliases_operations.py
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse f...
0.855851
0.108378
import logging import os import tempfile import threading from contextlib import contextmanager from distutils.dir_util import copy_tree from funcy import cached_property, retry, suppress, wrap_with from dvc.compat import fspath from dvc.config import NoRemoteError, NotDvcRepoError from dvc.exceptions import ( Ch...
dvc/external_repo.py
import logging import os import tempfile import threading from contextlib import contextmanager from distutils.dir_util import copy_tree from funcy import cached_property, retry, suppress, wrap_with from dvc.compat import fspath from dvc.config import NoRemoteError, NotDvcRepoError from dvc.exceptions import ( Ch...
0.516108
0.077622
import string import datetime import sys import hashlib def cracker(passarg): starttime = datetime.datetime.now() chars = ['#','@','$','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', '...
permutation.py
import string import datetime import sys import hashlib def cracker(passarg): starttime = datetime.datetime.now() chars = ['#','@','$','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', '...
0.084909
0.261325
import random from faker import Faker from common.constants import CreateCourseConstants fake = Faker("Ru-ru") class CreateCourse: def __init__( self, full_course_name=None, short_course_name=None, end_day=None, end_month=None, end_year=None, end_hour=Non...
models/create_course.py
import random from faker import Faker from common.constants import CreateCourseConstants fake = Faker("Ru-ru") class CreateCourse: def __init__( self, full_course_name=None, short_course_name=None, end_day=None, end_month=None, end_year=None, end_hour=Non...
0.522202
0.119152
test_get_app_tables = [ { "alias": "_DBID_MEMBERSHIP", "created": "2020-09-01T20:16:15Z", "defaultSortFieldId": 4, "defaultSortOrder": "ASC", "description": "", "id": "abcdef", "keyFieldId": 3, "name": "Members", "nextFieldId": 100, "nextRecordId": 250, "pluralRecordName": ...
test/test_quickbase/test_data.py
test_get_app_tables = [ { "alias": "_DBID_MEMBERSHIP", "created": "2020-09-01T20:16:15Z", "defaultSortFieldId": 4, "defaultSortOrder": "ASC", "description": "", "id": "abcdef", "keyFieldId": 3, "name": "Members", "nextFieldId": 100, "nextRecordId": 250, "pluralRecordName": ...
0.407098
0.386503
import pytest import os, glob import micasense.capture as capture import micasense.image as image @pytest.fixture() def files_dir(): return os.path.join('data', '0000SET', '000') @pytest.fixture() def file_list(): return glob.glob(os.path.join(files_dir(), 'IMG_0000_*.tif')) @pytest.fixture() def bad_file_l...
tests/test_capture.py
import pytest import os, glob import micasense.capture as capture import micasense.image as image @pytest.fixture() def files_dir(): return os.path.join('data', '0000SET', '000') @pytest.fixture() def file_list(): return glob.glob(os.path.join(files_dir(), 'IMG_0000_*.tif')) @pytest.fixture() def bad_file_l...
0.464902
0.488771
from __future__ import absolute_import, division, print_function, unicode_literals import os import sys import time import cv2 import numpy as np sys.path.append('../../webapp') from candysorter.models.images.calibrate import ImageCalibrator from candysorter.models.images.detect import CandyDetector from candysort...
setup/script/camera_tune.py
from __future__ import absolute_import, division, print_function, unicode_literals import os import sys import time import cv2 import numpy as np sys.path.append('../../webapp') from candysorter.models.images.calibrate import ImageCalibrator from candysorter.models.images.detect import CandyDetector from candysort...
0.452536
0.076684
import psutil import time import math import gitlab import os from argparse import ArgumentParser import configparser MODULE_NAME = "ptl: Automatically log time in GitLab issue tracker for COMP23311 at UoM." __version__ = "0.1.0" def print_config(token, project_id, issue_id): print("--:CONFIG:--\n" + "🎫 TOKEN:" + ...
ptl/__main__.py
import psutil import time import math import gitlab import os from argparse import ArgumentParser import configparser MODULE_NAME = "ptl: Automatically log time in GitLab issue tracker for COMP23311 at UoM." __version__ = "0.1.0" def print_config(token, project_id, issue_id): print("--:CONFIG:--\n" + "🎫 TOKEN:" + ...
0.167559
0.050144
from enum import IntEnum, unique @unique # Just to avoid potential developer errors class PacketType(IntEnum): # Handshake packets PROTOCOL_REQUEST = 0 PROTOCOL_RESPONSE = 1 # Universe; server → client SERVER_DISCONNECT = 2 CONNECT_SUCCESS = 3 CONNECT_FAILURE = 4 HANDSHAKE_CHALLENGE =...
starrypy/enums.py
from enum import IntEnum, unique @unique # Just to avoid potential developer errors class PacketType(IntEnum): # Handshake packets PROTOCOL_REQUEST = 0 PROTOCOL_RESPONSE = 1 # Universe; server → client SERVER_DISCONNECT = 2 CONNECT_SUCCESS = 3 CONNECT_FAILURE = 4 HANDSHAKE_CHALLENGE =...
0.336767
0.079531
import requests import json from utils.validate_input import validate_required_field_existence from torre.constants import API_URL, URL, SEARCH_URL GENOME_USERNAME_FIELD = 'genome_username' LOCATION_FIELD = 'location' ROLE_FIELD = 'role' SALARY_RANGE_FIELD = 'salaryRange' MIN_SALARY_RANGE_FIELD = 'min' MAX_SALARY_RANG...
back/torre/skill_differences.py
import requests import json from utils.validate_input import validate_required_field_existence from torre.constants import API_URL, URL, SEARCH_URL GENOME_USERNAME_FIELD = 'genome_username' LOCATION_FIELD = 'location' ROLE_FIELD = 'role' SALARY_RANGE_FIELD = 'salaryRange' MIN_SALARY_RANGE_FIELD = 'min' MAX_SALARY_RANG...
0.374791
0.169956
from datetime import datetime from elasticsearch_dsl import DocType, Date, String, construct_field user_field = construct_field('object') user_field.property('name', 'string', fields={'raw': construct_field('string', index='not_analyzed')}) class Repository(DocType): owner = user_field created_at = Date() ...
test_elasticsearch_dsl/test_integration/test_document.py
from datetime import datetime from elasticsearch_dsl import DocType, Date, String, construct_field user_field = construct_field('object') user_field.property('name', 'string', fields={'raw': construct_field('string', index='not_analyzed')}) class Repository(DocType): owner = user_field created_at = Date() ...
0.783906
0.360602
from __future__ import print_function import time import datetime from dateutil.relativedelta import relativedelta import numpy as np import math from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import GRU from keras.layers import Dropout from keras.lay...
model.py
from __future__ import print_function import time import datetime from dateutil.relativedelta import relativedelta import numpy as np import math from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import GRU from keras.layers import Dropout from keras.lay...
0.84994
0.451085
import argparse as ap import logging import os import sys import pandas logger = logging.getLogger() logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(...
Docker image/dh-importer/create_tsv_output.py
import argparse as ap import logging import os import sys import pandas logger = logging.getLogger() logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(...
0.293607
0.163079
import asyncio import discord import random import itertools from typing import Iterator from async_timeout import timeout from discord.ext.commands import Context from discord import Guild, TextChannel from app.ext.performance import run_in_threadpool from .YTDLSource import YTDLSource from app.controlle...
app/ext/music/Player.py
import asyncio import discord import random import itertools from typing import Iterator from async_timeout import timeout from discord.ext.commands import Context from discord import Guild, TextChannel from app.ext.performance import run_in_threadpool from .YTDLSource import YTDLSource from app.controlle...
0.584271
0.153613
from __future__ import absolute_import import json import logging import os import threading import time import datetime import socket import traceback import platform import commands import atexit from requests_futures import sessions def setInterval(interval): def decorator(function): def wrapper(*args, ...
splunk_eventgen/logger/splunk_hec_logging_handler.py
from __future__ import absolute_import import json import logging import os import threading import time import datetime import socket import traceback import platform import commands import atexit from requests_futures import sessions def setInterval(interval): def decorator(function): def wrapper(*args, ...
0.379608
0.049336
from collections import defaultdict from gzip import GzipFile from math import modf from sys import stderr from xml.sax import make_parser from xml.sax.handler import feature_external_ges from xml.dom import pulldom cpuClock = 3579545 vdpClock = cpuClock * 6 masterClock = cpuClock * 960 vdpTicksPerLine = 1368 # The...
Contrib/tas/omr2txt.py
from collections import defaultdict from gzip import GzipFile from math import modf from sys import stderr from xml.sax import make_parser from xml.sax.handler import feature_external_ges from xml.dom import pulldom cpuClock = 3579545 vdpClock = cpuClock * 6 masterClock = cpuClock * 960 vdpTicksPerLine = 1368 # The...
0.367724
0.270227
import os import uuid from dateutil.tz import tzutc from datetime import datetime import string import random from azure_devtools.perfstress_tests import PerfStressTest from azure.core.exceptions import ResourceNotFoundError from azure.data.tables import EdmType, EntityProperty from azure.data.tables import TableSer...
sdk/tables/azure-data-tables/tests/perfstress_tests/_base.py
import os import uuid from dateutil.tz import tzutc from datetime import datetime import string import random from azure_devtools.perfstress_tests import PerfStressTest from azure.core.exceptions import ResourceNotFoundError from azure.data.tables import EdmType, EntityProperty from azure.data.tables import TableSer...
0.414425
0.089455
from absl import logging from scenic.dataset_lib.big_transfer import ops as pp_ops from scenic.dataset_lib.big_transfer import registry import tensorflow.compat.v1 as tf TPU_SUPPORTED_DTYPES = [ tf.bool, tf.int32, tf.int64, tf.bfloat16, tf.float32, tf.complex64, tf.uint32 ] def get_preprocess_fn(pp_pipeline,...
scenic/dataset_lib/big_transfer/builder.py
from absl import logging from scenic.dataset_lib.big_transfer import ops as pp_ops from scenic.dataset_lib.big_transfer import registry import tensorflow.compat.v1 as tf TPU_SUPPORTED_DTYPES = [ tf.bool, tf.int32, tf.int64, tf.bfloat16, tf.float32, tf.complex64, tf.uint32 ] def get_preprocess_fn(pp_pipeline,...
0.860823
0.517266
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps, ImageTransform import fastestimator as fe from fastestimator.architecture.pytorch import ResNet9 from fastestimator.dataset.data.cifair10 import load_data from fastestimator.op.numpyop import NumpyOp from fastestimator.op.numpyop.meta imp...
apphub/automl/rand_augment/rand_augment_torch.py
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps, ImageTransform import fastestimator as fe from fastestimator.architecture.pytorch import ResNet9 from fastestimator.dataset.data.cifair10 import load_data from fastestimator.op.numpyop import NumpyOp from fastestimator.op.numpyop.meta imp...
0.808143
0.474449
"""Some common combinations""" import string from pyparsing import Empty, FollowedBy, LineEnd, Literal, OneOrMore, Optional from pyparsing import Suppress, SkipTo, Word, ZeroOrMore from regparser.grammar import atomic from regparser.grammar.utils import keep_pos, Marker period_section = Suppress(".") + atomic.sectio...
regparser/grammar/unified.py
"""Some common combinations""" import string from pyparsing import Empty, FollowedBy, LineEnd, Literal, OneOrMore, Optional from pyparsing import Suppress, SkipTo, Word, ZeroOrMore from regparser.grammar import atomic from regparser.grammar.utils import keep_pos, Marker period_section = Suppress(".") + atomic.sectio...
0.761538
0.442275
import sympy as sp import numpy as np import scipy.sparse.linalg as lin import array_to_latex as a2l from time import time x = sp.Symbol('x', real=True) fe = {} rnd = {} func = {} def matvec(u_hat, f_hat, A, B, alpha, method): """Compute matrix vector product Parameters ---------- u_hat : Function ...
docs/paper/CG/CGpaper_dirichlet.py
import sympy as sp import numpy as np import scipy.sparse.linalg as lin import array_to_latex as a2l from time import time x = sp.Symbol('x', real=True) fe = {} rnd = {} func = {} def matvec(u_hat, f_hat, A, B, alpha, method): """Compute matrix vector product Parameters ---------- u_hat : Function ...
0.737253
0.717556
HTML = '''\ <a href="#javascript-disabled" class="alime{extra_class}" \ style="width: {width}em"> <span class="sr-only">(Click to send mail)</span> <!-- Automatically generated (https://github.com/cduck/alime) --> {chars} </a>\ ''' HTML_BETWEEN_STATIC = '\n\n<br>\n\n' CHAR = '<span><span>{char}</span></span...
alime/templates.py
HTML = '''\ <a href="#javascript-disabled" class="alime{extra_class}" \ style="width: {width}em"> <span class="sr-only">(Click to send mail)</span> <!-- Automatically generated (https://github.com/cduck/alime) --> {chars} </a>\ ''' HTML_BETWEEN_STATIC = '\n\n<br>\n\n' CHAR = '<span><span>{char}</span></span...
0.411584
0.116588
# Generates a dependancy file # > generateDeps.py path [rel] [obj] [indent] # Path is the path to (recursivley) generate dependancies for, defaults to the current directory # Rel is the path that the files will be relative to, this should be the directory that a "deps.json" is output # Obj will be merged with the dep...
tools/generateDeps.py
# Generates a dependancy file # > generateDeps.py path [rel] [obj] [indent] # Path is the path to (recursivley) generate dependancies for, defaults to the current directory # Rel is the path that the files will be relative to, this should be the directory that a "deps.json" is output # Obj will be merged with the dep...
0.350977
0.32544
from pathlib import Path import os import dj_database_url if os.path.exists('env.py'): import env # noqa # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - un...
main/settings.py
from pathlib import Path import os import dj_database_url if os.path.exists('env.py'): import env # noqa # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - un...
0.461502
0.054249
import logging import os from functools import lru_cache from typing import List, Mapping, Optional import pandas as pd from .utils import get_version from ..constants import ( RELATION_COLUMNS, RELATION_ID, RELATION_PREFIX, SOURCE_ID, SOURCE_PREFIX, TARGET_ID, TARGET_PREFIX, ) from ..gett...
src/pyobo/api/relations.py
import logging import os from functools import lru_cache from typing import List, Mapping, Optional import pandas as pd from .utils import get_version from ..constants import ( RELATION_COLUMNS, RELATION_ID, RELATION_PREFIX, SOURCE_ID, SOURCE_PREFIX, TARGET_ID, TARGET_PREFIX, ) from ..gett...
0.691706
0.113629
import urllib.request from urllib.parse import quote from bs4 import BeautifulSoup filePathMaster = "/home/RRADAR/rob.adams/Documents/News_Web_Crawler_Scrapers/" filenameSHPCulandBeh = filePathMaster +"Crawled Data SHP Culture and Behaviour/" filenameSHPCourt = filePathMaster + "Crawled Data SHP Court/" filenameHSE = ...
WebCrawler.py
import urllib.request from urllib.parse import quote from bs4 import BeautifulSoup filePathMaster = "/home/RRADAR/rob.adams/Documents/News_Web_Crawler_Scrapers/" filenameSHPCulandBeh = filePathMaster +"Crawled Data SHP Culture and Behaviour/" filenameSHPCourt = filePathMaster + "Crawled Data SHP Court/" filenameHSE = ...
0.042444
0.108661
import os import subprocess import urlparse from osbuild import command from osbuild import config from osbuild import utils def _chdir(func): def wrapped(*args, **kwargs): orig_cwd = os.getcwd() os.chdir(args[0].local) result = func(*args, **kwargs) os.chdir(orig_cwd) ...
osbuild/git.py
import os import subprocess import urlparse from osbuild import command from osbuild import config from osbuild import utils def _chdir(func): def wrapped(*args, **kwargs): orig_cwd = os.getcwd() os.chdir(args[0].local) result = func(*args, **kwargs) os.chdir(orig_cwd) ...
0.45423
0.088387
from rest_framework import serializers from club.models import Story, Segment, User, Comment, UsersRelStories class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_only=True, required=False) cla...
club/serializers.py
from rest_framework import serializers from club.models import Story, Segment, User, Comment, UsersRelStories class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_only=True, required=False) cla...
0.550366
0.122839
class Cart: def __init__(self, position, direction): self.position = position self.direction = direction self.turn = 0 self.crashed = False carts, tracks = [], {} for y, line in enumerate(open('inputs/day13.input')): for x, char in enumerate(line): if char in ">v<^": ...
2018/day13.py
class Cart: def __init__(self, position, direction): self.position = position self.direction = direction self.turn = 0 self.crashed = False carts, tracks = [], {} for y, line in enumerate(open('inputs/day13.input')): for x, char in enumerate(line): if char in ">v<^": ...
0.376967
0.37912
import TCGMain as tc from modules import pyrand def runtests(): #rngtest() #packtest() openpacktest('Quacker Booster', print_res=True) def rngtest(): test_input_list = ('50', '30', '10', '5', '3', '1.5', '.5') perfect_results = {x+'%': int(float(x)*100) for x in test_input_list} test_input_l...
TCGTests.py
import TCGMain as tc from modules import pyrand def runtests(): #rngtest() #packtest() openpacktest('Quacker Booster', print_res=True) def rngtest(): test_input_list = ('50', '30', '10', '5', '3', '1.5', '.5') perfect_results = {x+'%': int(float(x)*100) for x in test_input_list} test_input_l...
0.235108
0.440409
import math import random from sqlite3 import Error import discord from discord.ext import commands, tasks from helper.sql import SQLFunctions from discord.ext.commands.cooldowns import BucketType def xpfier(n): return round((n/0.0002725)**1.15) def levefier(xp): return math.floor(xp**(1/1.15) * 0.0002725) ...
cogs/voice.py
import math import random from sqlite3 import Error import discord from discord.ext import commands, tasks from helper.sql import SQLFunctions from discord.ext.commands.cooldowns import BucketType def xpfier(n): return round((n/0.0002725)**1.15) def levefier(xp): return math.floor(xp**(1/1.15) * 0.0002725) ...
0.52074
0.144934
import random from datetime import datetime from django.contrib.sites.shortcuts import get_current_site from django.contrib.staticfiles.storage import staticfiles_storage from django.contrib.syndication.views import add_domain from django.http import HttpResponseForbidden, JsonResponse from django.template.loader impo...
emojiweather/commands/views.py
import random from datetime import datetime from django.contrib.sites.shortcuts import get_current_site from django.contrib.staticfiles.storage import staticfiles_storage from django.contrib.syndication.views import add_domain from django.http import HttpResponseForbidden, JsonResponse from django.template.loader impo...
0.37777
0.089694
from __future__ import generators, unicode_literals import sys if sys.version_info[0] < 3: str = unicode import Tkinter as tkinter import ttk import tkFileDialog as filedialog import tkSimpleDialog as simpledialog else: import tkinter import tkinter.ttk as ttk import tkinter.filedialog a...
template-mvvm.py
from __future__ import generators, unicode_literals import sys if sys.version_info[0] < 3: str = unicode import Tkinter as tkinter import ttk import tkFileDialog as filedialog import tkSimpleDialog as simpledialog else: import tkinter import tkinter.ttk as ttk import tkinter.filedialog a...
0.28577
0.065605
import sys import pygame from bullet import Bullet from alien import Alien from time import sleep #检测按键 def check_events(ship,settings,bullets,screen,play_button,state): #相应按键和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame....
game_functions.py
import sys import pygame from bullet import Bullet from alien import Alien from time import sleep #检测按键 def check_events(ship,settings,bullets,screen,play_button,state): #相应按键和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame....
0.173743
0.123656
from p5 import * from random import randint class Sun: """An object which can't move on its own and attracts other objects""" def __init__(self, pos, mass): self.pos = pos self.mass = mass self.g = 1 def show(self): fill(240,230,140) no_stroke() circle(self...
2.Forces/gravitational_attraction.py
from p5 import * from random import randint class Sun: """An object which can't move on its own and attracts other objects""" def __init__(self, pos, mass): self.pos = pos self.mass = mass self.g = 1 def show(self): fill(240,230,140) no_stroke() circle(self...
0.683314
0.680812
from .compat import (set_urllib_method, singledispatch, urlencode, urllib_http_error_cls, urllib_request) from .http import Response __all__ = ['send', 'send_async'] @singledispatch def send(client, request): """Given a client, send a :class:`~snug.http.Request`, returning a :class:`~snu...
snug/clients.py
from .compat import (set_urllib_method, singledispatch, urlencode, urllib_http_error_cls, urllib_request) from .http import Response __all__ = ['send', 'send_async'] @singledispatch def send(client, request): """Given a client, send a :class:`~snug.http.Request`, returning a :class:`~snu...
0.763307
0.106691
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import time import os import sys from multiprocessing import Pool from time import sleep # HACK: cross py2-py3 compatible version try: from queue import Queue except ...
output_template/python/usb_camera_demo.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import time import os import sys from multiprocessing import Pool from time import sleep # HACK: cross py2-py3 compatible version try: from queue import Queue except ...
0.439747
0.109706
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'VPNConnectionIkeConfigArgs', 'VPNConnectionIpsecConfigArgs', ] @pulumi.input_type class VPNConnectionIkeConfigArgs: def __init__(__self__, *, ...
sdk/python/pulumi_ucloud/ipsecvpn/_inputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'VPNConnectionIkeConfigArgs', 'VPNConnectionIpsecConfigArgs', ] @pulumi.input_type class VPNConnectionIkeConfigArgs: def __init__(__self__, *, ...
0.857976
0.140631
from tqdm.auto import tqdm from unittest import TestCase from embiggen.edge_prediction import edge_prediction_evaluation from embiggen import get_available_models_for_edge_prediction, get_available_models_for_node_embedding from embiggen.edge_prediction.edge_prediction_model import AbstractEdgePredictionModel from embi...
tests/test_edge_prediction_pipeline.py
from tqdm.auto import tqdm from unittest import TestCase from embiggen.edge_prediction import edge_prediction_evaluation from embiggen import get_available_models_for_edge_prediction, get_available_models_for_node_embedding from embiggen.edge_prediction.edge_prediction_model import AbstractEdgePredictionModel from embi...
0.801781
0.276156
import urlparse import json import httplib2 from keystoneclient.v2_0 import services from tests import utils class ServiceTests(utils.TestCase): def setUp(self): super(ServiceTests, self).setUp() self.TEST_REQUEST_HEADERS = { 'X-Auth-Token': 'aToken', 'User-Agent': 'pytho...
tests/v2_0/test_services.py
import urlparse import json import httplib2 from keystoneclient.v2_0 import services from tests import utils class ServiceTests(utils.TestCase): def setUp(self): super(ServiceTests, self).setUp() self.TEST_REQUEST_HEADERS = { 'X-Auth-Token': 'aToken', 'User-Agent': 'pytho...
0.36557
0.203233
def reccomend_blood_pressure(blood_pressure): recommendation_to_user = "" if blood_pressure >= 140 / 90: if blood_pressure >= 160 / 100: recommendation_to_user += "Blood Pressure is in danger levels, these levels are in need of medication\n" else: recommendation_to_user ...
src/models/recommendations.py
def reccomend_blood_pressure(blood_pressure): recommendation_to_user = "" if blood_pressure >= 140 / 90: if blood_pressure >= 160 / 100: recommendation_to_user += "Blood Pressure is in danger levels, these levels are in need of medication\n" else: recommendation_to_user ...
0.280616
0.574454
import unittest import json from pysliceplorer import hyperslice_core as hs_core class TestHyperSlice(unittest.TestCase): def f(self, x1, x2, x3, x4): return x1 + x2 + x3 + x4 def test_min_max(self): with self.assertRaises(Exception): hs_core(self.f, 20, 10, 4, (0, 0, 0, 0), 10) ...
test/test_hyperslice.py
import unittest import json from pysliceplorer import hyperslice_core as hs_core class TestHyperSlice(unittest.TestCase): def f(self, x1, x2, x3, x4): return x1 + x2 + x3 + x4 def test_min_max(self): with self.assertRaises(Exception): hs_core(self.f, 20, 10, 4, (0, 0, 0, 0), 10) ...
0.577734
0.670001
import six from heat.engine.constraint import common_constraints as cc from heat.tests import common from heat.tests import utils class TestIPConstraint(common.HeatTestCase): def setUp(self): super(TestIPConstraint, self).setUp() self.constraint = cc.IPConstraint() def test_validate_ipv4_f...
heat/tests/constraints/test_common_constraints.py
import six from heat.engine.constraint import common_constraints as cc from heat.tests import common from heat.tests import utils class TestIPConstraint(common.HeatTestCase): def setUp(self): super(TestIPConstraint, self).setUp() self.constraint = cc.IPConstraint() def test_validate_ipv4_f...
0.690142
0.538194
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile import pandas as pd import six import tensorflow as tf import tensorflow_lattice as tfl flags = tf.flags FLAGS = flags.FLAGS # Run mode of the program. flags.DEFINE_string( "run...
examples/uci_census.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile import pandas as pd import six import tensorflow as tf import tensorflow_lattice as tfl flags = tf.flags FLAGS = flags.FLAGS # Run mode of the program. flags.DEFINE_string( "run...
0.723212
0.255158
import sys import pdfkit import filters from flask import Flask, render_template, request, abort, make_response from flask_cors import CORS app = Flask(__name__) CORS(app) # Add the Jinja filters. app.jinja_env.filters['title'] = filters.title app.jinja_env.filters['is_dict'] = filters.is_dict app.jinja_env.filters...
main.py
import sys import pdfkit import filters from flask import Flask, render_template, request, abort, make_response from flask_cors import CORS app = Flask(__name__) CORS(app) # Add the Jinja filters. app.jinja_env.filters['title'] = filters.title app.jinja_env.filters['is_dict'] = filters.is_dict app.jinja_env.filters...
0.369998
0.127517
import requests api_key = 'xxxxxx' # replace with a valid bingmap api key base_url = "https://dev.virtualearth.net/REST/v1/Imagery/Map/" zoom = "20" maptype = "Aerial" size = "600,600" def bing_getaerial(latlon): url = base_url + maptype + '/' + latlon + '/' + zoom + '?mapsize=' + size + "&fmt=png&key=" + api_k...
bingapi.py
import requests api_key = 'xxxxxx' # replace with a valid bingmap api key base_url = "https://dev.virtualearth.net/REST/v1/Imagery/Map/" zoom = "20" maptype = "Aerial" size = "600,600" def bing_getaerial(latlon): url = base_url + maptype + '/' + latlon + '/' + zoom + '?mapsize=' + size + "&fmt=png&key=" + api_k...
0.265595
0.156878
import os import xml.etree.ElementTree as ET from pathlib import Path from typing import Optional import pandas as pd import pytest def _get_xml_templates(): suffix = "_template.xml" current_dir = os.path.dirname(os.path.realpath(__file__)) return [ _.rstrip(suffix) for _ in os.listdir(Pa...
test/unittests/iotools/converters/adni_to_bids/test_adni_json.py
import os import xml.etree.ElementTree as ET from pathlib import Path from typing import Optional import pandas as pd import pytest def _get_xml_templates(): suffix = "_template.xml" current_dir = os.path.dirname(os.path.realpath(__file__)) return [ _.rstrip(suffix) for _ in os.listdir(Pa...
0.706596
0.294202
# imports import numpy as __numpy # functions def denominator(x, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """ denominator(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) rational number denominato...
resources/dot_PyCharm/system/python_stubs/-762174762/numpy/core/_rational_tests.py
# imports import numpy as __numpy # functions def denominator(x, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """ denominator(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) rational number denominato...
0.731059
0.281572
from collections import defaultdict from datetime import date from dateutil.relativedelta import relativedelta from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Sum from django.shortcuts import redirect, render from django.urls import reverse, reverse_lazy from django.views import...
silverstrike/views/categories.py
from collections import defaultdict from datetime import date from dateutil.relativedelta import relativedelta from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Sum from django.shortcuts import redirect, render from django.urls import reverse, reverse_lazy from django.views import...
0.557604
0.121738
from abc import ABC, abstractmethod from typing import Dict import pandas as pd import logging from dgi.code2graph.process_facts import ConsumeFacts # Author information __author__ = "<NAME>" __license__ = "Apache 2.0" __version__ = "1.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Research Prototy...
dgi/code2graph/abstract_graph_builder.py
from abc import ABC, abstractmethod from typing import Dict import pandas as pd import logging from dgi.code2graph.process_facts import ConsumeFacts # Author information __author__ = "<NAME>" __license__ = "Apache 2.0" __version__ = "1.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Research Prototy...
0.864625
0.219526
import logging from datetime import datetime from playhouse.migrate import * from peewee import ProgrammingError from sanicms import load_config config = load_config() db = PostgresqlDatabase(**config['DB_CONFIG']) migrator = PostgresqlMigrator(db) logger = logging.getLogger('sanic') class MigrationRecord(Model):...
migrations.py
import logging from datetime import datetime from playhouse.migrate import * from peewee import ProgrammingError from sanicms import load_config config = load_config() db = PostgresqlDatabase(**config['DB_CONFIG']) migrator = PostgresqlMigrator(db) logger = logging.getLogger('sanic') class MigrationRecord(Model):...
0.566978
0.076684
import os import sys import pandas as pd if os.path.exists("./Mephisto"): # noqa sys.path.append(os.path.abspath("./Mephisto")) # noqa print("WARNING: Loading Mephisto from local directory") # noqa from mephisto.core.data_browser import DataBrowser as MephistoDataBrowser # isort:skip from mephisto.core...
annotators/pay_workers.py
import os import sys import pandas as pd if os.path.exists("./Mephisto"): # noqa sys.path.append(os.path.abspath("./Mephisto")) # noqa print("WARNING: Loading Mephisto from local directory") # noqa from mephisto.core.data_browser import DataBrowser as MephistoDataBrowser # isort:skip from mephisto.core...
0.223462
0.097777
(dp0 VOpera 9.7 p1 (dp2 S'summary_display' p3 S'8/14' p4 sS'total_runs' p5 L2L sS'summary_score' p6 I57 sS'results' p7 (dp8 S'du' p9 (dp10 S'score' p11 I100 sS'raw_score' p12 I1 sS'display' p13 S'yes' p14 ssS'parscriptimage' p15 (dp16 g11 I100 sg12 I1 sg13 g14 ssS'cacheexp' p17 (dp18 g11 I100 sg12 I1 sg13 g14 ssS'cache...
static_mode/network_2.py
(dp0 VOpera 9.7 p1 (dp2 S'summary_display' p3 S'8/14' p4 sS'total_runs' p5 L2L sS'summary_score' p6 I57 sS'results' p7 (dp8 S'du' p9 (dp10 S'score' p11 I100 sS'raw_score' p12 I1 sS'display' p13 S'yes' p14 ssS'parscriptimage' p15 (dp16 g11 I100 sg12 I1 sg13 g14 ssS'cacheexp' p17 (dp18 g11 I100 sg12 I1 sg13 g14 ssS'cache...
0.145085
0.05113
import os import sys import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import metrics from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split def transLabel(data): """ 将文字变量转化为数字变量 """ data["label_code"] = pd.Categoric...
pr/binary_model_evaluation/evaluation_example_code.py
import os import sys import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import metrics from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split def transLabel(data): """ 将文字变量转化为数字变量 """ data["label_code"] = pd.Categoric...
0.485844
0.515376
import os import sys AMBARI_AGENT_HOST_DIR = "AMBARI_AGENT_HOST_DIR" SYMLINKS_TXT = "symlinks.txt" VERSIONS_TXT = "versions.txt" # main method to parse arguments from user and start work def main(): if len(sys.argv) <= 1: sys.exit(-1) args = sys.argv[1:] do_work(args) def extrakt_var_from_pythonpath(na...
ambari-server/src/main/resources/stacks/PERF/1.0/hooks/before-INSTALL/scripts/distro-select.py
import os import sys AMBARI_AGENT_HOST_DIR = "AMBARI_AGENT_HOST_DIR" SYMLINKS_TXT = "symlinks.txt" VERSIONS_TXT = "versions.txt" # main method to parse arguments from user and start work def main(): if len(sys.argv) <= 1: sys.exit(-1) args = sys.argv[1:] do_work(args) def extrakt_var_from_pythonpath(na...
0.07038
0.10697
import json from argparse import ArgumentParser from os import linesep from pathlib import Path import numpy as np from cascade.dismod.db.wrapper import DismodFile, get_engine from cascade.dismod.metrics import data_records from cascade.dismod.constants import INTEGRAND_COHORT_COST INTEGRANDS = list(INTEGRAND_COHORT...
examples/add_integrands.py
import json from argparse import ArgumentParser from os import linesep from pathlib import Path import numpy as np from cascade.dismod.db.wrapper import DismodFile, get_engine from cascade.dismod.metrics import data_records from cascade.dismod.constants import INTEGRAND_COHORT_COST INTEGRANDS = list(INTEGRAND_COHORT...
0.49292
0.108307
import winsound from time import sleep class TextToMorseParser: _standard_duration = 150 # Set Duration To 300 ms == 0.3 second _standard_freq = 1000 # Set Frequency To 900 Hertz <EMAIL> def duration(self, duration): self._standard_duration = duration @property def frquency(self, f...
text2morse/Parser.py
import winsound from time import sleep class TextToMorseParser: _standard_duration = 150 # Set Duration To 300 ms == 0.3 second _standard_freq = 1000 # Set Frequency To 900 Hertz <EMAIL> def duration(self, duration): self._standard_duration = duration @property def frquency(self, f...
0.650467
0.20351
import torch import torch.nn as nn from torch import optim from multiprocessing import cpu_count import numpy as np import argparse import os import time from networks import LightSpeech from dataset import DataLoader, collate_fn from dataset import LightSpeechDataset from loss import LigthSpeechLoss import utils impo...
train.py
import torch import torch.nn as nn from torch import optim from multiprocessing import cpu_count import numpy as np import argparse import os import time from networks import LightSpeech from dataset import DataLoader, collate_fn from dataset import LightSpeechDataset from loss import LigthSpeechLoss import utils impo...
0.753285
0.222616
import numpy as np import pandas as pd from estimagic.estimation.msm_weighting import get_weighting_matrix from estimagic.exceptions import INVALID_SENSITIVITY_MSG from estimagic.inference.msm_covs import cov_optimal from estimagic.inference.msm_covs import cov_robust from estimagic.inference.shared import process_pan...
estimagic/sensitivity/msm_sensitivity.py
import numpy as np import pandas as pd from estimagic.estimation.msm_weighting import get_weighting_matrix from estimagic.exceptions import INVALID_SENSITIVITY_MSG from estimagic.inference.msm_covs import cov_optimal from estimagic.inference.msm_covs import cov_robust from estimagic.inference.shared import process_pan...
0.895134
0.648494
import quex.input.regular_expression.core as regular_expression import quex.input.files.mode_option as mode_option import quex.input.files.code_fragment as code_fragment from quex.input.files.specifier.mode import ModeParsed from quex.input.code.core import CodeUser from qu...
quex/input/files/mode.py
import quex.input.regular_expression.core as regular_expression import quex.input.files.mode_option as mode_option import quex.input.files.code_fragment as code_fragment from quex.input.files.specifier.mode import ModeParsed from quex.input.code.core import CodeUser from qu...
0.444685
0.150153
from math import sqrt from random import randint, random from Animal import Animal, Food def distance(x1, y1, x2, y2): return sqrt((x1-x2)**2 + (y1-y2)**2) class World(object): MAX_ANIMAL_COUNT = 100 MAX_EATING_DISTANCE = 20 EATING_VALUE = 0.03 def __init__(self, width, height): self.w...
World.py
from math import sqrt from random import randint, random from Animal import Animal, Food def distance(x1, y1, x2, y2): return sqrt((x1-x2)**2 + (y1-y2)**2) class World(object): MAX_ANIMAL_COUNT = 100 MAX_EATING_DISTANCE = 20 EATING_VALUE = 0.03 def __init__(self, width, height): self.w...
0.628407
0.31695
import sys import os import datetime import numpy import scipy.stats from sklearn.preprocessing import RobustScaler, StandardScaler, MinMaxScaler import pandas as pd class DescriptiveStatistic: def __init__(self, path=None): self.data_frame = pd.read_csv(path, delimiter=',', index_col=False, ) s...
testability/descriptive_statistics.py
import sys import os import datetime import numpy import scipy.stats from sklearn.preprocessing import RobustScaler, StandardScaler, MinMaxScaler import pandas as pd class DescriptiveStatistic: def __init__(self, path=None): self.data_frame = pd.read_csv(path, delimiter=',', index_col=False, ) s...
0.393502
0.367866
from .api import FIELD_INDEXES, COLUMN_TO_NAME, get_index_name, get_column_name, regex from django.db import models from django.db.models.sql import aggregates as sqlaggregates from django.db.models.sql.constants import LOOKUP_SEP, MULTI, SINGLE, LHS_ALIAS,\ JOIN_TYPE, LHS_JOIN_COL, TABLE_NAME, RHS_JOIN_COL from dj...
dbindexer/compiler.py
from .api import FIELD_INDEXES, COLUMN_TO_NAME, get_index_name, get_column_name, regex from django.db import models from django.db.models.sql import aggregates as sqlaggregates from django.db.models.sql.constants import LOOKUP_SEP, MULTI, SINGLE, LHS_ALIAS,\ JOIN_TYPE, LHS_JOIN_COL, TABLE_NAME, RHS_JOIN_COL from dj...
0.363195
0.144843
import logging import os import subprocess import sys import threading from typing import Optional, List, Tuple import requests from orangeshare import Config from orangeshare.temp_dir import temp_dir from orangeshare.updater.UpdatePopup import UpdatePopup class Updater: _instance = None @staticmethod ...
orangeshare/updater/__init__.py
import logging import os import subprocess import sys import threading from typing import Optional, List, Tuple import requests from orangeshare import Config from orangeshare.temp_dir import temp_dir from orangeshare.updater.UpdatePopup import UpdatePopup class Updater: _instance = None @staticmethod ...
0.650467
0.204104
from __future__ import print_function import argparse, os, sys, time import numpy as np from hparams import hparams from emotion_inferring.train import er_train HPARAMETER_FILE = '' def get_arguments(hparams): parser = argparse.ArgumentParser( description='Train The Emotion Recognition System') parser.add...
train.py
from __future__ import print_function import argparse, os, sys, time import numpy as np from hparams import hparams from emotion_inferring.train import er_train HPARAMETER_FILE = '' def get_arguments(hparams): parser = argparse.ArgumentParser( description='Train The Emotion Recognition System') parser.add...
0.511717
0.059292
import urllib2 import json from tempfile import TemporaryFile from bz2file import BZ2File from db import database, Change, State from lxml import etree from datetime import datetime NOTES_URI = 'http://planet.openstreetmap.org/notes/planet-notes-latest.osn.bz2' def check_update(): request = urllib2.Request(NOTES...
mmwatch/server/parse_notes.py
import urllib2 import json from tempfile import TemporaryFile from bz2file import BZ2File from db import database, Change, State from lxml import etree from datetime import datetime NOTES_URI = 'http://planet.openstreetmap.org/notes/planet-notes-latest.osn.bz2' def check_update(): request = urllib2.Request(NOTES...
0.19962
0.094135
# lib import random # third party # project class Dice: """Base class for a dice.""" def __init__(self, **kwargs): self.kwargs = kwargs self.rolls = [] self.dice_count = 1 self.roll_count = 1 def roll(self, count=None): """Implement in sub-class""" raise N...
pyprototypr/dice.py
# lib import random # third party # project class Dice: """Base class for a dice.""" def __init__(self, **kwargs): self.kwargs = kwargs self.rolls = [] self.dice_count = 1 self.roll_count = 1 def roll(self, count=None): """Implement in sub-class""" raise N...
0.734215
0.241489
import unittest import mock try: from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( InMemorySpanExporter, ) from openteleme...
tests/_helpers.py
import unittest import mock try: from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( InMemorySpanExporter, ) from openteleme...
0.464902
0.282586
import os from setuptools import find_packages, setup readme = open('README.rst').read() history = open('CHANGES.rst').read() tests_require = [ 'Flask-BabelEx>=0.9.4', 'Flask-Menu>=0.5.0', 'SQLAlchemy-Continuum>=1.2.1', 'check-manifest>=0.25', 'coverage>=4.0', 'invenio-access>=1.2.0', 'in...
setup.py
import os from setuptools import find_packages, setup readme = open('README.rst').read() history = open('CHANGES.rst').read() tests_require = [ 'Flask-BabelEx>=0.9.4', 'Flask-Menu>=0.5.0', 'SQLAlchemy-Continuum>=1.2.1', 'check-manifest>=0.25', 'coverage>=4.0', 'invenio-access>=1.2.0', 'in...
0.308294
0.119897
import os import sys from os.path import basename base_path = tmp_global_obj["basepath"] cur_path = base_path + 'modules' + os.sep + 'zipper' + os.sep + 'libs' + os.sep if cur_path not in sys.path: sys.path.append(cur_path) import pyzipper """ Obtengo el modulo que fueron invocados """ module = GetParams("mo...
__init__.py
import os import sys from os.path import basename base_path = tmp_global_obj["basepath"] cur_path = base_path + 'modules' + os.sep + 'zipper' + os.sep + 'libs' + os.sep if cur_path not in sys.path: sys.path.append(cur_path) import pyzipper """ Obtengo el modulo que fueron invocados """ module = GetParams("mo...
0.159577
0.11004
import json from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.common.abstract_client import AbstractClient from tencentcloud.eiam.v20210420 import models class EiamClient(AbstractClient): _apiVersion = '2021-04-20' _endpoint = 'eiam.tencentcloud...
tencentcloud/eiam/v20210420/eiam_client.py
import json from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.common.abstract_client import AbstractClient from tencentcloud.eiam.v20210420 import models class EiamClient(AbstractClient): _apiVersion = '2021-04-20' _endpoint = 'eiam.tencentcloud...
0.311217
0.043814
import sys import csv import spacy import contractions from wordseg import segment from spacy.tokenizer import Tokenizer def replaceMentions(token, user_mentions): username = None for user in user_mentions: if(user['screen_name'] == token[1:]): username = user['name'] break return username #Tokenizer instr...
4.tweet_preprocessing/tweet_preprocess_part2.py
import sys import csv import spacy import contractions from wordseg import segment from spacy.tokenizer import Tokenizer def replaceMentions(token, user_mentions): username = None for user in user_mentions: if(user['screen_name'] == token[1:]): username = user['name'] break return username #Tokenizer instr...
0.057725
0.127354
import tensorflow as tf import tensorflow_transform as tft from tensorflow.keras.callbacks import TensorBoard from tensorflow_hub import KerasLayer from tensorflow.keras.layers import Dense from tensorflow.keras.models import Sequential from tfx_bsl.tfxio import dataset_options from config import ( HUB_URL, H...
notebooks/tfx_pipelines/guided_projects/guided_project_3_nlp_starter/model.py
import tensorflow as tf import tensorflow_transform as tft from tensorflow.keras.callbacks import TensorBoard from tensorflow_hub import KerasLayer from tensorflow.keras.layers import Dense from tensorflow.keras.models import Sequential from tfx_bsl.tfxio import dataset_options from config import ( HUB_URL, H...
0.850608
0.352007
from pyomo.environ import * model = m = ConcreteModel() m.x2 = Var(within=Reals,bounds=(0.1,3.4),initialize=0.1) m.x3 = Var(within=Reals,bounds=(0.1,3.4),initialize=0.1) m.x4 = Var(within=Reals,bounds=(0.1,3.4),initialize=0.1) m.x5 = Var(within=Reals,bounds=(0.1,3.4),initialize=0.1) m.x6 = Var(within=Reals,bounds=...
tests/examples/minlplib/space25a.py
from pyomo.environ import * model = m = ConcreteModel() m.x2 = Var(within=Reals,bounds=(0.1,3.4),initialize=0.1) m.x3 = Var(within=Reals,bounds=(0.1,3.4),initialize=0.1) m.x4 = Var(within=Reals,bounds=(0.1,3.4),initialize=0.1) m.x5 = Var(within=Reals,bounds=(0.1,3.4),initialize=0.1) m.x6 = Var(within=Reals,bounds=...
0.505127
0.22792
import json import mock from oslo_config import cfg from zake import fake_client from poppy.provider.akamai.mod_san_queue import zookeeper_queue from tests.unit import base AKAMAI_OPTIONS = [ # queue backend configs cfg.StrOpt( 'queue_backend_type', help='SAN Cert Queueing backend'), cf...
tests/unit/provider/akamai/test_mod_san_queue.py
import json import mock from oslo_config import cfg from zake import fake_client from poppy.provider.akamai.mod_san_queue import zookeeper_queue from tests.unit import base AKAMAI_OPTIONS = [ # queue backend configs cfg.StrOpt( 'queue_backend_type', help='SAN Cert Queueing backend'), cf...
0.443841
0.17434
import logging from tool_shed.util import common_util, hg_util, shed_util_common as suc log = logging.getLogger( __name__ ) def get_latest_changeset_revision( app, repository, repo ): repository_tip = repository.tip( app ) repository_metadata = suc.get_repository_metadata_by_changeset_revision( app, ...
lib/tool_shed/util/metadata_util.py
import logging from tool_shed.util import common_util, hg_util, shed_util_common as suc log = logging.getLogger( __name__ ) def get_latest_changeset_revision( app, repository, repo ): repository_tip = repository.tip( app ) repository_metadata = suc.get_repository_metadata_by_changeset_revision( app, ...
0.527317
0.100613
from __future__ import absolute_import, unicode_literals import datetime import logging import time import uuid from io import BytesIO import attr import gevent import requests from celery import Celery from django.conf import settings from django.contrib.auth.models import User from django.core import cache from dja...
corehq/apps/hqadmin/service_checks.py
from __future__ import absolute_import, unicode_literals import datetime import logging import time import uuid from io import BytesIO import attr import gevent import requests from celery import Celery from django.conf import settings from django.contrib.auth.models import User from django.core import cache from dja...
0.475362
0.084833
if not __name__.endswith('.plotting'): raise Exception("Must do 'import psico.plotting' instead of 'run ...'") from pymol import cmd, CmdException def _showfigure(fig, filename, quiet): ''' DESCRIPTION Helper function for plot commands. ''' if filename is None: try: fig.show()...
psico/plotting.py
if not __name__.endswith('.plotting'): raise Exception("Must do 'import psico.plotting' instead of 'run ...'") from pymol import cmd, CmdException def _showfigure(fig, filename, quiet): ''' DESCRIPTION Helper function for plot commands. ''' if filename is None: try: fig.show()...
0.426322
0.385057
import unittest import numpy as np import torch from parameterized import parameterized from monai.transforms import Rand3DElastic TEST_CASES = [ [ { "magnitude_range": (0.3, 2.3), "sigma_range": (1.0, 20.0), "prob": 0.0, "as_tensor_output": False, ...
tests/test_rand_elastic_3d.py
import unittest import numpy as np import torch from parameterized import parameterized from monai.transforms import Rand3DElastic TEST_CASES = [ [ { "magnitude_range": (0.3, 2.3), "sigma_range": (1.0, 20.0), "prob": 0.0, "as_tensor_output": False, ...
0.663669
0.688657
import os import logging import json import webapp2 from google.appengine.api import urlfetch from google.appengine.ext import ndb from google.appengine.ext.webapp import template import models import register_handler BASE_URL = '/contexts/' REGISTER_URL = BASE_URL + 'register' class Context(models.BaseModel): a...
context_store.py
import os import logging import json import webapp2 from google.appengine.api import urlfetch from google.appengine.ext import ndb from google.appengine.ext.webapp import template import models import register_handler BASE_URL = '/contexts/' REGISTER_URL = BASE_URL + 'register' class Context(models.BaseModel): a...
0.223208
0.04778
import re from nonebot import IntentCommand, CommandSession from nalomu.commands import BaseCommand, method_command, method_parser, method_nlp from nalomu.util import is_number from .data_source import NUser, fortune_list, fortune_list_image class UserCommands(BaseCommand): def __init__(self, session: CommandSe...
nalomu/plugins/user/UserCommands.py
import re from nonebot import IntentCommand, CommandSession from nalomu.commands import BaseCommand, method_command, method_parser, method_nlp from nalomu.util import is_number from .data_source import NUser, fortune_list, fortune_list_image class UserCommands(BaseCommand): def __init__(self, session: CommandSe...
0.33372
0.087213
import math, numpy from . import base, configure, modifier, transfer class Layer(base.Net): ''' Base class for all Layers ''' def __init__(self, inputs, outputs, alpha = None): ''' Constructor : param inputs : dimension of input feature space : param outputs : dimension of output feature space : par...
net/layer.py
import math, numpy from . import base, configure, modifier, transfer class Layer(base.Net): ''' Base class for all Layers ''' def __init__(self, inputs, outputs, alpha = None): ''' Constructor : param inputs : dimension of input feature space : param outputs : dimension of output feature space : par...
0.529993
0.47098
import os import argparse def executedSortedGziped(filename,query): if verbose: print(mysql_command_line + query + chromClause + "\" > " + outDir + filename); os.system(mysql_command_line + query + chromClause + "\" > " + outDir + filename); if verbose: print("(head -n 1; sort -k 1,1) < " + outDir + filenam...
cellbase-app/app/bin/ensembl-scripts/variation.py
import os import argparse def executedSortedGziped(filename,query): if verbose: print(mysql_command_line + query + chromClause + "\" > " + outDir + filename); os.system(mysql_command_line + query + chromClause + "\" > " + outDir + filename); if verbose: print("(head -n 1; sort -k 1,1) < " + outDir + filenam...
0.235636
0.075483
import sched import json import time import logging from uk_covid19 import Cov19API import os def parse_csv_data(csv_filename: str) -> list[str]: """ Takes in covid data csv file and returns list of each row as a string Note: Returns the same data format as the parse_json_data function Keyword argumen...
covid_dashboard/covid_data_handler.py
import sched import json import time import logging from uk_covid19 import Cov19API import os def parse_csv_data(csv_filename: str) -> list[str]: """ Takes in covid data csv file and returns list of each row as a string Note: Returns the same data format as the parse_json_data function Keyword argumen...
0.596786
0.412648
import time import os import sys import threading try: import hl_vt100 except ImportError: print "Please install hl_vt100 : " print " -> https://github.com/JulienPalard/vt100-emulator" sys.exit(1) import BaseHTTPServer import SocketServer try: from argparse import ArgumentParser except ImportError: ...
ashttp.py
import time import os import sys import threading try: import hl_vt100 except ImportError: print "Please install hl_vt100 : " print " -> https://github.com/JulienPalard/vt100-emulator" sys.exit(1) import BaseHTTPServer import SocketServer try: from argparse import ArgumentParser except ImportError: ...
0.214034
0.092729
num_list = [0,5,10,15,20,25,30,35,40] del num_list[2:5] # result [0,5,25,30,35,40] print(f'current list is ; {num_list}') ''' Slicing Strings vs. Lists Slicing a list will return a copy of that list and not a reference to the original list. We can see this here: if we assign our list slice to another list, since the l...
src/3-learn-array-sequence-slice.py
num_list = [0,5,10,15,20,25,30,35,40] del num_list[2:5] # result [0,5,25,30,35,40] print(f'current list is ; {num_list}') ''' Slicing Strings vs. Lists Slicing a list will return a copy of that list and not a reference to the original list. We can see this here: if we assign our list slice to another list, since the l...
0.40251
0.494202
from tkinter import Button from btn_funs import create_btn, clear_entry, insert_ans, eval_expression def show_btns(root, input_entry, result_entry): r = 2 c = 0 count = 0 for i in range(0, 13): if c == 3: if count == 0: plus_operator_btn = create_btn(root, input_ent...
btn_wids.py
from tkinter import Button from btn_funs import create_btn, clear_entry, insert_ans, eval_expression def show_btns(root, input_entry, result_entry): r = 2 c = 0 count = 0 for i in range(0, 13): if c == 3: if count == 0: plus_operator_btn = create_btn(root, input_ent...
0.20264
0.115761
class WaterArea(object): def __init__(self, nums): self.nums = nums self.length = len(nums) def find_water_area(self, idx): if idx == 0 or idx == (self.length - 1): return 0 left_idx, left_max = self.get_left_max(idx) right_idx, right_max = self.get_right_ma...
standing_water/brute_force.py
class WaterArea(object): def __init__(self, nums): self.nums = nums self.length = len(nums) def find_water_area(self, idx): if idx == 0 or idx == (self.length - 1): return 0 left_idx, left_max = self.get_left_max(idx) right_idx, right_max = self.get_right_ma...
0.692226
0.378574
决策树一般流程 1、收集数据:可以使用任何方法 2、准备数据:树构造只适用于标称型数据,因此数值型数据必须离散化 3、分析数据:可以使用任何方法,构造树完成之后,我们应该检查图形是否符合预期 4、训练算法:构造树的数据结构 5、测试算法:使用经验树计算错误率 6、使用算法:此步骤可以适用于任何监督学习算法,而使用决策树可以更好的理解数据的内在含义 ''' from math import log class Tree: def __init__(self): pass # 计算给定数据集的香农熵 def calShannonEnt(self,dataSet): numEn...
classification/decision_tree.py
决策树一般流程 1、收集数据:可以使用任何方法 2、准备数据:树构造只适用于标称型数据,因此数值型数据必须离散化 3、分析数据:可以使用任何方法,构造树完成之后,我们应该检查图形是否符合预期 4、训练算法:构造树的数据结构 5、测试算法:使用经验树计算错误率 6、使用算法:此步骤可以适用于任何监督学习算法,而使用决策树可以更好的理解数据的内在含义 ''' from math import log class Tree: def __init__(self): pass # 计算给定数据集的香农熵 def calShannonEnt(self,dataSet): numEn...
0.233357
0.631765
import logging from services.common import pusher as push_service from services.leop.jrpc.serializers import launch as launch_serial from services.leop.jrpc.serializers import messages as message_serializers logger = logging.getLogger('leop') class LaunchPush(object): """Push service Object that contains a ...
services/leop/push.py
import logging from services.common import pusher as push_service from services.leop.jrpc.serializers import launch as launch_serial from services.leop.jrpc.serializers import messages as message_serializers logger = logging.getLogger('leop') class LaunchPush(object): """Push service Object that contains a ...
0.674265
0.220321